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