ARMFrameLowering.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671
  1. //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the ARM implementation of TargetFrameLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ARMFrameLowering.h"
  13. #include "ARMBaseInstrInfo.h"
  14. #include "ARMBaseRegisterInfo.h"
  15. #include "ARMConstantPoolValue.h"
  16. #include "ARMMachineFunctionInfo.h"
  17. #include "ARMSubtarget.h"
  18. #include "MCTargetDesc/ARMAddressingModes.h"
  19. #include "MCTargetDesc/ARMBaseInfo.h"
  20. #include "Utils/ARMBaseInfo.h"
  21. #include "llvm/ADT/BitVector.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/CodeGen/MachineBasicBlock.h"
  26. #include "llvm/CodeGen/MachineConstantPool.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineInstr.h"
  30. #include "llvm/CodeGen/MachineInstrBuilder.h"
  31. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineOperand.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/RegisterScavenging.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. #include "llvm/CodeGen/TargetOpcodes.h"
  38. #include "llvm/CodeGen/TargetRegisterInfo.h"
  39. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  40. #include "llvm/IR/Attributes.h"
  41. #include "llvm/IR/CallingConv.h"
  42. #include "llvm/IR/DebugLoc.h"
  43. #include "llvm/IR/Function.h"
  44. #include "llvm/MC/MCContext.h"
  45. #include "llvm/MC/MCDwarf.h"
  46. #include "llvm/MC/MCInstrDesc.h"
  47. #include "llvm/MC/MCRegisterInfo.h"
  48. #include "llvm/Support/CodeGen.h"
  49. #include "llvm/Support/CommandLine.h"
  50. #include "llvm/Support/Compiler.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/ErrorHandling.h"
  53. #include "llvm/Support/MathExtras.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Target/TargetMachine.h"
  56. #include "llvm/Target/TargetOptions.h"
  57. #include <algorithm>
  58. #include <cassert>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <iterator>
  62. #include <utility>
  63. #include <vector>
  64. #define DEBUG_TYPE "arm-frame-lowering"
  65. using namespace llvm;
  66. static cl::opt<bool>
  67. SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
  68. cl::desc("Align ARM NEON spills in prolog and epilog"));
  69. static MachineBasicBlock::iterator
  70. skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
  71. unsigned NumAlignedDPRCS2Regs);
  72. ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
  73. : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
  74. STI(sti) {}
  75. bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
  76. // iOS always has a FP for backtracking, force other targets to keep their FP
  77. // when doing FastISel. The emitted code is currently superior, and in cases
  78. // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
  79. return MF.getSubtarget<ARMSubtarget>().useFastISel();
  80. }
  81. /// Returns true if the target can safely skip saving callee-saved registers
  82. /// for noreturn nounwind functions.
  83. bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
  84. assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
  85. MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
  86. !MF.getFunction().hasFnAttribute(Attribute::UWTable));
  87. // Frame pointer and link register are not treated as normal CSR, thus we
  88. // can always skip CSR saves for nonreturning functions.
  89. return true;
  90. }
  91. /// hasFP - Return true if the specified function should have a dedicated frame
  92. /// pointer register. This is true if the function has variable sized allocas
  93. /// or if frame pointer elimination is disabled.
  94. bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
  95. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  96. const MachineFrameInfo &MFI = MF.getFrameInfo();
  97. // ABI-required frame pointer.
  98. if (MF.getTarget().Options.DisableFramePointerElim(MF))
  99. return true;
  100. // Frame pointer required for use within this function.
  101. return (RegInfo->needsStackRealignment(MF) ||
  102. MFI.hasVarSizedObjects() ||
  103. MFI.isFrameAddressTaken());
  104. }
  105. /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
  106. /// not required, we reserve argument space for call sites in the function
  107. /// immediately on entry to the current function. This eliminates the need for
  108. /// add/sub sp brackets around call sites. Returns true if the call frame is
  109. /// included as part of the stack frame.
  110. bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
  111. const MachineFrameInfo &MFI = MF.getFrameInfo();
  112. unsigned CFSize = MFI.getMaxCallFrameSize();
  113. // It's not always a good idea to include the call frame as part of the
  114. // stack frame. ARM (especially Thumb) has small immediate offset to
  115. // address the stack frame. So a large call frame can cause poor codegen
  116. // and may even makes it impossible to scavenge a register.
  117. if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
  118. return false;
  119. return !MFI.hasVarSizedObjects();
  120. }
  121. /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
  122. /// call frame pseudos can be simplified. Unlike most targets, having a FP
  123. /// is not sufficient here since we still may reference some objects via SP
  124. /// even when FP is available in Thumb2 mode.
  125. bool
  126. ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
  127. return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
  128. }
  129. static void emitRegPlusImmediate(
  130. bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
  131. const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
  132. unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
  133. ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
  134. if (isARM)
  135. emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
  136. Pred, PredReg, TII, MIFlags);
  137. else
  138. emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
  139. Pred, PredReg, TII, MIFlags);
  140. }
  141. static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
  142. MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
  143. const ARMBaseInstrInfo &TII, int NumBytes,
  144. unsigned MIFlags = MachineInstr::NoFlags,
  145. ARMCC::CondCodes Pred = ARMCC::AL,
  146. unsigned PredReg = 0) {
  147. emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
  148. MIFlags, Pred, PredReg);
  149. }
  150. static int sizeOfSPAdjustment(const MachineInstr &MI) {
  151. int RegSize;
  152. switch (MI.getOpcode()) {
  153. case ARM::VSTMDDB_UPD:
  154. RegSize = 8;
  155. break;
  156. case ARM::STMDB_UPD:
  157. case ARM::t2STMDB_UPD:
  158. RegSize = 4;
  159. break;
  160. case ARM::t2STR_PRE:
  161. case ARM::STR_PRE_IMM:
  162. return 4;
  163. default:
  164. llvm_unreachable("Unknown push or pop like instruction");
  165. }
  166. int count = 0;
  167. // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
  168. // pred) so the list starts at 4.
  169. for (int i = MI.getNumOperands() - 1; i >= 4; --i)
  170. count += RegSize;
  171. return count;
  172. }
  173. static bool WindowsRequiresStackProbe(const MachineFunction &MF,
  174. size_t StackSizeInBytes) {
  175. const MachineFrameInfo &MFI = MF.getFrameInfo();
  176. const Function &F = MF.getFunction();
  177. unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
  178. if (F.hasFnAttribute("stack-probe-size"))
  179. F.getFnAttribute("stack-probe-size")
  180. .getValueAsString()
  181. .getAsInteger(0, StackProbeSize);
  182. return (StackSizeInBytes >= StackProbeSize) &&
  183. !F.hasFnAttribute("no-stack-arg-probe");
  184. }
  185. namespace {
  186. struct StackAdjustingInsts {
  187. struct InstInfo {
  188. MachineBasicBlock::iterator I;
  189. unsigned SPAdjust;
  190. bool BeforeFPSet;
  191. };
  192. SmallVector<InstInfo, 4> Insts;
  193. void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
  194. bool BeforeFPSet = false) {
  195. InstInfo Info = {I, SPAdjust, BeforeFPSet};
  196. Insts.push_back(Info);
  197. }
  198. void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
  199. auto Info =
  200. llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
  201. assert(Info != Insts.end() && "invalid sp adjusting instruction");
  202. Info->SPAdjust += ExtraBytes;
  203. }
  204. void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
  205. const ARMBaseInstrInfo &TII, bool HasFP) {
  206. MachineFunction &MF = *MBB.getParent();
  207. unsigned CFAOffset = 0;
  208. for (auto &Info : Insts) {
  209. if (HasFP && !Info.BeforeFPSet)
  210. return;
  211. CFAOffset += Info.SPAdjust;
  212. unsigned CFIIndex = MF.addFrameInst(
  213. MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
  214. BuildMI(MBB, std::next(Info.I), dl,
  215. TII.get(TargetOpcode::CFI_INSTRUCTION))
  216. .addCFIIndex(CFIIndex)
  217. .setMIFlags(MachineInstr::FrameSetup);
  218. }
  219. }
  220. };
  221. } // end anonymous namespace
  222. /// Emit an instruction sequence that will align the address in
  223. /// register Reg by zero-ing out the lower bits. For versions of the
  224. /// architecture that support Neon, this must be done in a single
  225. /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
  226. /// single instruction. That function only gets called when optimizing
  227. /// spilling of D registers on a core with the Neon instruction set
  228. /// present.
  229. static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
  230. const TargetInstrInfo &TII,
  231. MachineBasicBlock &MBB,
  232. MachineBasicBlock::iterator MBBI,
  233. const DebugLoc &DL, const unsigned Reg,
  234. const Align Alignment,
  235. const bool MustBeSingleInstruction) {
  236. const ARMSubtarget &AST =
  237. static_cast<const ARMSubtarget &>(MF.getSubtarget());
  238. const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
  239. const unsigned AlignMask = Alignment.value() - 1U;
  240. const unsigned NrBitsToZero = Log2(Alignment);
  241. assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
  242. if (!AFI->isThumbFunction()) {
  243. // if the BFC instruction is available, use that to zero the lower
  244. // bits:
  245. // bfc Reg, #0, log2(Alignment)
  246. // otherwise use BIC, if the mask to zero the required number of bits
  247. // can be encoded in the bic immediate field
  248. // bic Reg, Reg, Alignment-1
  249. // otherwise, emit
  250. // lsr Reg, Reg, log2(Alignment)
  251. // lsl Reg, Reg, log2(Alignment)
  252. if (CanUseBFC) {
  253. BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
  254. .addReg(Reg, RegState::Kill)
  255. .addImm(~AlignMask)
  256. .add(predOps(ARMCC::AL));
  257. } else if (AlignMask <= 255) {
  258. BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
  259. .addReg(Reg, RegState::Kill)
  260. .addImm(AlignMask)
  261. .add(predOps(ARMCC::AL))
  262. .add(condCodeOp());
  263. } else {
  264. assert(!MustBeSingleInstruction &&
  265. "Shouldn't call emitAligningInstructions demanding a single "
  266. "instruction to be emitted for large stack alignment for a target "
  267. "without BFC.");
  268. BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
  269. .addReg(Reg, RegState::Kill)
  270. .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
  271. .add(predOps(ARMCC::AL))
  272. .add(condCodeOp());
  273. BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
  274. .addReg(Reg, RegState::Kill)
  275. .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
  276. .add(predOps(ARMCC::AL))
  277. .add(condCodeOp());
  278. }
  279. } else {
  280. // Since this is only reached for Thumb-2 targets, the BFC instruction
  281. // should always be available.
  282. assert(CanUseBFC);
  283. BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
  284. .addReg(Reg, RegState::Kill)
  285. .addImm(~AlignMask)
  286. .add(predOps(ARMCC::AL));
  287. }
  288. }
  289. /// We need the offset of the frame pointer relative to other MachineFrameInfo
  290. /// offsets which are encoded relative to SP at function begin.
  291. /// See also emitPrologue() for how the FP is set up.
  292. /// Unfortunately we cannot determine this value in determineCalleeSaves() yet
  293. /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
  294. /// this to produce a conservative estimate that we check in an assert() later.
  295. static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI) {
  296. // For Thumb1, push.w isn't available, so the first push will always push
  297. // r7 and lr onto the stack first.
  298. if (AFI.isThumb1OnlyFunction())
  299. return -AFI.getArgRegsSaveSize() - (2 * 4);
  300. // This is a conservative estimation: Assume the frame pointer being r7 and
  301. // pc("r15") up to r8 getting spilled before (= 8 registers).
  302. int FPCXTSaveSize = (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0;
  303. return - FPCXTSaveSize - AFI.getArgRegsSaveSize() - (8 * 4);
  304. }
  305. void ARMFrameLowering::emitPrologue(MachineFunction &MF,
  306. MachineBasicBlock &MBB) const {
  307. MachineBasicBlock::iterator MBBI = MBB.begin();
  308. MachineFrameInfo &MFI = MF.getFrameInfo();
  309. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  310. MachineModuleInfo &MMI = MF.getMMI();
  311. MCContext &Context = MMI.getContext();
  312. const TargetMachine &TM = MF.getTarget();
  313. const MCRegisterInfo *MRI = Context.getRegisterInfo();
  314. const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
  315. const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
  316. assert(!AFI->isThumb1OnlyFunction() &&
  317. "This emitPrologue does not support Thumb1!");
  318. bool isARM = !AFI->isThumbFunction();
  319. Align Alignment = STI.getFrameLowering()->getStackAlign();
  320. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
  321. unsigned NumBytes = MFI.getStackSize();
  322. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  323. int FPCXTSaveSize = 0;
  324. // Debug location must be unknown since the first debug location is used
  325. // to determine the end of the prologue.
  326. DebugLoc dl;
  327. Register FramePtr = RegInfo->getFrameRegister(MF);
  328. // Determine the sizes of each callee-save spill areas and record which frame
  329. // belongs to which callee-save spill areas.
  330. unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
  331. int FramePtrSpillFI = 0;
  332. int D8SpillFI = 0;
  333. // All calls are tail calls in GHC calling conv, and functions have no
  334. // prologue/epilogue.
  335. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  336. return;
  337. StackAdjustingInsts DefCFAOffsetCandidates;
  338. bool HasFP = hasFP(MF);
  339. // Allocate the vararg register save area.
  340. if (ArgRegsSaveSize) {
  341. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
  342. MachineInstr::FrameSetup);
  343. DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
  344. }
  345. if (!AFI->hasStackFrame() &&
  346. (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
  347. if (NumBytes - ArgRegsSaveSize != 0) {
  348. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
  349. MachineInstr::FrameSetup);
  350. DefCFAOffsetCandidates.addInst(std::prev(MBBI),
  351. NumBytes - ArgRegsSaveSize, true);
  352. }
  353. DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
  354. return;
  355. }
  356. // Determine spill area sizes.
  357. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  358. unsigned Reg = CSI[i].getReg();
  359. int FI = CSI[i].getFrameIdx();
  360. switch (Reg) {
  361. case ARM::R8:
  362. case ARM::R9:
  363. case ARM::R10:
  364. case ARM::R11:
  365. case ARM::R12:
  366. if (STI.splitFramePushPop(MF)) {
  367. GPRCS2Size += 4;
  368. break;
  369. }
  370. LLVM_FALLTHROUGH;
  371. case ARM::R0:
  372. case ARM::R1:
  373. case ARM::R2:
  374. case ARM::R3:
  375. case ARM::R4:
  376. case ARM::R5:
  377. case ARM::R6:
  378. case ARM::R7:
  379. case ARM::LR:
  380. if (Reg == FramePtr)
  381. FramePtrSpillFI = FI;
  382. GPRCS1Size += 4;
  383. break;
  384. case ARM::FPCXTNS:
  385. FPCXTSaveSize = 4;
  386. break;
  387. default:
  388. // This is a DPR. Exclude the aligned DPRCS2 spills.
  389. if (Reg == ARM::D8)
  390. D8SpillFI = FI;
  391. if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
  392. DPRCSSize += 8;
  393. }
  394. }
  395. // Move past FPCXT area.
  396. MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
  397. if (FPCXTSaveSize > 0) {
  398. LastPush = MBBI++;
  399. DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, true);
  400. }
  401. // Move past area 1.
  402. if (GPRCS1Size > 0) {
  403. GPRCS1Push = LastPush = MBBI++;
  404. DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
  405. }
  406. // Determine starting offsets of spill areas.
  407. unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize;
  408. unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size;
  409. unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
  410. Align DPRAlign = DPRCSSize ? std::min(Align(8), Alignment) : Align(4);
  411. unsigned DPRGapSize =
  412. (GPRCS1Size + GPRCS2Size + FPCXTSaveSize + ArgRegsSaveSize) %
  413. DPRAlign.value();
  414. unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
  415. int FramePtrOffsetInPush = 0;
  416. if (HasFP) {
  417. int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
  418. assert(getMaxFPOffset(STI, *AFI) <= FPOffset &&
  419. "Max FP estimation is wrong");
  420. FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize + FPCXTSaveSize;
  421. AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
  422. NumBytes);
  423. }
  424. AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
  425. AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
  426. AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
  427. // Move past area 2.
  428. if (GPRCS2Size > 0) {
  429. GPRCS2Push = LastPush = MBBI++;
  430. DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
  431. }
  432. // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
  433. // .cfi_offset operations will reflect that.
  434. if (DPRGapSize) {
  435. assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
  436. if (LastPush != MBB.end() &&
  437. tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
  438. DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
  439. else {
  440. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
  441. MachineInstr::FrameSetup);
  442. DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
  443. }
  444. }
  445. // Move past area 3.
  446. if (DPRCSSize > 0) {
  447. // Since vpush register list cannot have gaps, there may be multiple vpush
  448. // instructions in the prologue.
  449. while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
  450. DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
  451. LastPush = MBBI++;
  452. }
  453. }
  454. // Move past the aligned DPRCS2 area.
  455. if (AFI->getNumAlignedDPRCS2Regs() > 0) {
  456. MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
  457. // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
  458. // leaves the stack pointer pointing to the DPRCS2 area.
  459. //
  460. // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
  461. NumBytes += MFI.getObjectOffset(D8SpillFI);
  462. } else
  463. NumBytes = DPRCSOffset;
  464. if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
  465. uint32_t NumWords = NumBytes >> 2;
  466. if (NumWords < 65536)
  467. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
  468. .addImm(NumWords)
  469. .setMIFlags(MachineInstr::FrameSetup)
  470. .add(predOps(ARMCC::AL));
  471. else
  472. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
  473. .addImm(NumWords)
  474. .setMIFlags(MachineInstr::FrameSetup);
  475. switch (TM.getCodeModel()) {
  476. case CodeModel::Tiny:
  477. llvm_unreachable("Tiny code model not available on ARM.");
  478. case CodeModel::Small:
  479. case CodeModel::Medium:
  480. case CodeModel::Kernel:
  481. BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
  482. .add(predOps(ARMCC::AL))
  483. .addExternalSymbol("__chkstk")
  484. .addReg(ARM::R4, RegState::Implicit)
  485. .setMIFlags(MachineInstr::FrameSetup);
  486. break;
  487. case CodeModel::Large:
  488. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
  489. .addExternalSymbol("__chkstk")
  490. .setMIFlags(MachineInstr::FrameSetup);
  491. BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
  492. .add(predOps(ARMCC::AL))
  493. .addReg(ARM::R12, RegState::Kill)
  494. .addReg(ARM::R4, RegState::Implicit)
  495. .setMIFlags(MachineInstr::FrameSetup);
  496. break;
  497. }
  498. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
  499. .addReg(ARM::SP, RegState::Kill)
  500. .addReg(ARM::R4, RegState::Kill)
  501. .setMIFlags(MachineInstr::FrameSetup)
  502. .add(predOps(ARMCC::AL))
  503. .add(condCodeOp());
  504. NumBytes = 0;
  505. }
  506. if (NumBytes) {
  507. // Adjust SP after all the callee-save spills.
  508. if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
  509. tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
  510. DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
  511. else {
  512. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
  513. MachineInstr::FrameSetup);
  514. DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
  515. }
  516. if (HasFP && isARM)
  517. // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
  518. // Note it's not safe to do this in Thumb2 mode because it would have
  519. // taken two instructions:
  520. // mov sp, r7
  521. // sub sp, #24
  522. // If an interrupt is taken between the two instructions, then sp is in
  523. // an inconsistent state (pointing to the middle of callee-saved area).
  524. // The interrupt handler can end up clobbering the registers.
  525. AFI->setShouldRestoreSPFromFP(true);
  526. }
  527. // Set FP to point to the stack slot that contains the previous FP.
  528. // For iOS, FP is R7, which has now been stored in spill area 1.
  529. // Otherwise, if this is not iOS, all the callee-saved registers go
  530. // into spill area 1, including the FP in R11. In either case, it
  531. // is in area one and the adjustment needs to take place just after
  532. // that push.
  533. if (HasFP) {
  534. MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
  535. unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
  536. emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
  537. dl, TII, FramePtr, ARM::SP,
  538. PushSize + FramePtrOffsetInPush,
  539. MachineInstr::FrameSetup);
  540. if (FramePtrOffsetInPush + PushSize != 0) {
  541. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
  542. nullptr, MRI->getDwarfRegNum(FramePtr, true),
  543. FPCXTSaveSize + ArgRegsSaveSize - FramePtrOffsetInPush));
  544. BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  545. .addCFIIndex(CFIIndex)
  546. .setMIFlags(MachineInstr::FrameSetup);
  547. } else {
  548. unsigned CFIIndex =
  549. MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
  550. nullptr, MRI->getDwarfRegNum(FramePtr, true)));
  551. BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  552. .addCFIIndex(CFIIndex)
  553. .setMIFlags(MachineInstr::FrameSetup);
  554. }
  555. }
  556. // Now that the prologue's actual instructions are finalised, we can insert
  557. // the necessary DWARF cf instructions to describe the situation. Start by
  558. // recording where each register ended up:
  559. if (GPRCS1Size > 0) {
  560. MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
  561. int CFIIndex;
  562. for (const auto &Entry : CSI) {
  563. unsigned Reg = Entry.getReg();
  564. int FI = Entry.getFrameIdx();
  565. switch (Reg) {
  566. case ARM::R8:
  567. case ARM::R9:
  568. case ARM::R10:
  569. case ARM::R11:
  570. case ARM::R12:
  571. if (STI.splitFramePushPop(MF))
  572. break;
  573. LLVM_FALLTHROUGH;
  574. case ARM::R0:
  575. case ARM::R1:
  576. case ARM::R2:
  577. case ARM::R3:
  578. case ARM::R4:
  579. case ARM::R5:
  580. case ARM::R6:
  581. case ARM::R7:
  582. case ARM::LR:
  583. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  584. nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
  585. BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  586. .addCFIIndex(CFIIndex)
  587. .setMIFlags(MachineInstr::FrameSetup);
  588. break;
  589. }
  590. }
  591. }
  592. if (GPRCS2Size > 0) {
  593. MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
  594. for (const auto &Entry : CSI) {
  595. unsigned Reg = Entry.getReg();
  596. int FI = Entry.getFrameIdx();
  597. switch (Reg) {
  598. case ARM::R8:
  599. case ARM::R9:
  600. case ARM::R10:
  601. case ARM::R11:
  602. case ARM::R12:
  603. if (STI.splitFramePushPop(MF)) {
  604. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  605. unsigned Offset = MFI.getObjectOffset(FI);
  606. unsigned CFIIndex = MF.addFrameInst(
  607. MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
  608. BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  609. .addCFIIndex(CFIIndex)
  610. .setMIFlags(MachineInstr::FrameSetup);
  611. }
  612. break;
  613. }
  614. }
  615. }
  616. if (DPRCSSize > 0) {
  617. // Since vpush register list cannot have gaps, there may be multiple vpush
  618. // instructions in the prologue.
  619. MachineBasicBlock::iterator Pos = std::next(LastPush);
  620. for (const auto &Entry : CSI) {
  621. unsigned Reg = Entry.getReg();
  622. int FI = Entry.getFrameIdx();
  623. if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
  624. (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
  625. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  626. unsigned Offset = MFI.getObjectOffset(FI);
  627. unsigned CFIIndex = MF.addFrameInst(
  628. MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
  629. BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  630. .addCFIIndex(CFIIndex)
  631. .setMIFlags(MachineInstr::FrameSetup);
  632. }
  633. }
  634. }
  635. // Now we can emit descriptions of where the canonical frame address was
  636. // throughout the process. If we have a frame pointer, it takes over the job
  637. // half-way through, so only the first few .cfi_def_cfa_offset instructions
  638. // actually get emitted.
  639. DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
  640. if (STI.isTargetELF() && hasFP(MF))
  641. MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
  642. AFI->getFramePtrSpillOffset());
  643. AFI->setFPCXTSaveAreaSize(FPCXTSaveSize);
  644. AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
  645. AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
  646. AFI->setDPRCalleeSavedGapSize(DPRGapSize);
  647. AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
  648. // If we need dynamic stack realignment, do it here. Be paranoid and make
  649. // sure if we also have VLAs, we have a base pointer for frame access.
  650. // If aligned NEON registers were spilled, the stack has already been
  651. // realigned.
  652. if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
  653. Align MaxAlign = MFI.getMaxAlign();
  654. assert(!AFI->isThumb1OnlyFunction());
  655. if (!AFI->isThumbFunction()) {
  656. emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
  657. false);
  658. } else {
  659. // We cannot use sp as source/dest register here, thus we're using r4 to
  660. // perform the calculations. We're emitting the following sequence:
  661. // mov r4, sp
  662. // -- use emitAligningInstructions to produce best sequence to zero
  663. // -- out lower bits in r4
  664. // mov sp, r4
  665. // FIXME: It will be better just to find spare register here.
  666. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
  667. .addReg(ARM::SP, RegState::Kill)
  668. .add(predOps(ARMCC::AL));
  669. emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
  670. false);
  671. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  672. .addReg(ARM::R4, RegState::Kill)
  673. .add(predOps(ARMCC::AL));
  674. }
  675. AFI->setShouldRestoreSPFromFP(true);
  676. }
  677. // If we need a base pointer, set it up here. It's whatever the value
  678. // of the stack pointer is at this point. Any variable size objects
  679. // will be allocated after this, so we can still use the base pointer
  680. // to reference locals.
  681. // FIXME: Clarify FrameSetup flags here.
  682. if (RegInfo->hasBasePointer(MF)) {
  683. if (isARM)
  684. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
  685. .addReg(ARM::SP)
  686. .add(predOps(ARMCC::AL))
  687. .add(condCodeOp());
  688. else
  689. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
  690. .addReg(ARM::SP)
  691. .add(predOps(ARMCC::AL));
  692. }
  693. // If the frame has variable sized objects then the epilogue must restore
  694. // the sp from fp. We can assume there's an FP here since hasFP already
  695. // checks for hasVarSizedObjects.
  696. if (MFI.hasVarSizedObjects())
  697. AFI->setShouldRestoreSPFromFP(true);
  698. }
  699. void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
  700. MachineBasicBlock &MBB) const {
  701. MachineFrameInfo &MFI = MF.getFrameInfo();
  702. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  703. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  704. const ARMBaseInstrInfo &TII =
  705. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  706. assert(!AFI->isThumb1OnlyFunction() &&
  707. "This emitEpilogue does not support Thumb1!");
  708. bool isARM = !AFI->isThumbFunction();
  709. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
  710. int NumBytes = (int)MFI.getStackSize();
  711. Register FramePtr = RegInfo->getFrameRegister(MF);
  712. // All calls are tail calls in GHC calling conv, and functions have no
  713. // prologue/epilogue.
  714. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  715. return;
  716. // First put ourselves on the first (from top) terminator instructions.
  717. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  718. DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
  719. if (!AFI->hasStackFrame()) {
  720. if (NumBytes - ArgRegsSaveSize != 0)
  721. emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize,
  722. MachineInstr::FrameDestroy);
  723. } else {
  724. // Unwind MBBI to point to first LDR / VLDRD.
  725. if (MBBI != MBB.begin()) {
  726. do {
  727. --MBBI;
  728. } while (MBBI != MBB.begin() &&
  729. MBBI->getFlag(MachineInstr::FrameDestroy));
  730. if (!MBBI->getFlag(MachineInstr::FrameDestroy))
  731. ++MBBI;
  732. }
  733. // Move SP to start of FP callee save spill area.
  734. NumBytes -= (ArgRegsSaveSize +
  735. AFI->getFPCXTSaveAreaSize() +
  736. AFI->getGPRCalleeSavedArea1Size() +
  737. AFI->getGPRCalleeSavedArea2Size() +
  738. AFI->getDPRCalleeSavedGapSize() +
  739. AFI->getDPRCalleeSavedAreaSize());
  740. // Reset SP based on frame pointer only if the stack frame extends beyond
  741. // frame pointer stack slot or target is ELF and the function has FP.
  742. if (AFI->shouldRestoreSPFromFP()) {
  743. NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
  744. if (NumBytes) {
  745. if (isARM)
  746. emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
  747. ARMCC::AL, 0, TII,
  748. MachineInstr::FrameDestroy);
  749. else {
  750. // It's not possible to restore SP from FP in a single instruction.
  751. // For iOS, this looks like:
  752. // mov sp, r7
  753. // sub sp, #24
  754. // This is bad, if an interrupt is taken after the mov, sp is in an
  755. // inconsistent state.
  756. // Use the first callee-saved register as a scratch register.
  757. assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
  758. "No scratch register to restore SP from FP!");
  759. emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
  760. ARMCC::AL, 0, TII, MachineInstr::FrameDestroy);
  761. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  762. .addReg(ARM::R4)
  763. .add(predOps(ARMCC::AL))
  764. .setMIFlag(MachineInstr::FrameDestroy);
  765. }
  766. } else {
  767. // Thumb2 or ARM.
  768. if (isARM)
  769. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
  770. .addReg(FramePtr)
  771. .add(predOps(ARMCC::AL))
  772. .add(condCodeOp())
  773. .setMIFlag(MachineInstr::FrameDestroy);
  774. else
  775. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  776. .addReg(FramePtr)
  777. .add(predOps(ARMCC::AL))
  778. .setMIFlag(MachineInstr::FrameDestroy);
  779. }
  780. } else if (NumBytes &&
  781. !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
  782. emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
  783. MachineInstr::FrameDestroy);
  784. // Increment past our save areas.
  785. if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
  786. MBBI++;
  787. // Since vpop register list cannot have gaps, there may be multiple vpop
  788. // instructions in the epilogue.
  789. while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
  790. MBBI++;
  791. }
  792. if (AFI->getDPRCalleeSavedGapSize()) {
  793. assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
  794. "unexpected DPR alignment gap");
  795. emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(),
  796. MachineInstr::FrameDestroy);
  797. }
  798. if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
  799. if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
  800. if (AFI->getFPCXTSaveAreaSize()) MBBI++;
  801. }
  802. if (ArgRegsSaveSize)
  803. emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize,
  804. MachineInstr::FrameDestroy);
  805. }
  806. /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
  807. /// debug info. It's the same as what we use for resolving the code-gen
  808. /// references for now. FIXME: This can go wrong when references are
  809. /// SP-relative and simple call frames aren't used.
  810. StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF,
  811. int FI,
  812. Register &FrameReg) const {
  813. return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0));
  814. }
  815. int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
  816. int FI, Register &FrameReg,
  817. int SPAdj) const {
  818. const MachineFrameInfo &MFI = MF.getFrameInfo();
  819. const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
  820. MF.getSubtarget().getRegisterInfo());
  821. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  822. int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
  823. int FPOffset = Offset - AFI->getFramePtrSpillOffset();
  824. bool isFixed = MFI.isFixedObjectIndex(FI);
  825. FrameReg = ARM::SP;
  826. Offset += SPAdj;
  827. // SP can move around if there are allocas. We may also lose track of SP
  828. // when emergency spilling inside a non-reserved call frame setup.
  829. bool hasMovingSP = !hasReservedCallFrame(MF);
  830. // When dynamically realigning the stack, use the frame pointer for
  831. // parameters, and the stack/base pointer for locals.
  832. if (RegInfo->needsStackRealignment(MF)) {
  833. assert(hasFP(MF) && "dynamic stack realignment without a FP!");
  834. if (isFixed) {
  835. FrameReg = RegInfo->getFrameRegister(MF);
  836. Offset = FPOffset;
  837. } else if (hasMovingSP) {
  838. assert(RegInfo->hasBasePointer(MF) &&
  839. "VLAs and dynamic stack alignment, but missing base pointer!");
  840. FrameReg = RegInfo->getBaseRegister();
  841. Offset -= SPAdj;
  842. }
  843. return Offset;
  844. }
  845. // If there is a frame pointer, use it when we can.
  846. if (hasFP(MF) && AFI->hasStackFrame()) {
  847. // Use frame pointer to reference fixed objects. Use it for locals if
  848. // there are VLAs (and thus the SP isn't reliable as a base).
  849. if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
  850. FrameReg = RegInfo->getFrameRegister(MF);
  851. return FPOffset;
  852. } else if (hasMovingSP) {
  853. assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
  854. if (AFI->isThumb2Function()) {
  855. // Try to use the frame pointer if we can, else use the base pointer
  856. // since it's available. This is handy for the emergency spill slot, in
  857. // particular.
  858. if (FPOffset >= -255 && FPOffset < 0) {
  859. FrameReg = RegInfo->getFrameRegister(MF);
  860. return FPOffset;
  861. }
  862. }
  863. } else if (AFI->isThumbFunction()) {
  864. // Prefer SP to base pointer, if the offset is suitably aligned and in
  865. // range as the effective range of the immediate offset is bigger when
  866. // basing off SP.
  867. // Use add <rd>, sp, #<imm8>
  868. // ldr <rd>, [sp, #<imm8>]
  869. if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
  870. return Offset;
  871. // In Thumb2 mode, the negative offset is very limited. Try to avoid
  872. // out of range references. ldr <rt>,[<rn>, #-<imm8>]
  873. if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
  874. FrameReg = RegInfo->getFrameRegister(MF);
  875. return FPOffset;
  876. }
  877. } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
  878. // Otherwise, use SP or FP, whichever is closer to the stack slot.
  879. FrameReg = RegInfo->getFrameRegister(MF);
  880. return FPOffset;
  881. }
  882. }
  883. // Use the base pointer if we have one.
  884. // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
  885. // That can happen if we forced a base pointer for a large call frame.
  886. if (RegInfo->hasBasePointer(MF)) {
  887. FrameReg = RegInfo->getBaseRegister();
  888. Offset -= SPAdj;
  889. }
  890. return Offset;
  891. }
  892. void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
  893. MachineBasicBlock::iterator MI,
  894. ArrayRef<CalleeSavedInfo> CSI,
  895. unsigned StmOpc, unsigned StrOpc,
  896. bool NoGap, bool (*Func)(unsigned, bool),
  897. unsigned NumAlignedDPRCS2Regs,
  898. unsigned MIFlags) const {
  899. MachineFunction &MF = *MBB.getParent();
  900. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  901. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  902. DebugLoc DL;
  903. using RegAndKill = std::pair<unsigned, bool>;
  904. SmallVector<RegAndKill, 4> Regs;
  905. unsigned i = CSI.size();
  906. while (i != 0) {
  907. unsigned LastReg = 0;
  908. for (; i != 0; --i) {
  909. unsigned Reg = CSI[i-1].getReg();
  910. if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
  911. // D-registers in the aligned area DPRCS2 are NOT spilled here.
  912. if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
  913. continue;
  914. const MachineRegisterInfo &MRI = MF.getRegInfo();
  915. bool isLiveIn = MRI.isLiveIn(Reg);
  916. if (!isLiveIn && !MRI.isReserved(Reg))
  917. MBB.addLiveIn(Reg);
  918. // If NoGap is true, push consecutive registers and then leave the rest
  919. // for other instructions. e.g.
  920. // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
  921. if (NoGap && LastReg && LastReg != Reg-1)
  922. break;
  923. LastReg = Reg;
  924. // Do not set a kill flag on values that are also marked as live-in. This
  925. // happens with the @llvm-returnaddress intrinsic and with arguments
  926. // passed in callee saved registers.
  927. // Omitting the kill flags is conservatively correct even if the live-in
  928. // is not used after all.
  929. Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
  930. }
  931. if (Regs.empty())
  932. continue;
  933. llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
  934. return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
  935. });
  936. if (Regs.size() > 1 || StrOpc== 0) {
  937. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
  938. .addReg(ARM::SP)
  939. .setMIFlags(MIFlags)
  940. .add(predOps(ARMCC::AL));
  941. for (unsigned i = 0, e = Regs.size(); i < e; ++i)
  942. MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
  943. } else if (Regs.size() == 1) {
  944. BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
  945. .addReg(Regs[0].first, getKillRegState(Regs[0].second))
  946. .addReg(ARM::SP)
  947. .setMIFlags(MIFlags)
  948. .addImm(-4)
  949. .add(predOps(ARMCC::AL));
  950. }
  951. Regs.clear();
  952. // Put any subsequent vpush instructions before this one: they will refer to
  953. // higher register numbers so need to be pushed first in order to preserve
  954. // monotonicity.
  955. if (MI != MBB.begin())
  956. --MI;
  957. }
  958. }
  959. void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
  960. MachineBasicBlock::iterator MI,
  961. MutableArrayRef<CalleeSavedInfo> CSI,
  962. unsigned LdmOpc, unsigned LdrOpc,
  963. bool isVarArg, bool NoGap,
  964. bool (*Func)(unsigned, bool),
  965. unsigned NumAlignedDPRCS2Regs) const {
  966. MachineFunction &MF = *MBB.getParent();
  967. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  968. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  969. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  970. DebugLoc DL;
  971. bool isTailCall = false;
  972. bool isInterrupt = false;
  973. bool isTrap = false;
  974. bool isCmseEntry = false;
  975. if (MBB.end() != MI) {
  976. DL = MI->getDebugLoc();
  977. unsigned RetOpcode = MI->getOpcode();
  978. isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
  979. isInterrupt =
  980. RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
  981. isTrap =
  982. RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
  983. RetOpcode == ARM::tTRAP;
  984. isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET);
  985. }
  986. SmallVector<unsigned, 4> Regs;
  987. unsigned i = CSI.size();
  988. while (i != 0) {
  989. unsigned LastReg = 0;
  990. bool DeleteRet = false;
  991. for (; i != 0; --i) {
  992. CalleeSavedInfo &Info = CSI[i-1];
  993. unsigned Reg = Info.getReg();
  994. if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
  995. // The aligned reloads from area DPRCS2 are not inserted here.
  996. if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
  997. continue;
  998. if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
  999. !isCmseEntry && !isTrap && STI.hasV5TOps()) {
  1000. if (MBB.succ_empty()) {
  1001. Reg = ARM::PC;
  1002. // Fold the return instruction into the LDM.
  1003. DeleteRet = true;
  1004. LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
  1005. // We 'restore' LR into PC so it is not live out of the return block:
  1006. // Clear Restored bit.
  1007. Info.setRestored(false);
  1008. } else
  1009. LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
  1010. }
  1011. // If NoGap is true, pop consecutive registers and then leave the rest
  1012. // for other instructions. e.g.
  1013. // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
  1014. if (NoGap && LastReg && LastReg != Reg-1)
  1015. break;
  1016. LastReg = Reg;
  1017. Regs.push_back(Reg);
  1018. }
  1019. if (Regs.empty())
  1020. continue;
  1021. llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
  1022. return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
  1023. });
  1024. if (Regs.size() > 1 || LdrOpc == 0) {
  1025. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
  1026. .addReg(ARM::SP)
  1027. .add(predOps(ARMCC::AL))
  1028. .setMIFlags(MachineInstr::FrameDestroy);
  1029. for (unsigned i = 0, e = Regs.size(); i < e; ++i)
  1030. MIB.addReg(Regs[i], getDefRegState(true));
  1031. if (DeleteRet) {
  1032. if (MI != MBB.end()) {
  1033. MIB.copyImplicitOps(*MI);
  1034. MI->eraseFromParent();
  1035. }
  1036. }
  1037. MI = MIB;
  1038. } else if (Regs.size() == 1) {
  1039. // If we adjusted the reg to PC from LR above, switch it back here. We
  1040. // only do that for LDM.
  1041. if (Regs[0] == ARM::PC)
  1042. Regs[0] = ARM::LR;
  1043. MachineInstrBuilder MIB =
  1044. BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
  1045. .addReg(ARM::SP, RegState::Define)
  1046. .addReg(ARM::SP)
  1047. .setMIFlags(MachineInstr::FrameDestroy);
  1048. // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
  1049. // that refactoring is complete (eventually).
  1050. if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
  1051. MIB.addReg(0);
  1052. MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
  1053. } else
  1054. MIB.addImm(4);
  1055. MIB.add(predOps(ARMCC::AL));
  1056. }
  1057. Regs.clear();
  1058. // Put any subsequent vpop instructions after this one: they will refer to
  1059. // higher register numbers so need to be popped afterwards.
  1060. if (MI != MBB.end())
  1061. ++MI;
  1062. }
  1063. }
  1064. /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
  1065. /// starting from d8. Also insert stack realignment code and leave the stack
  1066. /// pointer pointing to the d8 spill slot.
  1067. static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
  1068. MachineBasicBlock::iterator MI,
  1069. unsigned NumAlignedDPRCS2Regs,
  1070. ArrayRef<CalleeSavedInfo> CSI,
  1071. const TargetRegisterInfo *TRI) {
  1072. MachineFunction &MF = *MBB.getParent();
  1073. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1074. DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
  1075. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  1076. MachineFrameInfo &MFI = MF.getFrameInfo();
  1077. // Mark the D-register spill slots as properly aligned. Since MFI computes
  1078. // stack slot layout backwards, this can actually mean that the d-reg stack
  1079. // slot offsets can be wrong. The offset for d8 will always be correct.
  1080. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  1081. unsigned DNum = CSI[i].getReg() - ARM::D8;
  1082. if (DNum > NumAlignedDPRCS2Regs - 1)
  1083. continue;
  1084. int FI = CSI[i].getFrameIdx();
  1085. // The even-numbered registers will be 16-byte aligned, the odd-numbered
  1086. // registers will be 8-byte aligned.
  1087. MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16));
  1088. // The stack slot for D8 needs to be maximally aligned because this is
  1089. // actually the point where we align the stack pointer. MachineFrameInfo
  1090. // computes all offsets relative to the incoming stack pointer which is a
  1091. // bit weird when realigning the stack. Any extra padding for this
  1092. // over-alignment is not realized because the code inserted below adjusts
  1093. // the stack pointer by numregs * 8 before aligning the stack pointer.
  1094. if (DNum == 0)
  1095. MFI.setObjectAlignment(FI, MFI.getMaxAlign());
  1096. }
  1097. // Move the stack pointer to the d8 spill slot, and align it at the same
  1098. // time. Leave the stack slot address in the scratch register r4.
  1099. //
  1100. // sub r4, sp, #numregs * 8
  1101. // bic r4, r4, #align - 1
  1102. // mov sp, r4
  1103. //
  1104. bool isThumb = AFI->isThumbFunction();
  1105. assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
  1106. AFI->setShouldRestoreSPFromFP(true);
  1107. // sub r4, sp, #numregs * 8
  1108. // The immediate is <= 64, so it doesn't need any special encoding.
  1109. unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
  1110. BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  1111. .addReg(ARM::SP)
  1112. .addImm(8 * NumAlignedDPRCS2Regs)
  1113. .add(predOps(ARMCC::AL))
  1114. .add(condCodeOp());
  1115. Align MaxAlign = MF.getFrameInfo().getMaxAlign();
  1116. // We must set parameter MustBeSingleInstruction to true, since
  1117. // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
  1118. // stack alignment. Luckily, this can always be done since all ARM
  1119. // architecture versions that support Neon also support the BFC
  1120. // instruction.
  1121. emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
  1122. // mov sp, r4
  1123. // The stack pointer must be adjusted before spilling anything, otherwise
  1124. // the stack slots could be clobbered by an interrupt handler.
  1125. // Leave r4 live, it is used below.
  1126. Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
  1127. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
  1128. .addReg(ARM::R4)
  1129. .add(predOps(ARMCC::AL));
  1130. if (!isThumb)
  1131. MIB.add(condCodeOp());
  1132. // Now spill NumAlignedDPRCS2Regs registers starting from d8.
  1133. // r4 holds the stack slot address.
  1134. unsigned NextReg = ARM::D8;
  1135. // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
  1136. // The writeback is only needed when emitting two vst1.64 instructions.
  1137. if (NumAlignedDPRCS2Regs >= 6) {
  1138. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1139. &ARM::QQPRRegClass);
  1140. MBB.addLiveIn(SupReg);
  1141. BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
  1142. .addReg(ARM::R4, RegState::Kill)
  1143. .addImm(16)
  1144. .addReg(NextReg)
  1145. .addReg(SupReg, RegState::ImplicitKill)
  1146. .add(predOps(ARMCC::AL));
  1147. NextReg += 4;
  1148. NumAlignedDPRCS2Regs -= 4;
  1149. }
  1150. // We won't modify r4 beyond this point. It currently points to the next
  1151. // register to be spilled.
  1152. unsigned R4BaseReg = NextReg;
  1153. // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
  1154. if (NumAlignedDPRCS2Regs >= 4) {
  1155. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1156. &ARM::QQPRRegClass);
  1157. MBB.addLiveIn(SupReg);
  1158. BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
  1159. .addReg(ARM::R4)
  1160. .addImm(16)
  1161. .addReg(NextReg)
  1162. .addReg(SupReg, RegState::ImplicitKill)
  1163. .add(predOps(ARMCC::AL));
  1164. NextReg += 4;
  1165. NumAlignedDPRCS2Regs -= 4;
  1166. }
  1167. // 16-byte aligned vst1.64 with 2 d-regs.
  1168. if (NumAlignedDPRCS2Regs >= 2) {
  1169. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1170. &ARM::QPRRegClass);
  1171. MBB.addLiveIn(SupReg);
  1172. BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
  1173. .addReg(ARM::R4)
  1174. .addImm(16)
  1175. .addReg(SupReg)
  1176. .add(predOps(ARMCC::AL));
  1177. NextReg += 2;
  1178. NumAlignedDPRCS2Regs -= 2;
  1179. }
  1180. // Finally, use a vanilla vstr.64 for the odd last register.
  1181. if (NumAlignedDPRCS2Regs) {
  1182. MBB.addLiveIn(NextReg);
  1183. // vstr.64 uses addrmode5 which has an offset scale of 4.
  1184. BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
  1185. .addReg(NextReg)
  1186. .addReg(ARM::R4)
  1187. .addImm((NextReg - R4BaseReg) * 2)
  1188. .add(predOps(ARMCC::AL));
  1189. }
  1190. // The last spill instruction inserted should kill the scratch register r4.
  1191. std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
  1192. }
  1193. /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
  1194. /// iterator to the following instruction.
  1195. static MachineBasicBlock::iterator
  1196. skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
  1197. unsigned NumAlignedDPRCS2Regs) {
  1198. // sub r4, sp, #numregs * 8
  1199. // bic r4, r4, #align - 1
  1200. // mov sp, r4
  1201. ++MI; ++MI; ++MI;
  1202. assert(MI->mayStore() && "Expecting spill instruction");
  1203. // These switches all fall through.
  1204. switch(NumAlignedDPRCS2Regs) {
  1205. case 7:
  1206. ++MI;
  1207. assert(MI->mayStore() && "Expecting spill instruction");
  1208. LLVM_FALLTHROUGH;
  1209. default:
  1210. ++MI;
  1211. assert(MI->mayStore() && "Expecting spill instruction");
  1212. LLVM_FALLTHROUGH;
  1213. case 1:
  1214. case 2:
  1215. case 4:
  1216. assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
  1217. ++MI;
  1218. }
  1219. return MI;
  1220. }
  1221. /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
  1222. /// starting from d8. These instructions are assumed to execute while the
  1223. /// stack is still aligned, unlike the code inserted by emitPopInst.
  1224. static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
  1225. MachineBasicBlock::iterator MI,
  1226. unsigned NumAlignedDPRCS2Regs,
  1227. ArrayRef<CalleeSavedInfo> CSI,
  1228. const TargetRegisterInfo *TRI) {
  1229. MachineFunction &MF = *MBB.getParent();
  1230. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1231. DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
  1232. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  1233. // Find the frame index assigned to d8.
  1234. int D8SpillFI = 0;
  1235. for (unsigned i = 0, e = CSI.size(); i != e; ++i)
  1236. if (CSI[i].getReg() == ARM::D8) {
  1237. D8SpillFI = CSI[i].getFrameIdx();
  1238. break;
  1239. }
  1240. // Materialize the address of the d8 spill slot into the scratch register r4.
  1241. // This can be fairly complicated if the stack frame is large, so just use
  1242. // the normal frame index elimination mechanism to do it. This code runs as
  1243. // the initial part of the epilog where the stack and base pointers haven't
  1244. // been changed yet.
  1245. bool isThumb = AFI->isThumbFunction();
  1246. assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
  1247. unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
  1248. BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  1249. .addFrameIndex(D8SpillFI)
  1250. .addImm(0)
  1251. .add(predOps(ARMCC::AL))
  1252. .add(condCodeOp());
  1253. // Now restore NumAlignedDPRCS2Regs registers starting from d8.
  1254. unsigned NextReg = ARM::D8;
  1255. // 16-byte aligned vld1.64 with 4 d-regs and writeback.
  1256. if (NumAlignedDPRCS2Regs >= 6) {
  1257. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1258. &ARM::QQPRRegClass);
  1259. BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
  1260. .addReg(ARM::R4, RegState::Define)
  1261. .addReg(ARM::R4, RegState::Kill)
  1262. .addImm(16)
  1263. .addReg(SupReg, RegState::ImplicitDefine)
  1264. .add(predOps(ARMCC::AL));
  1265. NextReg += 4;
  1266. NumAlignedDPRCS2Regs -= 4;
  1267. }
  1268. // We won't modify r4 beyond this point. It currently points to the next
  1269. // register to be spilled.
  1270. unsigned R4BaseReg = NextReg;
  1271. // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
  1272. if (NumAlignedDPRCS2Regs >= 4) {
  1273. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1274. &ARM::QQPRRegClass);
  1275. BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
  1276. .addReg(ARM::R4)
  1277. .addImm(16)
  1278. .addReg(SupReg, RegState::ImplicitDefine)
  1279. .add(predOps(ARMCC::AL));
  1280. NextReg += 4;
  1281. NumAlignedDPRCS2Regs -= 4;
  1282. }
  1283. // 16-byte aligned vld1.64 with 2 d-regs.
  1284. if (NumAlignedDPRCS2Regs >= 2) {
  1285. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1286. &ARM::QPRRegClass);
  1287. BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
  1288. .addReg(ARM::R4)
  1289. .addImm(16)
  1290. .add(predOps(ARMCC::AL));
  1291. NextReg += 2;
  1292. NumAlignedDPRCS2Regs -= 2;
  1293. }
  1294. // Finally, use a vanilla vldr.64 for the remaining odd register.
  1295. if (NumAlignedDPRCS2Regs)
  1296. BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
  1297. .addReg(ARM::R4)
  1298. .addImm(2 * (NextReg - R4BaseReg))
  1299. .add(predOps(ARMCC::AL));
  1300. // Last store kills r4.
  1301. std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
  1302. }
  1303. bool ARMFrameLowering::spillCalleeSavedRegisters(
  1304. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  1305. ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  1306. if (CSI.empty())
  1307. return false;
  1308. MachineFunction &MF = *MBB.getParent();
  1309. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1310. unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
  1311. unsigned PushOneOpc = AFI->isThumbFunction() ?
  1312. ARM::t2STR_PRE : ARM::STR_PRE_IMM;
  1313. unsigned FltOpc = ARM::VSTMDDB_UPD;
  1314. unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
  1315. // Save the non-secure floating point context.
  1316. if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) {
  1317. return C.getReg() == ARM::FPCXTNS;
  1318. })) {
  1319. BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre),
  1320. ARM::SP)
  1321. .addReg(ARM::SP)
  1322. .addImm(-4)
  1323. .add(predOps(ARMCC::AL));
  1324. }
  1325. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
  1326. MachineInstr::FrameSetup);
  1327. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
  1328. MachineInstr::FrameSetup);
  1329. emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
  1330. NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
  1331. // The code above does not insert spill code for the aligned DPRCS2 registers.
  1332. // The stack realignment code will be inserted between the push instructions
  1333. // and these spills.
  1334. if (NumAlignedDPRCS2Regs)
  1335. emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
  1336. return true;
  1337. }
  1338. bool ARMFrameLowering::restoreCalleeSavedRegisters(
  1339. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  1340. MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  1341. if (CSI.empty())
  1342. return false;
  1343. MachineFunction &MF = *MBB.getParent();
  1344. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1345. bool isVarArg = AFI->getArgRegsSaveSize() > 0;
  1346. unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
  1347. // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
  1348. // registers. Do that here instead.
  1349. if (NumAlignedDPRCS2Regs)
  1350. emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
  1351. unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
  1352. unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
  1353. unsigned FltOpc = ARM::VLDMDIA_UPD;
  1354. emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
  1355. NumAlignedDPRCS2Regs);
  1356. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1357. &isARMArea2Register, 0);
  1358. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1359. &isARMArea1Register, 0);
  1360. return true;
  1361. }
  1362. // FIXME: Make generic?
  1363. static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
  1364. const ARMBaseInstrInfo &TII) {
  1365. unsigned FnSize = 0;
  1366. for (auto &MBB : MF) {
  1367. for (auto &MI : MBB)
  1368. FnSize += TII.getInstSizeInBytes(MI);
  1369. }
  1370. if (MF.getJumpTableInfo())
  1371. for (auto &Table: MF.getJumpTableInfo()->getJumpTables())
  1372. FnSize += Table.MBBs.size() * 4;
  1373. FnSize += MF.getConstantPool()->getConstants().size() * 4;
  1374. return FnSize;
  1375. }
  1376. /// estimateRSStackSizeLimit - Look at each instruction that references stack
  1377. /// frames and return the stack size limit beyond which some of these
  1378. /// instructions will require a scratch register during their expansion later.
  1379. // FIXME: Move to TII?
  1380. static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
  1381. const TargetFrameLowering *TFI,
  1382. bool &HasNonSPFrameIndex) {
  1383. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1384. const ARMBaseInstrInfo &TII =
  1385. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  1386. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1387. unsigned Limit = (1 << 12) - 1;
  1388. for (auto &MBB : MF) {
  1389. for (auto &MI : MBB) {
  1390. if (MI.isDebugInstr())
  1391. continue;
  1392. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  1393. if (!MI.getOperand(i).isFI())
  1394. continue;
  1395. // When using ADDri to get the address of a stack object, 255 is the
  1396. // largest offset guaranteed to fit in the immediate offset.
  1397. if (MI.getOpcode() == ARM::ADDri) {
  1398. Limit = std::min(Limit, (1U << 8) - 1);
  1399. break;
  1400. }
  1401. // t2ADDri will not require an extra register, it can reuse the
  1402. // destination.
  1403. if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
  1404. break;
  1405. const MCInstrDesc &MCID = MI.getDesc();
  1406. const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF);
  1407. if (RegClass && !RegClass->contains(ARM::SP))
  1408. HasNonSPFrameIndex = true;
  1409. // Otherwise check the addressing mode.
  1410. switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
  1411. case ARMII::AddrMode_i12:
  1412. case ARMII::AddrMode2:
  1413. // Default 12 bit limit.
  1414. break;
  1415. case ARMII::AddrMode3:
  1416. case ARMII::AddrModeT2_i8:
  1417. Limit = std::min(Limit, (1U << 8) - 1);
  1418. break;
  1419. case ARMII::AddrMode5FP16:
  1420. Limit = std::min(Limit, ((1U << 8) - 1) * 2);
  1421. break;
  1422. case ARMII::AddrMode5:
  1423. case ARMII::AddrModeT2_i8s4:
  1424. case ARMII::AddrModeT2_ldrex:
  1425. Limit = std::min(Limit, ((1U << 8) - 1) * 4);
  1426. break;
  1427. case ARMII::AddrModeT2_i12:
  1428. // i12 supports only positive offset so these will be converted to
  1429. // i8 opcodes. See llvm::rewriteT2FrameIndex.
  1430. if (TFI->hasFP(MF) && AFI->hasStackFrame())
  1431. Limit = std::min(Limit, (1U << 8) - 1);
  1432. break;
  1433. case ARMII::AddrMode4:
  1434. case ARMII::AddrMode6:
  1435. // Addressing modes 4 & 6 (load/store) instructions can't encode an
  1436. // immediate offset for stack references.
  1437. return 0;
  1438. case ARMII::AddrModeT2_i7:
  1439. Limit = std::min(Limit, ((1U << 7) - 1) * 1);
  1440. break;
  1441. case ARMII::AddrModeT2_i7s2:
  1442. Limit = std::min(Limit, ((1U << 7) - 1) * 2);
  1443. break;
  1444. case ARMII::AddrModeT2_i7s4:
  1445. Limit = std::min(Limit, ((1U << 7) - 1) * 4);
  1446. break;
  1447. default:
  1448. llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
  1449. }
  1450. break; // At most one FI per instruction
  1451. }
  1452. }
  1453. }
  1454. return Limit;
  1455. }
  1456. // In functions that realign the stack, it can be an advantage to spill the
  1457. // callee-saved vector registers after realigning the stack. The vst1 and vld1
  1458. // instructions take alignment hints that can improve performance.
  1459. static void
  1460. checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
  1461. MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
  1462. if (!SpillAlignedNEONRegs)
  1463. return;
  1464. // Naked functions don't spill callee-saved registers.
  1465. if (MF.getFunction().hasFnAttribute(Attribute::Naked))
  1466. return;
  1467. // We are planning to use NEON instructions vst1 / vld1.
  1468. if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
  1469. return;
  1470. // Don't bother if the default stack alignment is sufficiently high.
  1471. if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8))
  1472. return;
  1473. // Aligned spills require stack realignment.
  1474. if (!static_cast<const ARMBaseRegisterInfo *>(
  1475. MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
  1476. return;
  1477. // We always spill contiguous d-registers starting from d8. Count how many
  1478. // needs spilling. The register allocator will almost always use the
  1479. // callee-saved registers in order, but it can happen that there are holes in
  1480. // the range. Registers above the hole will be spilled to the standard DPRCS
  1481. // area.
  1482. unsigned NumSpills = 0;
  1483. for (; NumSpills < 8; ++NumSpills)
  1484. if (!SavedRegs.test(ARM::D8 + NumSpills))
  1485. break;
  1486. // Don't do this for just one d-register. It's not worth it.
  1487. if (NumSpills < 2)
  1488. return;
  1489. // Spill the first NumSpills D-registers after realigning the stack.
  1490. MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
  1491. // A scratch register is required for the vst1 / vld1 instructions.
  1492. SavedRegs.set(ARM::R4);
  1493. }
  1494. bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
  1495. // For CMSE entry functions, we want to save the FPCXT_NS immediately
  1496. // upon function entry (resp. restore it immmediately before return)
  1497. if (STI.hasV8_1MMainlineOps() &&
  1498. MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction())
  1499. return false;
  1500. return true;
  1501. }
  1502. void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
  1503. BitVector &SavedRegs,
  1504. RegScavenger *RS) const {
  1505. TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
  1506. // This tells PEI to spill the FP as if it is any other callee-save register
  1507. // to take advantage the eliminateFrameIndex machinery. This also ensures it
  1508. // is spilled in the order specified by getCalleeSavedRegs() to make it easier
  1509. // to combine multiple loads / stores.
  1510. bool CanEliminateFrame = true;
  1511. bool CS1Spilled = false;
  1512. bool LRSpilled = false;
  1513. unsigned NumGPRSpills = 0;
  1514. unsigned NumFPRSpills = 0;
  1515. SmallVector<unsigned, 4> UnspilledCS1GPRs;
  1516. SmallVector<unsigned, 4> UnspilledCS2GPRs;
  1517. const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
  1518. MF.getSubtarget().getRegisterInfo());
  1519. const ARMBaseInstrInfo &TII =
  1520. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  1521. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1522. MachineFrameInfo &MFI = MF.getFrameInfo();
  1523. MachineRegisterInfo &MRI = MF.getRegInfo();
  1524. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1525. (void)TRI; // Silence unused warning in non-assert builds.
  1526. Register FramePtr = RegInfo->getFrameRegister(MF);
  1527. // Spill R4 if Thumb2 function requires stack realignment - it will be used as
  1528. // scratch register. Also spill R4 if Thumb2 function has varsized objects,
  1529. // since it's not always possible to restore sp from fp in a single
  1530. // instruction.
  1531. // FIXME: It will be better just to find spare register here.
  1532. if (AFI->isThumb2Function() &&
  1533. (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
  1534. SavedRegs.set(ARM::R4);
  1535. // If a stack probe will be emitted, spill R4 and LR, since they are
  1536. // clobbered by the stack probe call.
  1537. // This estimate should be a safe, conservative estimate. The actual
  1538. // stack probe is enabled based on the size of the local objects;
  1539. // this estimate also includes the varargs store size.
  1540. if (STI.isTargetWindows() &&
  1541. WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
  1542. SavedRegs.set(ARM::R4);
  1543. SavedRegs.set(ARM::LR);
  1544. }
  1545. if (AFI->isThumb1OnlyFunction()) {
  1546. // Spill LR if Thumb1 function uses variable length argument lists.
  1547. if (AFI->getArgRegsSaveSize() > 0)
  1548. SavedRegs.set(ARM::LR);
  1549. // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
  1550. // requires stack alignment. We don't know for sure what the stack size
  1551. // will be, but for this, an estimate is good enough. If there anything
  1552. // changes it, it'll be a spill, which implies we've used all the registers
  1553. // and so R4 is already used, so not marking it here will be OK.
  1554. // FIXME: It will be better just to find spare register here.
  1555. if (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF) ||
  1556. MFI.estimateStackSize(MF) > 508)
  1557. SavedRegs.set(ARM::R4);
  1558. }
  1559. // See if we can spill vector registers to aligned stack.
  1560. checkNumAlignedDPRCS2Regs(MF, SavedRegs);
  1561. // Spill the BasePtr if it's used.
  1562. if (RegInfo->hasBasePointer(MF))
  1563. SavedRegs.set(RegInfo->getBaseRegister());
  1564. // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
  1565. if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
  1566. CanEliminateFrame = false;
  1567. // Don't spill FP if the frame can be eliminated. This is determined
  1568. // by scanning the callee-save registers to see if any is modified.
  1569. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
  1570. for (unsigned i = 0; CSRegs[i]; ++i) {
  1571. unsigned Reg = CSRegs[i];
  1572. bool Spilled = false;
  1573. if (SavedRegs.test(Reg)) {
  1574. Spilled = true;
  1575. CanEliminateFrame = false;
  1576. }
  1577. if (!ARM::GPRRegClass.contains(Reg)) {
  1578. if (Spilled) {
  1579. if (ARM::SPRRegClass.contains(Reg))
  1580. NumFPRSpills++;
  1581. else if (ARM::DPRRegClass.contains(Reg))
  1582. NumFPRSpills += 2;
  1583. else if (ARM::QPRRegClass.contains(Reg))
  1584. NumFPRSpills += 4;
  1585. }
  1586. continue;
  1587. }
  1588. if (Spilled) {
  1589. NumGPRSpills++;
  1590. if (!STI.splitFramePushPop(MF)) {
  1591. if (Reg == ARM::LR)
  1592. LRSpilled = true;
  1593. CS1Spilled = true;
  1594. continue;
  1595. }
  1596. // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
  1597. switch (Reg) {
  1598. case ARM::LR:
  1599. LRSpilled = true;
  1600. LLVM_FALLTHROUGH;
  1601. case ARM::R0: case ARM::R1:
  1602. case ARM::R2: case ARM::R3:
  1603. case ARM::R4: case ARM::R5:
  1604. case ARM::R6: case ARM::R7:
  1605. CS1Spilled = true;
  1606. break;
  1607. default:
  1608. break;
  1609. }
  1610. } else {
  1611. if (!STI.splitFramePushPop(MF)) {
  1612. UnspilledCS1GPRs.push_back(Reg);
  1613. continue;
  1614. }
  1615. switch (Reg) {
  1616. case ARM::R0: case ARM::R1:
  1617. case ARM::R2: case ARM::R3:
  1618. case ARM::R4: case ARM::R5:
  1619. case ARM::R6: case ARM::R7:
  1620. case ARM::LR:
  1621. UnspilledCS1GPRs.push_back(Reg);
  1622. break;
  1623. default:
  1624. UnspilledCS2GPRs.push_back(Reg);
  1625. break;
  1626. }
  1627. }
  1628. }
  1629. bool ForceLRSpill = false;
  1630. if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
  1631. unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII);
  1632. // Force LR to be spilled if the Thumb function size is > 2048. This enables
  1633. // use of BL to implement far jump.
  1634. if (FnSize >= (1 << 11)) {
  1635. CanEliminateFrame = false;
  1636. ForceLRSpill = true;
  1637. }
  1638. }
  1639. // If any of the stack slot references may be out of range of an immediate
  1640. // offset, make sure a register (or a spill slot) is available for the
  1641. // register scavenger. Note that if we're indexing off the frame pointer, the
  1642. // effective stack size is 4 bytes larger since the FP points to the stack
  1643. // slot of the previous FP. Also, if we have variable sized objects in the
  1644. // function, stack slot references will often be negative, and some of
  1645. // our instructions are positive-offset only, so conservatively consider
  1646. // that case to want a spill slot (or register) as well. Similarly, if
  1647. // the function adjusts the stack pointer during execution and the
  1648. // adjustments aren't already part of our stack size estimate, our offset
  1649. // calculations may be off, so be conservative.
  1650. // FIXME: We could add logic to be more precise about negative offsets
  1651. // and which instructions will need a scratch register for them. Is it
  1652. // worth the effort and added fragility?
  1653. unsigned EstimatedStackSize =
  1654. MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
  1655. // Determine biggest (positive) SP offset in MachineFrameInfo.
  1656. int MaxFixedOffset = 0;
  1657. for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
  1658. int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
  1659. MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
  1660. }
  1661. bool HasFP = hasFP(MF);
  1662. if (HasFP) {
  1663. if (AFI->hasStackFrame())
  1664. EstimatedStackSize += 4;
  1665. } else {
  1666. // If FP is not used, SP will be used to access arguments, so count the
  1667. // size of arguments into the estimation.
  1668. EstimatedStackSize += MaxFixedOffset;
  1669. }
  1670. EstimatedStackSize += 16; // For possible paddings.
  1671. unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
  1672. bool HasNonSPFrameIndex = false;
  1673. if (AFI->isThumb1OnlyFunction()) {
  1674. // For Thumb1, don't bother to iterate over the function. The only
  1675. // instruction that requires an emergency spill slot is a store to a
  1676. // frame index.
  1677. //
  1678. // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
  1679. // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
  1680. // a 5-bit unsigned immediate.
  1681. //
  1682. // We could try to check if the function actually contains a tSTRspi
  1683. // that might need the spill slot, but it's not really important.
  1684. // Functions with VLAs or extremely large call frames are rare, and
  1685. // if a function is allocating more than 1KB of stack, an extra 4-byte
  1686. // slot probably isn't relevant.
  1687. if (RegInfo->hasBasePointer(MF))
  1688. EstimatedRSStackSizeLimit = (1U << 5) * 4;
  1689. else
  1690. EstimatedRSStackSizeLimit = (1U << 8) * 4;
  1691. EstimatedRSFixedSizeLimit = (1U << 5) * 4;
  1692. } else {
  1693. EstimatedRSStackSizeLimit =
  1694. estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
  1695. EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
  1696. }
  1697. // Final estimate of whether sp or bp-relative accesses might require
  1698. // scavenging.
  1699. bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
  1700. // If the stack pointer moves and we don't have a base pointer, the
  1701. // estimate logic doesn't work. The actual offsets might be larger when
  1702. // we're constructing a call frame, or we might need to use negative
  1703. // offsets from fp.
  1704. bool HasMovingSP = MFI.hasVarSizedObjects() ||
  1705. (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
  1706. bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
  1707. // If we have a frame pointer, we assume arguments will be accessed
  1708. // relative to the frame pointer. Check whether fp-relative accesses to
  1709. // arguments require scavenging.
  1710. //
  1711. // We could do slightly better on Thumb1; in some cases, an sp-relative
  1712. // offset would be legal even though an fp-relative offset is not.
  1713. int MaxFPOffset = getMaxFPOffset(STI, *AFI);
  1714. bool HasLargeArgumentList =
  1715. HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
  1716. bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
  1717. HasLargeArgumentList || HasNonSPFrameIndex;
  1718. LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
  1719. << "; EstimatedStack: " << EstimatedStackSize
  1720. << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
  1721. << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
  1722. if (BigFrameOffsets ||
  1723. !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
  1724. AFI->setHasStackFrame(true);
  1725. if (HasFP) {
  1726. SavedRegs.set(FramePtr);
  1727. // If the frame pointer is required by the ABI, also spill LR so that we
  1728. // emit a complete frame record.
  1729. if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
  1730. SavedRegs.set(ARM::LR);
  1731. LRSpilled = true;
  1732. NumGPRSpills++;
  1733. auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
  1734. if (LRPos != UnspilledCS1GPRs.end())
  1735. UnspilledCS1GPRs.erase(LRPos);
  1736. }
  1737. auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
  1738. if (FPPos != UnspilledCS1GPRs.end())
  1739. UnspilledCS1GPRs.erase(FPPos);
  1740. NumGPRSpills++;
  1741. if (FramePtr == ARM::R7)
  1742. CS1Spilled = true;
  1743. }
  1744. // This is true when we inserted a spill for a callee-save GPR which is
  1745. // not otherwise used by the function. This guaranteees it is possible
  1746. // to scavenge a register to hold the address of a stack slot. On Thumb1,
  1747. // the register must be a valid operand to tSTRi, i.e. r4-r7. For other
  1748. // subtargets, this is any GPR, i.e. r4-r11 or lr.
  1749. //
  1750. // If we don't insert a spill, we instead allocate an emergency spill
  1751. // slot, which can be used by scavenging to spill an arbitrary register.
  1752. //
  1753. // We currently don't try to figure out whether any specific instruction
  1754. // requires scavening an additional register.
  1755. bool ExtraCSSpill = false;
  1756. if (AFI->isThumb1OnlyFunction()) {
  1757. // For Thumb1-only targets, we need some low registers when we save and
  1758. // restore the high registers (which aren't allocatable, but could be
  1759. // used by inline assembly) because the push/pop instructions can not
  1760. // access high registers. If necessary, we might need to push more low
  1761. // registers to ensure that there is at least one free that can be used
  1762. // for the saving & restoring, and preferably we should ensure that as
  1763. // many as are needed are available so that fewer push/pop instructions
  1764. // are required.
  1765. // Low registers which are not currently pushed, but could be (r4-r7).
  1766. SmallVector<unsigned, 4> AvailableRegs;
  1767. // Unused argument registers (r0-r3) can be clobbered in the prologue for
  1768. // free.
  1769. int EntryRegDeficit = 0;
  1770. for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
  1771. if (!MF.getRegInfo().isLiveIn(Reg)) {
  1772. --EntryRegDeficit;
  1773. LLVM_DEBUG(dbgs()
  1774. << printReg(Reg, TRI)
  1775. << " is unused argument register, EntryRegDeficit = "
  1776. << EntryRegDeficit << "\n");
  1777. }
  1778. }
  1779. // Unused return registers can be clobbered in the epilogue for free.
  1780. int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
  1781. LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
  1782. << " return regs used, ExitRegDeficit = "
  1783. << ExitRegDeficit << "\n");
  1784. int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
  1785. LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
  1786. // r4-r6 can be used in the prologue if they are pushed by the first push
  1787. // instruction.
  1788. for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
  1789. if (SavedRegs.test(Reg)) {
  1790. --RegDeficit;
  1791. LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
  1792. << " is saved low register, RegDeficit = "
  1793. << RegDeficit << "\n");
  1794. } else {
  1795. AvailableRegs.push_back(Reg);
  1796. LLVM_DEBUG(
  1797. dbgs()
  1798. << printReg(Reg, TRI)
  1799. << " is non-saved low register, adding to AvailableRegs\n");
  1800. }
  1801. }
  1802. // r7 can be used if it is not being used as the frame pointer.
  1803. if (!HasFP) {
  1804. if (SavedRegs.test(ARM::R7)) {
  1805. --RegDeficit;
  1806. LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
  1807. << RegDeficit << "\n");
  1808. } else {
  1809. AvailableRegs.push_back(ARM::R7);
  1810. LLVM_DEBUG(
  1811. dbgs()
  1812. << "%r7 is non-saved low register, adding to AvailableRegs\n");
  1813. }
  1814. }
  1815. // Each of r8-r11 needs to be copied to a low register, then pushed.
  1816. for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
  1817. if (SavedRegs.test(Reg)) {
  1818. ++RegDeficit;
  1819. LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
  1820. << " is saved high register, RegDeficit = "
  1821. << RegDeficit << "\n");
  1822. }
  1823. }
  1824. // LR can only be used by PUSH, not POP, and can't be used at all if the
  1825. // llvm.returnaddress intrinsic is used. This is only worth doing if we
  1826. // are more limited at function entry than exit.
  1827. if ((EntryRegDeficit > ExitRegDeficit) &&
  1828. !(MF.getRegInfo().isLiveIn(ARM::LR) &&
  1829. MF.getFrameInfo().isReturnAddressTaken())) {
  1830. if (SavedRegs.test(ARM::LR)) {
  1831. --RegDeficit;
  1832. LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
  1833. << RegDeficit << "\n");
  1834. } else {
  1835. AvailableRegs.push_back(ARM::LR);
  1836. LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
  1837. }
  1838. }
  1839. // If there are more high registers that need pushing than low registers
  1840. // available, push some more low registers so that we can use fewer push
  1841. // instructions. This might not reduce RegDeficit all the way to zero,
  1842. // because we can only guarantee that r4-r6 are available, but r8-r11 may
  1843. // need saving.
  1844. LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
  1845. for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
  1846. unsigned Reg = AvailableRegs.pop_back_val();
  1847. LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
  1848. << " to make up reg deficit\n");
  1849. SavedRegs.set(Reg);
  1850. NumGPRSpills++;
  1851. CS1Spilled = true;
  1852. assert(!MRI.isReserved(Reg) && "Should not be reserved");
  1853. if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
  1854. ExtraCSSpill = true;
  1855. UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
  1856. if (Reg == ARM::LR)
  1857. LRSpilled = true;
  1858. }
  1859. LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
  1860. << "\n");
  1861. }
  1862. // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
  1863. // restore LR in that case.
  1864. bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
  1865. // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
  1866. // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
  1867. if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
  1868. SavedRegs.set(ARM::LR);
  1869. NumGPRSpills++;
  1870. SmallVectorImpl<unsigned>::iterator LRPos;
  1871. LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
  1872. if (LRPos != UnspilledCS1GPRs.end())
  1873. UnspilledCS1GPRs.erase(LRPos);
  1874. ForceLRSpill = false;
  1875. if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
  1876. !AFI->isThumb1OnlyFunction())
  1877. ExtraCSSpill = true;
  1878. }
  1879. // If stack and double are 8-byte aligned and we are spilling an odd number
  1880. // of GPRs, spill one extra callee save GPR so we won't have to pad between
  1881. // the integer and double callee save areas.
  1882. LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
  1883. const Align TargetAlign = getStackAlign();
  1884. if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
  1885. if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
  1886. for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
  1887. unsigned Reg = UnspilledCS1GPRs[i];
  1888. // Don't spill high register if the function is thumb. In the case of
  1889. // Windows on ARM, accept R11 (frame pointer)
  1890. if (!AFI->isThumbFunction() ||
  1891. (STI.isTargetWindows() && Reg == ARM::R11) ||
  1892. isARMLowRegister(Reg) ||
  1893. (Reg == ARM::LR && !ExpensiveLRRestore)) {
  1894. SavedRegs.set(Reg);
  1895. LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
  1896. << " to make up alignment\n");
  1897. if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
  1898. !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
  1899. ExtraCSSpill = true;
  1900. break;
  1901. }
  1902. }
  1903. } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
  1904. unsigned Reg = UnspilledCS2GPRs.front();
  1905. SavedRegs.set(Reg);
  1906. LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
  1907. << " to make up alignment\n");
  1908. if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
  1909. ExtraCSSpill = true;
  1910. }
  1911. }
  1912. // Estimate if we might need to scavenge a register at some point in order
  1913. // to materialize a stack offset. If so, either spill one additional
  1914. // callee-saved register or reserve a special spill slot to facilitate
  1915. // register scavenging. Thumb1 needs a spill slot for stack pointer
  1916. // adjustments also, even when the frame itself is small.
  1917. if (BigFrameOffsets && !ExtraCSSpill) {
  1918. // If any non-reserved CS register isn't spilled, just spill one or two
  1919. // extra. That should take care of it!
  1920. unsigned NumExtras = TargetAlign.value() / 4;
  1921. SmallVector<unsigned, 2> Extras;
  1922. while (NumExtras && !UnspilledCS1GPRs.empty()) {
  1923. unsigned Reg = UnspilledCS1GPRs.pop_back_val();
  1924. if (!MRI.isReserved(Reg) &&
  1925. (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
  1926. Extras.push_back(Reg);
  1927. NumExtras--;
  1928. }
  1929. }
  1930. // For non-Thumb1 functions, also check for hi-reg CS registers
  1931. if (!AFI->isThumb1OnlyFunction()) {
  1932. while (NumExtras && !UnspilledCS2GPRs.empty()) {
  1933. unsigned Reg = UnspilledCS2GPRs.pop_back_val();
  1934. if (!MRI.isReserved(Reg)) {
  1935. Extras.push_back(Reg);
  1936. NumExtras--;
  1937. }
  1938. }
  1939. }
  1940. if (NumExtras == 0) {
  1941. for (unsigned Reg : Extras) {
  1942. SavedRegs.set(Reg);
  1943. if (!MRI.isPhysRegUsed(Reg))
  1944. ExtraCSSpill = true;
  1945. }
  1946. }
  1947. if (!ExtraCSSpill && RS) {
  1948. // Reserve a slot closest to SP or frame pointer.
  1949. LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
  1950. const TargetRegisterClass &RC = ARM::GPRRegClass;
  1951. unsigned Size = TRI->getSpillSize(RC);
  1952. Align Alignment = TRI->getSpillAlign(RC);
  1953. RS->addScavengingFrameIndex(
  1954. MFI.CreateStackObject(Size, Alignment, false));
  1955. }
  1956. }
  1957. }
  1958. if (ForceLRSpill)
  1959. SavedRegs.set(ARM::LR);
  1960. AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
  1961. }
  1962. void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
  1963. BitVector &SavedRegs) const {
  1964. TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
  1965. // If we have the "returned" parameter attribute which guarantees that we
  1966. // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
  1967. // record that fact for IPRA.
  1968. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1969. if (AFI->getPreservesR0())
  1970. SavedRegs.set(ARM::R0);
  1971. }
  1972. bool ARMFrameLowering::assignCalleeSavedSpillSlots(
  1973. MachineFunction &MF, const TargetRegisterInfo *TRI,
  1974. std::vector<CalleeSavedInfo> &CSI) const {
  1975. // For CMSE entry functions, handle floating-point context as if it was a
  1976. // callee-saved register.
  1977. if (STI.hasV8_1MMainlineOps() &&
  1978. MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) {
  1979. CSI.emplace_back(ARM::FPCXTNS);
  1980. CSI.back().setRestored(false);
  1981. }
  1982. return false;
  1983. }
  1984. const TargetFrameLowering::SpillSlot *
  1985. ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
  1986. static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}};
  1987. NumEntries = array_lengthof(FixedSpillOffsets);
  1988. return FixedSpillOffsets;
  1989. }
  1990. MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
  1991. MachineFunction &MF, MachineBasicBlock &MBB,
  1992. MachineBasicBlock::iterator I) const {
  1993. const ARMBaseInstrInfo &TII =
  1994. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  1995. if (!hasReservedCallFrame(MF)) {
  1996. // If we have alloca, convert as follows:
  1997. // ADJCALLSTACKDOWN -> sub, sp, sp, amount
  1998. // ADJCALLSTACKUP -> add, sp, sp, amount
  1999. MachineInstr &Old = *I;
  2000. DebugLoc dl = Old.getDebugLoc();
  2001. unsigned Amount = TII.getFrameSize(Old);
  2002. if (Amount != 0) {
  2003. // We need to keep the stack aligned properly. To do this, we round the
  2004. // amount of space needed for the outgoing arguments up to the next
  2005. // alignment boundary.
  2006. Amount = alignSPAdjust(Amount);
  2007. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  2008. assert(!AFI->isThumb1OnlyFunction() &&
  2009. "This eliminateCallFramePseudoInstr does not support Thumb1!");
  2010. bool isARM = !AFI->isThumbFunction();
  2011. // Replace the pseudo instruction with a new instruction...
  2012. unsigned Opc = Old.getOpcode();
  2013. int PIdx = Old.findFirstPredOperandIdx();
  2014. ARMCC::CondCodes Pred =
  2015. (PIdx == -1) ? ARMCC::AL
  2016. : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
  2017. unsigned PredReg = TII.getFramePred(Old);
  2018. if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
  2019. emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
  2020. Pred, PredReg);
  2021. } else {
  2022. assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
  2023. emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
  2024. Pred, PredReg);
  2025. }
  2026. }
  2027. }
  2028. return MBB.erase(I);
  2029. }
  2030. /// Get the minimum constant for ARM that is greater than or equal to the
  2031. /// argument. In ARM, constants can have any value that can be produced by
  2032. /// rotating an 8-bit value to the right by an even number of bits within a
  2033. /// 32-bit word.
  2034. static uint32_t alignToARMConstant(uint32_t Value) {
  2035. unsigned Shifted = 0;
  2036. if (Value == 0)
  2037. return 0;
  2038. while (!(Value & 0xC0000000)) {
  2039. Value = Value << 2;
  2040. Shifted += 2;
  2041. }
  2042. bool Carry = (Value & 0x00FFFFFF);
  2043. Value = ((Value & 0xFF000000) >> 24) + Carry;
  2044. if (Value & 0x0000100)
  2045. Value = Value & 0x000001FC;
  2046. if (Shifted > 24)
  2047. Value = Value >> (Shifted - 24);
  2048. else
  2049. Value = Value << (24 - Shifted);
  2050. return Value;
  2051. }
  2052. // The stack limit in the TCB is set to this many bytes above the actual
  2053. // stack limit.
  2054. static const uint64_t kSplitStackAvailable = 256;
  2055. // Adjust the function prologue to enable split stacks. This currently only
  2056. // supports android and linux.
  2057. //
  2058. // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
  2059. // must be well defined in order to allow for consistent implementations of the
  2060. // __morestack helper function. The ABI is also not a normal ABI in that it
  2061. // doesn't follow the normal calling conventions because this allows the
  2062. // prologue of each function to be optimized further.
  2063. //
  2064. // Currently, the ABI looks like (when calling __morestack)
  2065. //
  2066. // * r4 holds the minimum stack size requested for this function call
  2067. // * r5 holds the stack size of the arguments to the function
  2068. // * the beginning of the function is 3 instructions after the call to
  2069. // __morestack
  2070. //
  2071. // Implementations of __morestack should use r4 to allocate a new stack, r5 to
  2072. // place the arguments on to the new stack, and the 3-instruction knowledge to
  2073. // jump directly to the body of the function when working on the new stack.
  2074. //
  2075. // An old (and possibly no longer compatible) implementation of __morestack for
  2076. // ARM can be found at [1].
  2077. //
  2078. // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
  2079. void ARMFrameLowering::adjustForSegmentedStacks(
  2080. MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
  2081. unsigned Opcode;
  2082. unsigned CFIIndex;
  2083. const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
  2084. bool Thumb = ST->isThumb();
  2085. // Sadly, this currently doesn't support varargs, platforms other than
  2086. // android/linux. Note that thumb1/thumb2 are support for android/linux.
  2087. if (MF.getFunction().isVarArg())
  2088. report_fatal_error("Segmented stacks do not support vararg functions.");
  2089. if (!ST->isTargetAndroid() && !ST->isTargetLinux())
  2090. report_fatal_error("Segmented stacks not supported on this platform.");
  2091. MachineFrameInfo &MFI = MF.getFrameInfo();
  2092. MachineModuleInfo &MMI = MF.getMMI();
  2093. MCContext &Context = MMI.getContext();
  2094. const MCRegisterInfo *MRI = Context.getRegisterInfo();
  2095. const ARMBaseInstrInfo &TII =
  2096. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  2097. ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
  2098. DebugLoc DL;
  2099. uint64_t StackSize = MFI.getStackSize();
  2100. // Do not generate a prologue for leaf functions with a stack of size zero.
  2101. // For non-leaf functions we have to allow for the possibility that the
  2102. // callis to a non-split function, as in PR37807. This function could also
  2103. // take the address of a non-split function. When the linker tries to adjust
  2104. // its non-existent prologue, it would fail with an error. Mark the object
  2105. // file so that such failures are not errors. See this Go language bug-report
  2106. // https://go-review.googlesource.com/c/go/+/148819/
  2107. if (StackSize == 0 && !MFI.hasTailCall()) {
  2108. MF.getMMI().setHasNosplitStack(true);
  2109. return;
  2110. }
  2111. // Use R4 and R5 as scratch registers.
  2112. // We save R4 and R5 before use and restore them before leaving the function.
  2113. unsigned ScratchReg0 = ARM::R4;
  2114. unsigned ScratchReg1 = ARM::R5;
  2115. uint64_t AlignedStackSize;
  2116. MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
  2117. MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
  2118. MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
  2119. MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
  2120. MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
  2121. // Grab everything that reaches PrologueMBB to update there liveness as well.
  2122. SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
  2123. SmallVector<MachineBasicBlock *, 2> WalkList;
  2124. WalkList.push_back(&PrologueMBB);
  2125. do {
  2126. MachineBasicBlock *CurMBB = WalkList.pop_back_val();
  2127. for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
  2128. if (BeforePrologueRegion.insert(PredBB).second)
  2129. WalkList.push_back(PredBB);
  2130. }
  2131. } while (!WalkList.empty());
  2132. // The order in that list is important.
  2133. // The blocks will all be inserted before PrologueMBB using that order.
  2134. // Therefore the block that should appear first in the CFG should appear
  2135. // first in the list.
  2136. MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
  2137. PostStackMBB};
  2138. for (MachineBasicBlock *B : AddedBlocks)
  2139. BeforePrologueRegion.insert(B);
  2140. for (const auto &LI : PrologueMBB.liveins()) {
  2141. for (MachineBasicBlock *PredBB : BeforePrologueRegion)
  2142. PredBB->addLiveIn(LI);
  2143. }
  2144. // Remove the newly added blocks from the list, since we know
  2145. // we do not have to do the following updates for them.
  2146. for (MachineBasicBlock *B : AddedBlocks) {
  2147. BeforePrologueRegion.erase(B);
  2148. MF.insert(PrologueMBB.getIterator(), B);
  2149. }
  2150. for (MachineBasicBlock *MBB : BeforePrologueRegion) {
  2151. // Make sure the LiveIns are still sorted and unique.
  2152. MBB->sortUniqueLiveIns();
  2153. // Replace the edges to PrologueMBB by edges to the sequences
  2154. // we are about to add.
  2155. MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
  2156. }
  2157. // The required stack size that is aligned to ARM constant criterion.
  2158. AlignedStackSize = alignToARMConstant(StackSize);
  2159. // When the frame size is less than 256 we just compare the stack
  2160. // boundary directly to the value of the stack pointer, per gcc.
  2161. bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
  2162. // We will use two of the callee save registers as scratch registers so we
  2163. // need to save those registers onto the stack.
  2164. // We will use SR0 to hold stack limit and SR1 to hold the stack size
  2165. // requested and arguments for __morestack().
  2166. // SR0: Scratch Register #0
  2167. // SR1: Scratch Register #1
  2168. // push {SR0, SR1}
  2169. if (Thumb) {
  2170. BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
  2171. .add(predOps(ARMCC::AL))
  2172. .addReg(ScratchReg0)
  2173. .addReg(ScratchReg1);
  2174. } else {
  2175. BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
  2176. .addReg(ARM::SP, RegState::Define)
  2177. .addReg(ARM::SP)
  2178. .add(predOps(ARMCC::AL))
  2179. .addReg(ScratchReg0)
  2180. .addReg(ScratchReg1);
  2181. }
  2182. // Emit the relevant DWARF information about the change in stack pointer as
  2183. // well as where to find both r4 and r5 (the callee-save registers)
  2184. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 8));
  2185. BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2186. .addCFIIndex(CFIIndex);
  2187. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  2188. nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
  2189. BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2190. .addCFIIndex(CFIIndex);
  2191. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  2192. nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
  2193. BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2194. .addCFIIndex(CFIIndex);
  2195. // mov SR1, sp
  2196. if (Thumb) {
  2197. BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
  2198. .addReg(ARM::SP)
  2199. .add(predOps(ARMCC::AL));
  2200. } else if (CompareStackPointer) {
  2201. BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
  2202. .addReg(ARM::SP)
  2203. .add(predOps(ARMCC::AL))
  2204. .add(condCodeOp());
  2205. }
  2206. // sub SR1, sp, #StackSize
  2207. if (!CompareStackPointer && Thumb) {
  2208. BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
  2209. .add(condCodeOp())
  2210. .addReg(ScratchReg1)
  2211. .addImm(AlignedStackSize)
  2212. .add(predOps(ARMCC::AL));
  2213. } else if (!CompareStackPointer) {
  2214. BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
  2215. .addReg(ARM::SP)
  2216. .addImm(AlignedStackSize)
  2217. .add(predOps(ARMCC::AL))
  2218. .add(condCodeOp());
  2219. }
  2220. if (Thumb && ST->isThumb1Only()) {
  2221. unsigned PCLabelId = ARMFI->createPICLabelUId();
  2222. ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
  2223. MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
  2224. MachineConstantPool *MCP = MF.getConstantPool();
  2225. unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4));
  2226. // ldr SR0, [pc, offset(STACK_LIMIT)]
  2227. BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
  2228. .addConstantPoolIndex(CPI)
  2229. .add(predOps(ARMCC::AL));
  2230. // ldr SR0, [SR0]
  2231. BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
  2232. .addReg(ScratchReg0)
  2233. .addImm(0)
  2234. .add(predOps(ARMCC::AL));
  2235. } else {
  2236. // Get TLS base address from the coprocessor
  2237. // mrc p15, #0, SR0, c13, c0, #3
  2238. BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
  2239. ScratchReg0)
  2240. .addImm(15)
  2241. .addImm(0)
  2242. .addImm(13)
  2243. .addImm(0)
  2244. .addImm(3)
  2245. .add(predOps(ARMCC::AL));
  2246. // Use the last tls slot on android and a private field of the TCP on linux.
  2247. assert(ST->isTargetAndroid() || ST->isTargetLinux());
  2248. unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
  2249. // Get the stack limit from the right offset
  2250. // ldr SR0, [sr0, #4 * TlsOffset]
  2251. BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
  2252. ScratchReg0)
  2253. .addReg(ScratchReg0)
  2254. .addImm(4 * TlsOffset)
  2255. .add(predOps(ARMCC::AL));
  2256. }
  2257. // Compare stack limit with stack size requested.
  2258. // cmp SR0, SR1
  2259. Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
  2260. BuildMI(GetMBB, DL, TII.get(Opcode))
  2261. .addReg(ScratchReg0)
  2262. .addReg(ScratchReg1)
  2263. .add(predOps(ARMCC::AL));
  2264. // This jump is taken if StackLimit < SP - stack required.
  2265. Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
  2266. BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
  2267. .addImm(ARMCC::LO)
  2268. .addReg(ARM::CPSR);
  2269. // Calling __morestack(StackSize, Size of stack arguments).
  2270. // __morestack knows that the stack size requested is in SR0(r4)
  2271. // and amount size of stack arguments is in SR1(r5).
  2272. // Pass first argument for the __morestack by Scratch Register #0.
  2273. // The amount size of stack required
  2274. if (Thumb) {
  2275. BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
  2276. .add(condCodeOp())
  2277. .addImm(AlignedStackSize)
  2278. .add(predOps(ARMCC::AL));
  2279. } else {
  2280. BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
  2281. .addImm(AlignedStackSize)
  2282. .add(predOps(ARMCC::AL))
  2283. .add(condCodeOp());
  2284. }
  2285. // Pass second argument for the __morestack by Scratch Register #1.
  2286. // The amount size of stack consumed to save function arguments.
  2287. if (Thumb) {
  2288. BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
  2289. .add(condCodeOp())
  2290. .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
  2291. .add(predOps(ARMCC::AL));
  2292. } else {
  2293. BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
  2294. .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
  2295. .add(predOps(ARMCC::AL))
  2296. .add(condCodeOp());
  2297. }
  2298. // push {lr} - Save return address of this function.
  2299. if (Thumb) {
  2300. BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
  2301. .add(predOps(ARMCC::AL))
  2302. .addReg(ARM::LR);
  2303. } else {
  2304. BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
  2305. .addReg(ARM::SP, RegState::Define)
  2306. .addReg(ARM::SP)
  2307. .add(predOps(ARMCC::AL))
  2308. .addReg(ARM::LR);
  2309. }
  2310. // Emit the DWARF info about the change in stack as well as where to find the
  2311. // previous link register
  2312. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 12));
  2313. BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2314. .addCFIIndex(CFIIndex);
  2315. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  2316. nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
  2317. BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2318. .addCFIIndex(CFIIndex);
  2319. // Call __morestack().
  2320. if (Thumb) {
  2321. BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
  2322. .add(predOps(ARMCC::AL))
  2323. .addExternalSymbol("__morestack");
  2324. } else {
  2325. BuildMI(AllocMBB, DL, TII.get(ARM::BL))
  2326. .addExternalSymbol("__morestack");
  2327. }
  2328. // pop {lr} - Restore return address of this original function.
  2329. if (Thumb) {
  2330. if (ST->isThumb1Only()) {
  2331. BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
  2332. .add(predOps(ARMCC::AL))
  2333. .addReg(ScratchReg0);
  2334. BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
  2335. .addReg(ScratchReg0)
  2336. .add(predOps(ARMCC::AL));
  2337. } else {
  2338. BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
  2339. .addReg(ARM::LR, RegState::Define)
  2340. .addReg(ARM::SP, RegState::Define)
  2341. .addReg(ARM::SP)
  2342. .addImm(4)
  2343. .add(predOps(ARMCC::AL));
  2344. }
  2345. } else {
  2346. BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
  2347. .addReg(ARM::SP, RegState::Define)
  2348. .addReg(ARM::SP)
  2349. .add(predOps(ARMCC::AL))
  2350. .addReg(ARM::LR);
  2351. }
  2352. // Restore SR0 and SR1 in case of __morestack() was called.
  2353. // __morestack() will skip PostStackMBB block so we need to restore
  2354. // scratch registers from here.
  2355. // pop {SR0, SR1}
  2356. if (Thumb) {
  2357. BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
  2358. .add(predOps(ARMCC::AL))
  2359. .addReg(ScratchReg0)
  2360. .addReg(ScratchReg1);
  2361. } else {
  2362. BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
  2363. .addReg(ARM::SP, RegState::Define)
  2364. .addReg(ARM::SP)
  2365. .add(predOps(ARMCC::AL))
  2366. .addReg(ScratchReg0)
  2367. .addReg(ScratchReg1);
  2368. }
  2369. // Update the CFA offset now that we've popped
  2370. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
  2371. BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2372. .addCFIIndex(CFIIndex);
  2373. // Return from this function.
  2374. BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
  2375. // Restore SR0 and SR1 in case of __morestack() was not called.
  2376. // pop {SR0, SR1}
  2377. if (Thumb) {
  2378. BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
  2379. .add(predOps(ARMCC::AL))
  2380. .addReg(ScratchReg0)
  2381. .addReg(ScratchReg1);
  2382. } else {
  2383. BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
  2384. .addReg(ARM::SP, RegState::Define)
  2385. .addReg(ARM::SP)
  2386. .add(predOps(ARMCC::AL))
  2387. .addReg(ScratchReg0)
  2388. .addReg(ScratchReg1);
  2389. }
  2390. // Update the CFA offset now that we've popped
  2391. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
  2392. BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2393. .addCFIIndex(CFIIndex);
  2394. // Tell debuggers that r4 and r5 are now the same as they were in the
  2395. // previous function, that they're the "Same Value".
  2396. CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
  2397. nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
  2398. BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2399. .addCFIIndex(CFIIndex);
  2400. CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
  2401. nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
  2402. BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2403. .addCFIIndex(CFIIndex);
  2404. // Organizing MBB lists
  2405. PostStackMBB->addSuccessor(&PrologueMBB);
  2406. AllocMBB->addSuccessor(PostStackMBB);
  2407. GetMBB->addSuccessor(PostStackMBB);
  2408. GetMBB->addSuccessor(AllocMBB);
  2409. McrMBB->addSuccessor(GetMBB);
  2410. PrevStackMBB->addSuccessor(McrMBB);
  2411. #ifdef EXPENSIVE_CHECKS
  2412. MF.verify();
  2413. #endif
  2414. }