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