blob: 2b0ceaa66258e98d85fe1c7c9d49803424ac738e [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//
9//===----------------------------------------------------------------------===//
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000010
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000011#define DEBUG_TYPE "hexagon-pei"
12
Craig Topperb25fda92012-03-17 18:46:09 +000013#include "HexagonFrameLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "HexagonBlockRanges.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
19#include "HexagonTargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000020#include "MCTargetDesc/HexagonBaseInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000021#include "llvm/ADT/BitVector.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000022#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000025#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000026#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/SmallVector.h"
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +000029#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000030#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000031#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000032#include "llvm/CodeGen/MachineFrameInfo.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000033#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000035#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000037#include "llvm/CodeGen/MachineMemOperand.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000038#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000039#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000040#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000041#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/RegisterScavenging.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000043#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000045#include "llvm/MC/MCDwarf.h"
46#include "llvm/MC/MCRegisterInfo.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/CodeGen.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000050#include "llvm/Support/Debug.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000051#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/MathExtras.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000053#include "llvm/Support/raw_ostream.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000054#include "llvm/Target/TargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000055#include "llvm/Target/TargetRegisterInfo.h"
56#include <algorithm>
57#include <cassert>
58#include <cstdint>
59#include <iterator>
60#include <limits>
61#include <map>
62#include <new>
63#include <utility>
64#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000065
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000066// Hexagon stack frame layout as defined by the ABI:
67//
68// Incoming arguments
69// passed via stack
70// |
71// |
72// SP during function's FP during function's |
73// +-- runtime (top of stack) runtime (bottom) --+ |
74// | | |
75// --++---------------------+------------------+-----------------++-+-------
76// | parameter area for | variable-size | fixed-size |LR| arg
77// | called functions | local objects | local objects |FP|
78// --+----------------------+------------------+-----------------+--+-------
79// <- size known -> <- size unknown -> <- size known ->
80//
81// Low address High address
82//
83// <--- stack growth
84//
85//
86// - In any circumstances, the outgoing function arguments are always accessi-
87// ble using the SP, and the incoming arguments are accessible using the FP.
88// - If the local objects are not aligned, they can always be accessed using
89// the FP.
90// - If there are no variable-sized objects, the local objects can always be
91// accessed using the SP, regardless whether they are aligned or not. (The
92// alignment padding will be at the bottom of the stack (highest address),
93// and so the offset with respect to the SP will be known at the compile-
94// -time.)
95//
96// The only complication occurs if there are both, local aligned objects, and
97// dynamically allocated (variable-sized) objects. The alignment pad will be
98// placed between the FP and the local objects, thus preventing the use of the
99// FP to access the local objects. At the same time, the variable-sized objects
100// will be between the SP and the local objects, thus introducing an unknown
101// distance from the SP to the locals.
102//
103// To avoid this problem, a new register is created that holds the aligned
104// address of the bottom of the stack, referred in the sources as AP (aligned
105// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
106// that aligns AP to the required boundary (a maximum of the alignments of
107// all stack objects, fixed- and variable-sized). All local objects[1] will
108// then use AP as the base pointer.
109// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
110// their name from being allocated at fixed locations on the stack, relative
111// to the FP. In the presence of dynamic allocation and local alignment, such
112// objects can only be accessed through the FP.
113//
114// Illustration of the AP:
115// FP --+
116// |
117// ---------------+---------------------+-----+-----------------------++-+--
118// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
119// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
120// ---------------+---------------------+-----+-----------------+-----+--+--
121// |<-- Multiple of the -->|
122// stack alignment +-- AP
123//
124// The AP is set up at the beginning of the function. Since it is not a dedi-
125// cated (reserved) register, it needs to be kept live throughout the function
126// to be available as the base register for local object accesses.
127// Normally, an address of a stack objects is obtained by a pseudo-instruction
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000128// PS_fi. To access local objects with the AP register present, a different
129// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
130// argument compared to PS_fi: the first input register is the AP register.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000131// This keeps the register live between its definition and its uses.
132
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000133// The AP register is originally set up using pseudo-instruction PS_aligna:
134// AP = PS_aligna A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000135// where
136// A - required stack alignment
137// The alignment value must be the maximum of all alignments required by
138// any stack object.
139
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000140// The dynamic allocation uses a pseudo-instruction PS_alloca:
141// Rd = PS_alloca Rs, A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000142// where
143// Rd - address of the allocated space
144// Rs - minimum size (the actual allocated can be larger to accommodate
145// alignment)
146// A - required alignment
147
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000148using namespace llvm;
149
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000150static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
151 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000152
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +0000153static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000154 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
155 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000156
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000157static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000158 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
159 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000160
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000161static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000162 cl::Hidden, cl::desc("Specify Os spill func threshold"),
163 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000164
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000165static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
166 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
167 cl::init(false), cl::ZeroOrMore);
168
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000169static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
170 cl::init(true), cl::Hidden, cl::ZeroOrMore,
171 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000172
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000173static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
174 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
175 cl::desc("Max count of stack frame shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000176
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000177static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
178 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
179 cl::init(false), cl::ZeroOrMore);
180
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000181static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
182 cl::Hidden, cl::desc("Use allocframe more conservatively"));
183
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000184static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
185 cl::init(true), cl::desc("Optimize spill slots"));
186
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000187#ifndef NDEBUG
188static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000189 cl::init(std::numeric_limits<unsigned>::max()));
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000190static unsigned SpillOptCount = 0;
191#endif
192
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000193namespace llvm {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000194
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000195 void initializeHexagonCallFrameInformationPass(PassRegistry&);
196 FunctionPass *createHexagonCallFrameInformation();
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000197
198} // end namespace llvm
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000199
200namespace {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000201
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000202 class HexagonCallFrameInformation : public MachineFunctionPass {
203 public:
204 static char ID;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000205
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000206 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
207 PassRegistry &PR = *PassRegistry::getPassRegistry();
208 initializeHexagonCallFrameInformationPass(PR);
209 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000210
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000211 bool runOnMachineFunction(MachineFunction &MF) override;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000212
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000213 MachineFunctionProperties getRequiredProperties() const override {
214 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000215 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000216 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000217 };
218
219 char HexagonCallFrameInformation::ID = 0;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000220
221} // end anonymous namespace
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000222
223bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
224 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
225 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
226 MF.getFunction()->needsUnwindTableEntry();
227
228 if (!NeedCFI)
229 return false;
230 HFI.insertCFIInstructions(MF);
231 return true;
232}
233
234INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
235 "Hexagon call frame information", false, false)
236
237FunctionPass *llvm::createHexagonCallFrameInformation() {
238 return new HexagonCallFrameInformation();
239}
240
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000241/// Map a register pair Reg to the subregister that has the greater "number",
242/// i.e. D3 (aka R7:6) will be mapped to R7, etc.
243static unsigned getMax32BitSubRegister(unsigned Reg,
244 const TargetRegisterInfo &TRI,
245 bool hireg = true) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000246 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
247 return Reg;
248
249 unsigned RegNo = 0;
250 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
251 if (hireg) {
252 if (*SubRegs > RegNo)
253 RegNo = *SubRegs;
254 } else {
255 if (!RegNo || *SubRegs < RegNo)
256 RegNo = *SubRegs;
257 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000258 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000259 return RegNo;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000260}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000261
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000262/// Returns the callee saved register with the largest id in the vector.
263static unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
264 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000265 static_assert(Hexagon::R1 > 0,
266 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 if (CSI.empty())
268 return 0;
269
270 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
271 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
272 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
273 if (Reg > Max)
274 Max = Reg;
275 }
276 return Max;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000277}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000278
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000279/// Checks if the basic block contains any instruction that needs a stack
280/// frame to be already in place.
281static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
282 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000283 for (auto &I : MBB) {
284 const MachineInstr *MI = &I;
285 if (MI->isCall())
286 return true;
287 unsigned Opc = MI->getOpcode();
288 switch (Opc) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000289 case Hexagon::PS_alloca:
290 case Hexagon::PS_aligna:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000291 return true;
292 default:
293 break;
294 }
295 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000296 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000297 // While the presence of a frame index does not prove that a stack
298 // frame will be required, all frame indexes should be within alloc-
299 // frame/deallocframe. Otherwise, the code that translates a frame
300 // index into an offset would have to be aware of the placement of
301 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000302 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000303 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000304 if (MO.isReg()) {
305 unsigned R = MO.getReg();
306 // Virtual registers will need scavenging, which then may require
307 // a stack slot.
308 if (TargetRegisterInfo::isVirtualRegister(R))
Rafael Espindola6eab4042017-02-17 02:08:58 +0000309 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000310 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
311 if (CSR[*S])
312 return true;
313 continue;
314 }
315 if (MO.isRegMask()) {
316 // A regmask would normally have all callee-saved registers marked
317 // as preserved, so this check would not be needed, but in case of
318 // ever having other regmasks (for other calling conventions),
319 // make sure they would be processed correctly.
320 const uint32_t *BM = MO.getRegMask();
321 for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
322 unsigned R = x;
323 // If this regmask does not preserve a CSR, a frame will be needed.
324 if (!(BM[R/32] & (1u << (R%32))))
325 return true;
326 }
327 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000328 }
329 }
330 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000331}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000332
333 /// Returns true if MBB has a machine instructions that indicates a tail call
334 /// in the block.
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000335static bool hasTailCall(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000336 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
337 unsigned RetOpc = I->getOpcode();
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000338 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000339}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000340
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000341/// Returns true if MBB contains an instruction that returns.
342static bool hasReturn(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000343 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
344 if (I->isReturn())
345 return true;
346 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000347}
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000348
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000349/// Returns the "return" instruction from this block, or nullptr if there
350/// isn't any.
351static MachineInstr *getReturn(MachineBasicBlock &MBB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000352 for (auto &I : MBB)
353 if (I.isReturn())
354 return &I;
355 return nullptr;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000356}
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000357
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000358static bool isRestoreCall(unsigned Opc) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000359 switch (Opc) {
360 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
361 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000362 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
363 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
364 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
365 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000366 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
367 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
368 return true;
369 }
370 return false;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000371}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000372
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000373static inline bool isOptNone(const MachineFunction &MF) {
374 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
375 MF.getTarget().getOptLevel() == CodeGenOpt::None;
376}
377
378static inline bool isOptSize(const MachineFunction &MF) {
379 const Function &F = *MF.getFunction();
380 return F.optForSize() && !F.optForMinSize();
381}
382
383static inline bool isMinSize(const MachineFunction &MF) {
384 return MF.getFunction()->optForMinSize();
385}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000386
387/// Implements shrink-wrapping of the stack frame. By default, stack frame
388/// is created in the function entry block, and is cleaned up in every block
389/// that returns. This function finds alternate blocks: one for the frame
390/// setup (prolog) and one for the cleanup (epilog).
391void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
392 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
393 static unsigned ShrinkCounter = 0;
394
395 if (ShrinkLimit.getPosition()) {
396 if (ShrinkCounter >= ShrinkLimit)
397 return;
398 ShrinkCounter++;
399 }
400
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000401 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000402 auto &HRI = *HST.getRegisterInfo();
403
404 MachineDominatorTree MDT;
405 MDT.runOnMachineFunction(MF);
406 MachinePostDominatorTree MPT;
407 MPT.runOnMachineFunction(MF);
408
409 typedef DenseMap<unsigned,unsigned> UnsignedMap;
410 UnsignedMap RPO;
411 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
412 RPOTType RPOT(&MF);
413 unsigned RPON = 0;
414 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
415 RPO[(*I)->getNumber()] = RPON++;
416
417 // Don't process functions that have loops, at least for now. Placement
418 // of prolog and epilog must take loop structure into account. For simpli-
419 // city don't do it right now.
420 for (auto &I : MF) {
421 unsigned BN = RPO[I.getNumber()];
422 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
423 // If found a back-edge, return.
424 if (RPO[(*SI)->getNumber()] <= BN)
425 return;
426 }
427 }
428
429 // Collect the set of blocks that need a stack frame to execute. Scan
430 // each block for uses/defs of callee-saved registers, calls, etc.
431 SmallVector<MachineBasicBlock*,16> SFBlocks;
432 BitVector CSR(Hexagon::NUM_TARGET_REGS);
433 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000434 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
435 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000436
437 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000438 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000439 SFBlocks.push_back(&I);
440
441 DEBUG({
442 dbgs() << "Blocks needing SF: {";
443 for (auto &B : SFBlocks)
444 dbgs() << " BB#" << B->getNumber();
445 dbgs() << " }\n";
446 });
447 // No frame needed?
448 if (SFBlocks.empty())
449 return;
450
451 // Pick a common dominator and a common post-dominator.
452 MachineBasicBlock *DomB = SFBlocks[0];
453 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
454 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
455 if (!DomB)
456 break;
457 }
458 MachineBasicBlock *PDomB = SFBlocks[0];
459 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
460 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
461 if (!PDomB)
462 break;
463 }
464 DEBUG({
465 dbgs() << "Computed dom block: BB#";
466 if (DomB) dbgs() << DomB->getNumber();
467 else dbgs() << "<null>";
468 dbgs() << ", computed pdom block: BB#";
469 if (PDomB) dbgs() << PDomB->getNumber();
470 else dbgs() << "<null>";
471 dbgs() << "\n";
472 });
473 if (!DomB || !PDomB)
474 return;
475
476 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
477 if (!MDT.dominates(DomB, PDomB)) {
478 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
479 return;
480 }
481 if (!MPT.dominates(PDomB, DomB)) {
482 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
483 return;
484 }
485
486 // Finally, everything seems right.
487 PrologB = DomB;
488 EpilogB = PDomB;
489}
490
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000491/// Perform most of the PEI work here:
492/// - saving/restoring of the callee-saved registers,
493/// - stack frame creation and destruction.
494/// Normally, this work is distributed among various functions, but doing it
495/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000496void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
497 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000498 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000499 auto &HRI = *HST.getRegisterInfo();
500
Matthias Braun941a7052016-07-28 18:40:00 +0000501 MachineFrameInfo &MFI = MF.getFrameInfo();
502 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000503
504 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
505 if (EnableShrinkWrapping)
506 findShrunkPrologEpilog(MF, PrologB, EpilogB);
507
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000508 bool PrologueStubs = false;
509 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
510 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000511 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000512
513 if (EpilogB) {
514 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
515 insertEpilogueInBlock(*EpilogB);
516 } else {
517 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000518 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000519 insertCSRRestoresInBlock(B, CSI, HRI);
520
521 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000522 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000523 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000524
525 for (auto &B : MF) {
526 if (B.empty())
527 continue;
528 MachineInstr *RetI = getReturn(B);
529 if (!RetI || isRestoreCall(RetI->getOpcode()))
530 continue;
531 for (auto &R : CSI)
532 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
533 }
534 }
535
536 if (EpilogB) {
537 // If there is an epilog block, it may not have a return instruction.
538 // In such case, we need to add the callee-saved registers as live-ins
539 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000540 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000541 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000542 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000543 }
544}
545
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000546void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
547 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000548 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000549 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000550 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000551 auto &HII = *HST.getInstrInfo();
552 auto &HRI = *HST.getRegisterInfo();
553 DebugLoc dl;
554
Krzysztof Parzyszek71702172017-06-23 19:47:04 +0000555 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000556
557 // Calculate the total stack frame size.
558 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000559 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000560 // Round up the max call frame size to the max alignment on the stack.
Matthias Braun941a7052016-07-28 18:40:00 +0000561 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
562 MFI.setMaxCallFrameSize(MaxCFA);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000563
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000564 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Matthias Braun941a7052016-07-28 18:40:00 +0000565 MFI.setStackSize(FrameSize);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000566
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000567 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000568
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000569 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000570 unsigned NumBytes = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000571 unsigned SP = HRI.getStackRegister();
Matthias Braun941a7052016-07-28 18:40:00 +0000572 unsigned MaxCF = MFI.getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000573 MachineBasicBlock::iterator InsertPt = MBB.begin();
574
Krzysztof Parzyszek8849a512016-08-19 18:46:13 +0000575 SmallVector<MachineInstr *, 4> AdjustRegs;
576 for (auto &MBB : MF)
577 for (auto &MI : MBB)
578 if (MI.getOpcode() == Hexagon::PS_alloca)
579 AdjustRegs.push_back(&MI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000580
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000581 for (auto MI : AdjustRegs) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000582 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000583 expandAlloca(MI, HII, SP, MaxCF);
584 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000585 }
586
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000587 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000588 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000589
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000590 // Check for overflow.
591 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
592 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000593
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000594 // Create a dummy memory operand to avoid allocframe from being treated as
595 // a volatile memory reference.
596 MachineMemOperand *MMO =
597 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
598 4, 4);
599
600 if (NumBytes >= ALLOCFRAME_MAX) {
601 // Emit allocframe(#0).
602 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
603 .addImm(0)
604 .addMemOperand(MMO);
605
606 // Subtract offset from frame pointer.
607 // We use a caller-saved non-parameter register for that.
608 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000609 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32),
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000610 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000611 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
612 .addReg(SP)
613 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000614 } else {
615 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
616 .addImm(NumBytes)
617 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000618 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000619
620 if (AlignStack) {
621 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
622 .addReg(SP)
623 .addImm(-int64_t(MaxAlign));
624 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000625
626 // If the stack-checking is enabled, and we spilled the callee-saved
627 // registers inline (i.e. did not use a spill function), then call
628 // the stack checker directly.
629 if (EnableStackOVFSanitizer && !PrologueStubs)
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000630 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000631 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000632}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000633
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000634void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
635 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000636 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000637 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000638
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000639 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000640 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000641 auto &HRI = *HST.getRegisterInfo();
642 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000643
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000644 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000645 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
646
647 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
648 DebugLoc DL;
649 if (InsertPt != MBB.end())
650 DL = InsertPt->getDebugLoc();
651 else if (!MBB.empty())
652 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000653
654 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000655 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000656 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
657 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
658 .addReg(SP)
659 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000660 return;
661 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000662
663 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
664 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000665 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000666 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
667 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
668 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000669 MachineBasicBlock::iterator It = RetI;
670 ++It;
671 // Delete all instructions after the RESTORE (except labels).
672 while (It != MBB.end()) {
673 if (!It->isLabel())
674 It = MBB.erase(It);
675 else
676 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000677 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000678 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000679 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000680
681 // It is possible that the restoring code is a call to a library function.
682 // All of the restore* functions include "deallocframe", so we need to make
683 // sure that we don't add an extra one.
684 bool NeedsDeallocframe = true;
685 if (!MBB.empty() && InsertPt != MBB.begin()) {
686 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
687 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000688 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000689 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
690 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
691 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000692 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000693 NeedsDeallocframe = false;
694 }
695
696 if (!NeedsDeallocframe)
697 return;
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000698 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000699 // otherwise just add deallocframe. The function could be returning via a
700 // tail call.
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000701 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000702 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
703 return;
704 }
705 unsigned NewOpc = Hexagon::L4_return;
706 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
707 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000708 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000709 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000710}
711
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000712void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
713 MachineBasicBlock &SaveB) const {
714 SetVector<unsigned> Worklist;
715
716 MachineBasicBlock &EntryB = MF.front();
717 Worklist.insert(EntryB.getNumber());
718
719 unsigned SaveN = SaveB.getNumber();
Matthias Braun941a7052016-07-28 18:40:00 +0000720 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000721
722 for (unsigned i = 0; i < Worklist.size(); ++i) {
723 unsigned BN = Worklist[i];
724 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
725 for (auto &R : CSI)
726 if (!MBB.isLiveIn(R.getReg()))
727 MBB.addLiveIn(R.getReg());
728 if (BN != SaveN)
729 for (auto &SB : MBB.successors())
730 Worklist.insert(SB->getNumber());
731 }
732}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000733
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000734bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000735 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000736 BitVector &Path) const {
737 assert(MBB.getNumber() >= 0);
738 unsigned BN = MBB.getNumber();
739 if (Path[BN] || DoneF[BN])
740 return false;
741 if (DoneT[BN])
742 return true;
743
Matthias Braun941a7052016-07-28 18:40:00 +0000744 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000745
746 Path[BN] = true;
747 bool ReachedExit = false;
748 for (auto &SB : MBB.successors())
749 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
750
751 if (!MBB.empty() && MBB.back().isReturn()) {
752 // Add implicit uses of all callee-saved registers to the reached
753 // return instructions. This is to prevent the anti-dependency breaker
754 // from renaming these registers.
755 MachineInstr &RetI = MBB.back();
756 if (!isRestoreCall(RetI.getOpcode()))
757 for (auto &R : CSI)
758 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
759 ReachedExit = true;
760 }
761
762 // We don't want to add unnecessary live-ins to the restore block: since
763 // the callee-saved registers are being defined in it, the entry of the
764 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000765 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000766 for (auto &R : CSI)
767 if (!MBB.isLiveIn(R.getReg()))
768 MBB.addLiveIn(R.getReg());
769 DoneT[BN] = true;
770 }
771 if (!ReachedExit)
772 DoneF[BN] = true;
773
774 Path[BN] = false;
775 return ReachedExit;
776}
777
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000778static Optional<MachineBasicBlock::iterator>
779findCFILocation(MachineBasicBlock &B) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000780 // The CFI instructions need to be inserted right after allocframe.
781 // An exception to this is a situation where allocframe is bundled
782 // with a call: then the CFI instructions need to be inserted before
783 // the packet with the allocframe+call (in case the call throws an
784 // exception).
785 auto End = B.instr_end();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000786
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000787 for (MachineInstr &I : B) {
788 MachineBasicBlock::iterator It = I.getIterator();
789 if (!I.isBundle()) {
790 if (I.getOpcode() == Hexagon::S2_allocframe)
791 return std::next(It);
792 continue;
793 }
794 // I is a bundle.
795 bool HasCall = false, HasAllocFrame = false;
796 auto T = It.getInstrIterator();
797 while (++T != End && T->isBundled()) {
798 if (T->getOpcode() == Hexagon::S2_allocframe)
799 HasAllocFrame = true;
800 else if (T->isCall())
801 HasCall = true;
802 }
803 if (HasAllocFrame)
804 return HasCall ? It : std::next(It);
805 }
806 return None;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000807}
808
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000809void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
810 for (auto &B : MF) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000811 auto At = findCFILocation(B);
812 if (At.hasValue())
813 insertCFIInstructionsAt(B, At.getValue());
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000814 }
815}
816
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000817void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
818 MachineBasicBlock::iterator At) const {
819 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000820 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000821 MachineModuleInfo &MMI = MF.getMMI();
822 auto &HST = MF.getSubtarget<HexagonSubtarget>();
823 auto &HII = *HST.getInstrInfo();
824 auto &HRI = *HST.getRegisterInfo();
825
826 // If CFI instructions have debug information attached, something goes
827 // wrong with the final assembly generation: the prolog_end is placed
828 // in a wrong location.
829 DebugLoc DL;
830 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
831
832 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000833 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000834
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000835 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000836 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
837 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000838
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000839 // Define CFA via an offset from the value of FP.
840 //
841 // -8 -4 0 (SP)
842 // --+----+----+---------------------
843 // | FP | LR | increasing addresses -->
844 // --+----+----+---------------------
845 // | +-- Old SP (before allocframe)
846 // +-- New FP (after allocframe)
847 //
848 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
849 // MCCFIInstruction::createOffset takes the offset without sign change.
850 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
851 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000852 .addCFIIndex(MF.addFrameInst(DefCfa));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000853 // R31 (return addr) = CFA - 4
854 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
855 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000856 .addCFIIndex(MF.addFrameInst(OffR31));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000857 // R30 (frame ptr) = CFA - 8
858 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
859 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000860 .addCFIIndex(MF.addFrameInst(OffR30));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000861 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000862
863 static unsigned int RegsToMove[] = {
864 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
865 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
866 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
867 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
868 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
869 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
870 Hexagon::NoRegister
871 };
872
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000873 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000874
875 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
876 unsigned Reg = RegsToMove[i];
877 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
878 return C.getReg() == Reg;
879 };
David Majnemer562e8292016-08-12 00:18:03 +0000880 auto F = find_if(CSI, IfR);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000881 if (F == CSI.end())
882 continue;
883
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000884 int64_t Offset;
885 if (HasFP) {
886 // If the function has a frame pointer (i.e. has an allocframe),
887 // then the CFA has been defined in terms of FP. Any offsets in
888 // the following CFI instructions have to be defined relative
889 // to FP, which points to the bottom of the stack frame.
890 // The function getFrameIndexReference can still choose to use SP
891 // for the offset calculation, so we cannot simply call it here.
892 // Instead, get the offset (relative to the FP) directly.
893 Offset = MFI.getObjectOffset(F->getFrameIdx());
894 } else {
895 unsigned FrameReg;
896 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
897 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000898 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000899 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000900
901 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
902 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
903 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
904 Offset);
905 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000906 .addCFIIndex(MF.addFrameInst(OffReg));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000907 } else {
908 // Split the double regs into subregs, and generate appropriate
909 // cfi_offsets.
910 // The only reason, we are split double regs is, llvm-mc does not
911 // understand paired registers for cfi_offset.
912 // Eg .cfi_offset r1:0, -64
913
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000914 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
915 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000916 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
917 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
918 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
919 Offset+4);
920 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000921 .addCFIIndex(MF.addFrameInst(OffHi));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000922 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
923 Offset);
924 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000925 .addCFIIndex(MF.addFrameInst(OffLo));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000926 }
927 }
928}
929
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000930bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000931 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000932 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
933
934 bool HasFixed = MFI.getNumFixedObjects();
935 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
936 .getLocalFrameObjectCount();
937 bool HasExtraAlign = HRI.needsStackRealignment(MF);
938 bool HasAlloca = MFI.hasVarSizedObjects();
939
940 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
941 // that this shouldn't be required, but doing so now because gcc does and
942 // gdb can't break at the start of the function without it. Will remove if
943 // this turns out to be a gdb bug.
944 //
945 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
946 return true;
947
948 // By default we want to use SP (since it's always there). FP requires
949 // some setup (i.e. ALLOCFRAME).
950 // Fixed and preallocated objects need FP if the distance from them to
951 // the SP is unknown (as is with alloca or aligna).
952 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
953 return true;
954
955 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000956 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000957 return true;
958 }
959
960 if (MFI.hasCalls() ||
961 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
962 return true;
963
964 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000965}
966
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000967enum SpillKind {
968 SK_ToMem,
969 SK_FromMem,
970 SK_FromMemTailcall
971};
972
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000973static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
974 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000975 const char * V4SpillToMemoryFunctions[] = {
976 "__save_r16_through_r17",
977 "__save_r16_through_r19",
978 "__save_r16_through_r21",
979 "__save_r16_through_r23",
980 "__save_r16_through_r25",
981 "__save_r16_through_r27" };
982
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000983 const char * V4SpillToMemoryStkchkFunctions[] = {
984 "__save_r16_through_r17_stkchk",
985 "__save_r16_through_r19_stkchk",
986 "__save_r16_through_r21_stkchk",
987 "__save_r16_through_r23_stkchk",
988 "__save_r16_through_r25_stkchk",
989 "__save_r16_through_r27_stkchk" };
990
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000991 const char * V4SpillFromMemoryFunctions[] = {
992 "__restore_r16_through_r17_and_deallocframe",
993 "__restore_r16_through_r19_and_deallocframe",
994 "__restore_r16_through_r21_and_deallocframe",
995 "__restore_r16_through_r23_and_deallocframe",
996 "__restore_r16_through_r25_and_deallocframe",
997 "__restore_r16_through_r27_and_deallocframe" };
998
999 const char * V4SpillFromMemoryTailcallFunctions[] = {
1000 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1001 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1002 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1003 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1004 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1005 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1006 };
1007
1008 const char **SpillFunc = nullptr;
1009
1010 switch(SpillType) {
1011 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001012 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1013 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001014 break;
1015 case SK_FromMem:
1016 SpillFunc = V4SpillFromMemoryFunctions;
1017 break;
1018 case SK_FromMemTailcall:
1019 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1020 break;
1021 }
1022 assert(SpillFunc && "Unknown spill kind");
1023
1024 // Spill all callee-saved registers up to the highest register used.
1025 switch (MaxReg) {
1026 case Hexagon::R17:
1027 return SpillFunc[0];
1028 case Hexagon::R19:
1029 return SpillFunc[1];
1030 case Hexagon::R21:
1031 return SpillFunc[2];
1032 case Hexagon::R23:
1033 return SpillFunc[3];
1034 case Hexagon::R25:
1035 return SpillFunc[4];
1036 case Hexagon::R27:
1037 return SpillFunc[5];
1038 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001039 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001040 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001041 return nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001042}
1043
James Y Knight5567baf2015-08-15 02:32:35 +00001044int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001045 int FI, unsigned &FrameReg) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001046 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001047 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001048
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001049 int Offset = MFI.getObjectOffset(FI);
1050 bool HasAlloca = MFI.hasVarSizedObjects();
1051 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1052 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001053
Krzysztof Parzyszek918e6d72017-06-26 14:17:58 +00001054 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001055 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001056 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1057 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek918e6d72017-06-26 14:17:58 +00001058 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1059 // is true. HasExtraAlign may be set because of vector spills, without
1060 // aligned locals or aligned outgoing function arguments. Since vector
1061 // spills will ultimately be "unaligned", it is safe to use FP as the
1062 // base register.
1063 // In fact, in such a scenario the stack is actually not required to be
1064 // aligned, although it may end up being aligned anyway, since this
1065 // particular case is not easily detectable. The alignment will be
1066 // unnecessary, but not incorrect.
1067 // Unfortunately there is no quick way to verify that the above is
1068 // indeed the case (and that it's not a result of an error), so just
1069 // assume that missing AP will be replaced by FP.
1070 // (A better fix would be to rematerialize AP from FP and always align
1071 // vector spills.)
1072 if (AP == 0)
1073 AP = FP;
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001074
1075 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1076 // Use FP at -O0, except when there are objects with extra alignment.
1077 // That additional alignment requirement may cause a pad to be inserted,
1078 // which will make it impossible to use FP to access objects located
1079 // past the pad.
1080 if (NoOpt && !HasExtraAlign)
1081 UseFP = true;
1082 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1083 // Fixed and preallocated objects will be located before any padding
1084 // so FP must be used to access them.
1085 UseFP |= (HasAlloca || HasExtraAlign);
1086 } else {
1087 if (HasAlloca) {
1088 if (HasExtraAlign)
1089 UseAP = true;
1090 else
1091 UseFP = true;
1092 }
1093 }
1094
1095 // If FP was picked, then there had better be FP.
1096 bool HasFP = hasFP(MF);
1097 assert((HasFP || !UseFP) && "This function must have frame pointer");
1098
1099 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1100 // FP/LR. If the base register is used to access an object across these
1101 // 8 bytes, then the offset will need to be adjusted by 8.
1102 //
1103 // After allocframe:
1104 // HexagonISelLowering adds 8 to ---+
1105 // the offsets of all stack-based |
1106 // arguments (*) |
1107 // |
1108 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1109 // ------------------------+-----+------------------------> increasing
1110 // <local objects> |FP/LR| <input arguments> addresses
1111 // -----------------+------+-----+------------------------>
1112 // | |
1113 // SP/AP point --+ +-- FP points here (**)
1114 // somewhere on
1115 // this side of FP/LR
1116 //
1117 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1118 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1119
1120 // The lowering assumes that FP/LR is present, and so the offsets of
1121 // the formal arguments start at 8. If FP/LR is not there we need to
1122 // reduce the offset by 8.
1123 if (Offset > 0 && !HasFP)
1124 Offset -= 8;
1125
1126 if (UseFP)
1127 FrameReg = FP;
1128 else if (UseAP)
1129 FrameReg = AP;
1130 else
1131 FrameReg = SP;
1132
1133 // Calculate the actual offset in the instruction. If there is no FP
1134 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1135 // there will be no SP -= FrameSize), so the frame size should not be
1136 // added to the calculated offset.
1137 int RealOffset = Offset;
1138 if (!UseFP && !UseAP && HasFP)
1139 RealOffset = FrameSize+Offset;
1140 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001141}
1142
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001143bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001144 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1145 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001146 if (CSI.empty())
1147 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001148
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001149 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001150 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001151 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001152 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1153 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001154
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001155 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001156 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001157 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001158 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1159 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1160 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001161 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001162 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001163 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001164
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001165 // Call spill function.
1166 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001167 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001168 if (StkOvrFlowEnabled) {
1169 if (LongCalls)
1170 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1171 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1172 else
1173 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1174 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1175 } else {
1176 if (LongCalls)
1177 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1178 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1179 else
1180 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1181 : Hexagon::SAVE_REGISTERS_CALL_V4;
1182 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001183
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001184 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001185 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001186 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001187
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001188 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001189 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001190 // Add live in registers.
1191 for (unsigned I = 0; I < CSI.size(); ++I)
1192 MBB.addLiveIn(CSI[I].getReg());
1193 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001194 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001195
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001196 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001197 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001198 // Add live in registers. We treat eh_return callee saved register r0 - r3
1199 // specially. They are not really callee saved registers as they are not
1200 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001201 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1202 int FI = CSI[i].getFrameIdx();
1203 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001204 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001205 if (IsKill)
1206 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001207 }
1208 return true;
1209}
1210
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001211bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1212 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1213 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001214 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001215
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001216 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1217 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001218 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1219 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001220
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001221 if (useRestoreFunction(MF, CSI)) {
1222 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1223 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1224 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1225 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001226 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001227 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001228 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001229
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001230 // Call spill function.
1231 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1232 : MBB.getLastNonDebugInstr()->getDebugLoc();
1233 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001234
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001235 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001236 unsigned RetOpc;
1237 if (LongCalls)
1238 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1239 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1240 else
1241 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1242 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1243 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001244 .addExternalSymbol(RestoreFn);
1245 } else {
1246 // The block has a return.
1247 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1248 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001249 unsigned RetOpc;
1250 if (LongCalls)
1251 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1252 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1253 else
1254 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1255 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1256 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001257 .addExternalSymbol(RestoreFn);
1258 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001259 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001260 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001261 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001262 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001263 }
1264
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001265 for (unsigned i = 0; i < CSI.size(); ++i) {
1266 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001267 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1268 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001269 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001270 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001271
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001272 return true;
1273}
1274
Hans Wennborge1a2e902016-03-31 18:33:38 +00001275MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1276 MachineFunction &MF, MachineBasicBlock &MBB,
1277 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001278 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001279 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001280 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001281 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1282 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001283 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001284}
1285
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001286void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1287 MachineFunction &MF, RegScavenger *RS) const {
1288 // If this function has uses aligned stack and also has variable sized stack
1289 // objects, then we need to map all spill slots to fixed positions, so that
1290 // they can be accessed through FP. Otherwise they would have to be accessed
1291 // via AP, which may not be available at the particular place in the program.
Matthias Braun941a7052016-07-28 18:40:00 +00001292 MachineFrameInfo &MFI = MF.getFrameInfo();
1293 bool HasAlloca = MFI.hasVarSizedObjects();
1294 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001295
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001296 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001297 return;
1298
Matthias Braun941a7052016-07-28 18:40:00 +00001299 unsigned LFS = MFI.getLocalFrameSize();
1300 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1301 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001302 continue;
Matthias Braun941a7052016-07-28 18:40:00 +00001303 unsigned S = MFI.getObjectSize(i);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001304 // Reduce the alignment to at most 8. This will require unaligned vector
1305 // stores if they happen here.
Matthias Braun941a7052016-07-28 18:40:00 +00001306 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1307 MFI.setObjectAlignment(i, 8);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001308 LFS = alignTo(LFS+S, A);
Matthias Braun941a7052016-07-28 18:40:00 +00001309 MFI.mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001310 }
1311
Matthias Braun941a7052016-07-28 18:40:00 +00001312 MFI.setLocalFrameSize(LFS);
1313 unsigned A = MFI.getLocalFrameMaxAlign();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001314 assert(A <= 8 && "Unexpected local frame alignment");
1315 if (A == 0)
Matthias Braun941a7052016-07-28 18:40:00 +00001316 MFI.setLocalFrameMaxAlign(8);
1317 MFI.setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001318
1319 // Set the physical aligned-stack base address register.
1320 unsigned AP = 0;
1321 if (const MachineInstr *AI = getAlignaInstr(MF))
1322 AP = AI->getOperand(0).getReg();
1323 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1324 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001325}
1326
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001327/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001328static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001329 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001330 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001331
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001332 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1333 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1334 if (MRI.isPhysRegUsed(*AI))
1335 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001336 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001337 };
1338
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001339 // Check for an unused caller-saved register. Callee-saved registers
1340 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001341 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001342 if (!IsUsed(*P))
1343 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001344
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001345 // All caller-saved registers are used.
1346 return true;
1347}
1348
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001349#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001350static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001351 dbgs() << '{';
1352 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1353 unsigned R = x;
1354 dbgs() << ' ' << PrintReg(R, &TRI);
1355 }
1356 dbgs() << " }";
1357}
1358#endif
1359
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001360bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1361 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Reid Kleckner40d72302016-10-20 00:22:23 +00001362 DEBUG(dbgs() << __func__ << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001363 << MF.getFunction()->getName() << '\n');
Matthias Braun941a7052016-07-28 18:40:00 +00001364 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001365 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001366
1367 // Generate a set of unique, callee-saved registers (SRegs), where each
1368 // register in the set is maximal in terms of sub-/super-register relation,
1369 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1370
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001371 // (1) For each callee-saved register, add that register and all of its
1372 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001373 DEBUG(dbgs() << "Initial CS registers: {");
1374 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1375 unsigned R = CSI[i].getReg();
1376 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1377 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1378 SRegs[*SR] = true;
1379 }
1380 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001381 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001382
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001383 // (2) For each reserved register, remove that register and all of its
1384 // sub- and super-registers from SRegs.
1385 BitVector Reserved = TRI->getReservedRegs(MF);
1386 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1387 unsigned R = x;
1388 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1389 SRegs[*SR] = false;
1390 }
1391 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1392 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1393
1394 // (3) Collect all registers that have at least one sub-register in SRegs,
1395 // and also have no sub-registers that are reserved. These will be the can-
1396 // didates for saving as a whole instead of their individual sub-registers.
1397 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1398 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001399 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1400 unsigned R = x;
1401 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1402 TmpSup[*SR] = true;
1403 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001404 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1405 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001406 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1407 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001408 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001409 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001410 break;
1411 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001412 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001413 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001414
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001415 // (4) Include all super-registers found in (3) into SRegs.
1416 SRegs |= TmpSup;
1417 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001418
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001419 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001420 // remove R from SRegs.
1421 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1422 unsigned R = x;
1423 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1424 if (!SRegs[*SR])
1425 continue;
1426 SRegs[R] = false;
1427 break;
1428 }
1429 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001430 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001431
1432 // Now, for each register that has a fixed stack slot, create the stack
1433 // object for it.
1434 CSI.clear();
1435
1436 typedef TargetFrameLowering::SpillSlot SpillSlot;
1437 unsigned NumFixed;
1438 int MinOffset = 0; // CS offsets are negative.
1439 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1440 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1441 if (!SRegs[S->Reg])
1442 continue;
1443 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001444 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001445 MinOffset = std::min(MinOffset, S->Offset);
1446 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1447 SRegs[S->Reg] = false;
1448 }
1449
1450 // There can be some registers that don't have fixed slots. For example,
1451 // we need to store R0-R3 in functions with exception handling. For each
1452 // such register, create a non-fixed stack object.
1453 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1454 unsigned R = x;
1455 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001456 unsigned Size = TRI->getSpillSize(*RC);
1457 int Off = MinOffset - Size;
1458 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001459 assert(isPowerOf2_32(Align));
1460 Off &= -Align;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001461 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001462 MinOffset = std::min(MinOffset, Off);
1463 CSI.push_back(CalleeSavedInfo(R, FI));
1464 SRegs[R] = false;
1465 }
1466
1467 DEBUG({
1468 dbgs() << "CS information: {";
1469 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1470 int FI = CSI[i].getFrameIdx();
Matthias Braun941a7052016-07-28 18:40:00 +00001471 int Off = MFI.getObjectOffset(FI);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001472 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1473 if (Off >= 0)
1474 dbgs() << '+';
1475 dbgs() << Off;
1476 }
1477 dbgs() << " }\n";
1478 });
1479
1480#ifndef NDEBUG
1481 // Verify that all registers were handled.
1482 bool MissedReg = false;
1483 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1484 unsigned R = x;
1485 dbgs() << PrintReg(R, TRI) << ' ';
1486 MissedReg = true;
1487 }
1488 if (MissedReg)
1489 llvm_unreachable("...there are unhandled callee-saved registers!");
1490#endif
1491
1492 return true;
1493}
1494
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001495bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1496 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1497 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1498 MachineInstr *MI = &*It;
1499 DebugLoc DL = MI->getDebugLoc();
1500 unsigned DstR = MI->getOperand(0).getReg();
1501 unsigned SrcR = MI->getOperand(1).getReg();
1502 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1503 !Hexagon::ModRegsRegClass.contains(SrcR))
1504 return false;
1505
1506 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
Diana Picus116bbab2017-01-13 09:58:52 +00001507 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001508 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1509 .addReg(TmpR, RegState::Kill);
1510
1511 NewRegs.push_back(TmpR);
1512 B.erase(It);
1513 return true;
1514}
1515
1516bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1517 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1518 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1519 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001520 if (!MI->getOperand(0).isFI())
1521 return false;
1522
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001523 DebugLoc DL = MI->getDebugLoc();
1524 unsigned Opc = MI->getOpcode();
1525 unsigned SrcR = MI->getOperand(2).getReg();
1526 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001527 int FI = MI->getOperand(0).getIndex();
1528
1529 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1530 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1531 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1532 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1533 : Hexagon::A2_tfrcrr;
1534 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1535 .addReg(SrcR, getKillRegState(IsKill));
1536
1537 // S2_storeri_io FI, 0, TmpR
1538 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1539 .addFrameIndex(FI)
1540 .addImm(0)
1541 .addReg(TmpR, RegState::Kill)
1542 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1543
1544 NewRegs.push_back(TmpR);
1545 B.erase(It);
1546 return true;
1547}
1548
1549bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1550 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1551 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1552 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001553 if (!MI->getOperand(1).isFI())
1554 return false;
1555
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001556 DebugLoc DL = MI->getDebugLoc();
1557 unsigned Opc = MI->getOpcode();
1558 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001559 int FI = MI->getOperand(1).getIndex();
1560
1561 // TmpR = L2_loadri_io FI, 0
1562 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1563 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1564 .addFrameIndex(FI)
1565 .addImm(0)
1566 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1567
1568 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1569 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1570 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1571 : Hexagon::A2_tfrrcr;
1572 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1573 .addReg(TmpR, RegState::Kill);
1574
1575 NewRegs.push_back(TmpR);
1576 B.erase(It);
1577 return true;
1578}
1579
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001580bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1581 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1582 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1583 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1584 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001585 if (!MI->getOperand(0).isFI())
1586 return false;
1587
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001588 DebugLoc DL = MI->getDebugLoc();
1589 unsigned SrcR = MI->getOperand(2).getReg();
1590 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001591 int FI = MI->getOperand(0).getIndex();
1592
1593 bool Is128B = HST.useHVXDblOps();
1594 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1595 : &Hexagon::VectorRegs128BRegClass;
1596
1597 // Insert transfer to general vector register.
1598 // TmpR0 = A2_tfrsi 0x01010101
1599 // TmpR1 = V6_vandqrt Qx, TmpR0
1600 // store FI, 0, TmpR1
1601 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1602 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1603
1604 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1605 .addImm(0x01010101);
1606
1607 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1608 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1609 .addReg(SrcR, getKillRegState(IsKill))
1610 .addReg(TmpR0, RegState::Kill);
1611
1612 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1613 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1614 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1615
1616 NewRegs.push_back(TmpR0);
1617 NewRegs.push_back(TmpR1);
1618 B.erase(It);
1619 return true;
1620}
1621
1622bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1623 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1624 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1625 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1626 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001627 if (!MI->getOperand(1).isFI())
1628 return false;
1629
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001630 DebugLoc DL = MI->getDebugLoc();
1631 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001632 int FI = MI->getOperand(1).getIndex();
1633
1634 bool Is128B = HST.useHVXDblOps();
1635 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1636 : &Hexagon::VectorRegs128BRegClass;
1637
1638 // TmpR0 = A2_tfrsi 0x01010101
1639 // TmpR1 = load FI, 0
1640 // DstR = V6_vandvrt TmpR1, TmpR0
1641 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1642 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1643
1644 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1645 .addImm(0x01010101);
1646 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1647 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1648 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1649
1650 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1651 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1652 .addReg(TmpR1, RegState::Kill)
1653 .addReg(TmpR0, RegState::Kill);
1654
1655 NewRegs.push_back(TmpR0);
1656 NewRegs.push_back(TmpR1);
1657 B.erase(It);
1658 return true;
1659}
1660
1661bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1662 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1663 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1664 MachineFunction &MF = *B.getParent();
1665 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001666 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001667 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1668 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001669 if (!MI->getOperand(0).isFI())
1670 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001671
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001672 // It is possible that the double vector being stored is only partially
1673 // defined. From the point of view of the liveness tracking, it is ok to
1674 // store it as a whole, but if we break it up we may end up storing a
1675 // register that is entirely undefined.
Matthias Braunac4307c2017-05-26 21:51:00 +00001676 LivePhysRegs LPR(HRI);
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001677 LPR.addLiveIns(B);
1678 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001679 for (auto R = B.begin(); R != It; ++R) {
1680 Clobbers.clear();
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001681 LPR.stepForward(*R, Clobbers);
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001682 // Dead defs are recorded in Clobbers, but are not automatically removed
1683 // from the live set.
1684 for (auto &C : Clobbers)
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +00001685 if (C.second->isReg() && C.second->isDead())
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001686 LPR.removeReg(C.first);
1687 }
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001688
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001689 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001690 unsigned SrcR = MI->getOperand(2).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001691 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1692 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001693 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001694 int FI = MI->getOperand(0).getIndex();
1695
1696 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001697 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1698 : Hexagon::VectorRegs128BRegClass;
1699 unsigned Size = HRI.getSpillSize(RC);
1700 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001701 unsigned HasAlign = MFI.getObjectAlignment(FI);
1702 unsigned StoreOpc;
1703
1704 // Store low part.
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001705 if (LPR.contains(SrcLo)) {
1706 if (NeedAlign <= HasAlign)
1707 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1708 else
1709 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001710
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001711 BuildMI(B, It, DL, HII.get(StoreOpc))
1712 .addFrameIndex(FI)
1713 .addImm(0)
1714 .addReg(SrcLo, getKillRegState(IsKill))
1715 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1716 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001717
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001718 // Store high part.
1719 if (LPR.contains(SrcHi)) {
1720 if (NeedAlign <= MinAlign(HasAlign, Size))
1721 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1722 else
1723 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001724
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001725 BuildMI(B, It, DL, HII.get(StoreOpc))
1726 .addFrameIndex(FI)
1727 .addImm(Size)
1728 .addReg(SrcHi, getKillRegState(IsKill))
1729 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1730 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001731
1732 B.erase(It);
1733 return true;
1734}
1735
1736bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1737 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1738 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1739 MachineFunction &MF = *B.getParent();
1740 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001741 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001742 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1743 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001744 if (!MI->getOperand(1).isFI())
1745 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001746
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001747 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001748 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001749 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1750 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001751 int FI = MI->getOperand(1).getIndex();
1752
1753 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001754 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1755 : Hexagon::VectorRegs128BRegClass;
1756 unsigned Size = HRI.getSpillSize(RC);
1757 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001758 unsigned HasAlign = MFI.getObjectAlignment(FI);
1759 unsigned LoadOpc;
1760
1761 // Load low part.
1762 if (NeedAlign <= HasAlign)
1763 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1764 else
1765 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1766
1767 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1768 .addFrameIndex(FI)
1769 .addImm(0)
1770 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1771
1772 // Load high part.
1773 if (NeedAlign <= MinAlign(HasAlign, Size))
1774 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1775 else
1776 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1777
1778 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1779 .addFrameIndex(FI)
1780 .addImm(Size)
1781 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1782
1783 B.erase(It);
1784 return true;
1785}
1786
1787bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1788 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1789 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1790 MachineFunction &MF = *B.getParent();
1791 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001792 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001793 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001794 if (!MI->getOperand(0).isFI())
1795 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001796
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001797 auto &HRI = *HST.getRegisterInfo();
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001798 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001799 unsigned SrcR = MI->getOperand(2).getReg();
1800 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001801 int FI = MI->getOperand(0).getIndex();
1802
1803 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001804 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1805 : Hexagon::VectorRegs128BRegClass;
1806 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001807 unsigned HasAlign = MFI.getObjectAlignment(FI);
1808 unsigned StoreOpc;
1809
1810 if (NeedAlign <= HasAlign)
1811 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1812 else
1813 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1814
1815 BuildMI(B, It, DL, HII.get(StoreOpc))
1816 .addFrameIndex(FI)
1817 .addImm(0)
1818 .addReg(SrcR, getKillRegState(IsKill))
1819 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1820
1821 B.erase(It);
1822 return true;
1823}
1824
1825bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1826 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1827 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1828 MachineFunction &MF = *B.getParent();
1829 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001830 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001831 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001832 if (!MI->getOperand(1).isFI())
1833 return false;
1834
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001835 auto &HRI = *HST.getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001836 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001837 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001838 int FI = MI->getOperand(1).getIndex();
1839
1840 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001841 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1842 : Hexagon::VectorRegs128BRegClass;
1843 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001844 unsigned HasAlign = MFI.getObjectAlignment(FI);
1845 unsigned LoadOpc;
1846
1847 if (NeedAlign <= HasAlign)
1848 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1849 else
1850 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1851
1852 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1853 .addFrameIndex(FI)
1854 .addImm(0)
1855 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1856
1857 B.erase(It);
1858 return true;
1859}
1860
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001861bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1862 SmallVectorImpl<unsigned> &NewRegs) const {
1863 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001864 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001865 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001866 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001867
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001868 for (auto &B : MF) {
1869 // Traverse the basic block.
1870 MachineBasicBlock::iterator NextI;
1871 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1872 MachineInstr *MI = &*I;
1873 NextI = std::next(I);
1874 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001875
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001876 switch (Opc) {
1877 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001878 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001879 break;
1880 case Hexagon::STriw_pred:
1881 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001882 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001883 break;
1884 case Hexagon::LDriw_pred:
1885 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001886 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001887 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001888 case Hexagon::PS_vstorerq_ai:
1889 case Hexagon::PS_vstorerq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001890 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001891 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001892 case Hexagon::PS_vloadrq_ai:
1893 case Hexagon::PS_vloadrq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001894 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001895 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001896 case Hexagon::PS_vloadrw_ai:
1897 case Hexagon::PS_vloadrwu_ai:
1898 case Hexagon::PS_vloadrw_ai_128B:
1899 case Hexagon::PS_vloadrwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001900 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001901 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001902 case Hexagon::PS_vstorerw_ai:
1903 case Hexagon::PS_vstorerwu_ai:
1904 case Hexagon::PS_vstorerw_ai_128B:
1905 case Hexagon::PS_vstorerwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001906 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001907 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001908 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001909 }
1910 }
1911
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001912 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001913}
1914
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001915void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1916 BitVector &SavedRegs,
1917 RegScavenger *RS) const {
1918 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1919 auto &HRI = *HST.getRegisterInfo();
1920
1921 SavedRegs.resize(HRI.getNumRegs());
1922
1923 // If we have a function containing __builtin_eh_return we want to spill and
1924 // restore all callee saved registers. Pretend that they are used.
1925 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1926 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1927 SavedRegs.set(*R);
1928
1929 // Replace predicate register pseudo spill code.
1930 SmallVector<unsigned,8> NewRegs;
1931 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001932 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001933 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001934
1935 // We need to reserve a a spill slot if scavenging could potentially require
1936 // spilling a scavenged register.
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00001937 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +00001938 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001939 MachineRegisterInfo &MRI = MF.getRegInfo();
1940 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001941 // Reserve an int register in any case, because it could be used to hold
1942 // the stack offset in case it does not fit into a spill instruction.
1943 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1944
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001945 for (unsigned VR : NewRegs)
1946 SpillRCs.insert(MRI.getRegClass(VR));
1947
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001948 for (auto *RC : SpillRCs) {
1949 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1950 continue;
1951 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001952 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001953 for (unsigned i = 0; i < Num; i++) {
1954 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001955 RS->addScavengingFrameIndex(NewFI);
1956 }
1957 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001958 }
1959
1960 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1961}
1962
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001963unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1964 HexagonBlockRanges::IndexRange &FIR,
1965 HexagonBlockRanges::InstrIndexMap &IndexMap,
1966 HexagonBlockRanges::RegToRangeMap &DeadMap,
1967 const TargetRegisterClass *RC) const {
1968 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1969 auto &MRI = MF.getRegInfo();
1970
1971 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1972 auto F = DeadMap.find({Reg,0});
1973 if (F == DeadMap.end())
1974 return false;
1975 for (auto &DR : F->second)
1976 if (DR.contains(FIR))
1977 return true;
1978 return false;
1979 };
1980
1981 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1982 bool Dead = true;
1983 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1984 if (isDead(R.Reg))
1985 continue;
1986 Dead = false;
1987 break;
1988 }
1989 if (Dead)
1990 return Reg;
1991 }
1992 return 0;
1993}
1994
1995void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1996 SmallVectorImpl<unsigned> &VRegs) const {
1997 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1998 auto &HII = *HST.getInstrInfo();
1999 auto &HRI = *HST.getRegisterInfo();
2000 auto &MRI = MF.getRegInfo();
2001 HexagonBlockRanges HBR(MF);
2002
2003 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
2004 BlockIndexMap;
2005 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
2006 BlockRangeMap;
2007 typedef HexagonBlockRanges::IndexType IndexType;
2008
2009 struct SlotInfo {
2010 BlockRangeMap Map;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00002011 unsigned Size = 0;
2012 const TargetRegisterClass *RC = nullptr;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00002013
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00002014 SlotInfo() = default;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002015 };
2016
2017 BlockIndexMap BlockIndexes;
2018 SmallSet<int,4> BadFIs;
2019 std::map<int,SlotInfo> FIRangeMap;
2020
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002021 // Accumulate register classes: get a common class for a pre-existing
2022 // class HaveRC and a new class NewRC. Return nullptr if a common class
2023 // cannot be found, otherwise return the resulting class. If HaveRC is
2024 // nullptr, assume that it is still unset.
Malcolm Parsons17d266b2017-01-13 17:12:16 +00002025 auto getCommonRC =
2026 [](const TargetRegisterClass *HaveRC,
2027 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002028 if (HaveRC == nullptr || HaveRC == NewRC)
2029 return NewRC;
2030 // Different classes, both non-null. Pick the more general one.
2031 if (HaveRC->hasSubClassEq(NewRC))
2032 return HaveRC;
2033 if (NewRC->hasSubClassEq(HaveRC))
2034 return NewRC;
2035 return nullptr;
2036 };
2037
2038 // Scan all blocks in the function. Check all occurrences of frame indexes,
2039 // and collect relevant information.
2040 for (auto &B : MF) {
2041 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00002042 // Emplace appears not to be supported in gcc 4.7.2-4.
2043 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00002044 auto P = BlockIndexes.insert(
2045 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002046 auto &IndexMap = P.first->second;
2047 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2048 << IndexMap << '\n');
2049
2050 for (auto &In : B) {
2051 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002052 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2053 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002054 if (Load && Store) {
2055 // If it's both a load and a store, then we won't handle it.
2056 BadFIs.insert(LFI);
2057 BadFIs.insert(SFI);
2058 continue;
2059 }
2060 // Check for register classes of the register used as the source for
2061 // the store, and the register used as the destination for the load.
2062 // Also, only accept base+imm_offset addressing modes. Other addressing
2063 // modes can have side-effects (post-increments, etc.). For stack
2064 // slots they are very unlikely, so there is not much loss due to
2065 // this restriction.
2066 if (Load || Store) {
2067 int TFI = Load ? LFI : SFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002068 unsigned AM = HII.getAddrMode(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002069 SlotInfo &SI = FIRangeMap[TFI];
2070 bool Bad = (AM != HexagonII::BaseImmOffset);
2071 if (!Bad) {
2072 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002073 unsigned OpNum = Load ? 0 : 2;
2074 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002075 RC = getCommonRC(SI.RC, RC);
2076 if (RC == nullptr)
2077 Bad = true;
2078 else
2079 SI.RC = RC;
2080 }
2081 if (!Bad) {
2082 // Check sizes.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002083 unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002084 if (SI.Size != 0 && SI.Size != S)
2085 Bad = true;
2086 else
2087 SI.Size = S;
2088 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002089 if (!Bad) {
2090 for (auto *Mo : In.memoperands()) {
2091 if (!Mo->isVolatile())
2092 continue;
2093 Bad = true;
2094 break;
2095 }
2096 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002097 if (Bad)
2098 BadFIs.insert(TFI);
2099 }
2100
2101 // Locate uses of frame indices.
2102 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2103 const MachineOperand &Op = In.getOperand(i);
2104 if (!Op.isFI())
2105 continue;
2106 int FI = Op.getIndex();
2107 // Make sure that the following operand is an immediate and that
2108 // it is 0. This is the offset in the stack object.
2109 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2110 In.getOperand(i+1).getImm() != 0)
2111 BadFIs.insert(FI);
2112 if (BadFIs.count(FI))
2113 continue;
2114
2115 IndexType Index = IndexMap.getIndex(&In);
2116 if (Load) {
2117 if (LastStore[FI] == IndexType::None)
2118 LastStore[FI] = IndexType::Entry;
2119 LastLoad[FI] = Index;
2120 } else if (Store) {
2121 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2122 if (LastStore[FI] != IndexType::None)
2123 RL.add(LastStore[FI], LastLoad[FI], false, false);
2124 else if (LastLoad[FI] != IndexType::None)
2125 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2126 LastLoad[FI] = IndexType::None;
2127 LastStore[FI] = Index;
2128 } else {
2129 BadFIs.insert(FI);
2130 }
2131 }
2132 }
2133
2134 for (auto &I : LastLoad) {
2135 IndexType LL = I.second;
2136 if (LL == IndexType::None)
2137 continue;
2138 auto &RL = FIRangeMap[I.first].Map[&B];
2139 IndexType &LS = LastStore[I.first];
2140 if (LS != IndexType::None)
2141 RL.add(LS, LL, false, false);
2142 else
2143 RL.add(IndexType::Entry, LL, false, false);
2144 LS = IndexType::None;
2145 }
2146 for (auto &I : LastStore) {
2147 IndexType LS = I.second;
2148 if (LS == IndexType::None)
2149 continue;
2150 auto &RL = FIRangeMap[I.first].Map[&B];
2151 RL.add(LS, IndexType::None, false, false);
2152 }
2153 }
2154
2155 DEBUG({
2156 for (auto &P : FIRangeMap) {
2157 dbgs() << "fi#" << P.first;
2158 if (BadFIs.count(P.first))
2159 dbgs() << " (bad)";
2160 dbgs() << " RC: ";
2161 if (P.second.RC != nullptr)
2162 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2163 else
2164 dbgs() << "<null>\n";
2165 for (auto &R : P.second.Map)
2166 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2167 }
2168 });
2169
2170 // When a slot is loaded from in a block without being stored to in the
2171 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2172 // consider this slot to be live-on-exit from all blocks.
2173 SmallSet<int,4> LoxFIs;
2174
2175 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2176
2177 for (auto &P : FIRangeMap) {
2178 // P = pair(FI, map: BB->RangeList)
2179 if (BadFIs.count(P.first))
2180 continue;
2181 for (auto &B : MF) {
2182 auto F = P.second.Map.find(&B);
2183 // F = pair(BB, RangeList)
2184 if (F == P.second.Map.end() || F->second.empty())
2185 continue;
2186 HexagonBlockRanges::IndexRange &IR = F->second.front();
2187 if (IR.start() == IndexType::Entry)
2188 LoxFIs.insert(P.first);
2189 BlockFIMap[&B].push_back(P.first);
2190 }
2191 }
2192
2193 DEBUG({
2194 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2195 for (auto &P : BlockFIMap) {
2196 auto &FIs = P.second;
2197 if (FIs.empty())
2198 continue;
2199 dbgs() << " BB#" << P.first->getNumber() << ": {";
2200 for (auto I : FIs) {
2201 dbgs() << " fi#" << I;
2202 if (LoxFIs.count(I))
2203 dbgs() << '*';
2204 }
2205 dbgs() << " }\n";
2206 }
2207 });
2208
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002209#ifndef NDEBUG
2210 bool HasOptLimit = SpillOptMax.getPosition();
2211#endif
2212
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002213 // eliminate loads, when all loads eliminated, eliminate all stores.
2214 for (auto &B : MF) {
2215 auto F = BlockIndexes.find(&B);
2216 assert(F != BlockIndexes.end());
2217 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2218 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2219 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2220 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2221 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2222
2223 for (auto FI : BlockFIMap[&B]) {
2224 if (BadFIs.count(FI))
2225 continue;
2226 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2227 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2228 for (auto &Range : RL) {
2229 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2230 if (!IndexType::isInstr(Range.start()) ||
2231 !IndexType::isInstr(Range.end()))
2232 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002233 MachineInstr &SI = *IM.getInstr(Range.start());
2234 MachineInstr &EI = *IM.getInstr(Range.end());
2235 assert(SI.mayStore() && "Unexpected start instruction");
2236 assert(EI.mayLoad() && "Unexpected end instruction");
2237 MachineOperand &SrcOp = SI.getOperand(2);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002238
2239 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2240 SrcOp.getSubReg() };
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002241 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002242 // The this-> is needed to unconfuse MSVC.
2243 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2244 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2245 if (FoundR == 0)
2246 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002247#ifndef NDEBUG
2248 if (HasOptLimit) {
2249 if (SpillOptCount >= SpillOptMax)
2250 return;
2251 SpillOptCount++;
2252 }
2253#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002254
2255 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002256 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002257 MachineInstr *CopyIn = nullptr;
2258 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002259 const DebugLoc &DL = SI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002260 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
Diana Picus116bbab2017-01-13 09:58:52 +00002261 .add(SrcOp);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002262 }
2263
2264 ++StartIt;
2265 // Check if this is a last store and the FI is live-on-exit.
2266 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2267 // Update store's source register.
2268 if (unsigned SR = SrcOp.getSubReg())
2269 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2270 else
2271 SrcOp.setReg(FoundR);
2272 SrcOp.setSubReg(0);
2273 // We are keeping this register live.
2274 SrcOp.setIsKill(false);
2275 } else {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002276 B.erase(&SI);
2277 IM.replaceInstr(&SI, CopyIn);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002278 }
2279
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002280 auto EndIt = std::next(EI.getIterator());
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002281 for (auto It = StartIt; It != EndIt; It = NextIt) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002282 MachineInstr &MI = *It;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002283 NextIt = std::next(It);
2284 int TFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002285 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002286 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002287 unsigned DstR = MI.getOperand(0).getReg();
2288 assert(MI.getOperand(0).getSubReg() == 0);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002289 MachineInstr *CopyOut = nullptr;
2290 if (DstR != FoundR) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002291 DebugLoc DL = MI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002292 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2293 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2294 unsigned CopyOpc = TargetOpcode::COPY;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002295 if (HII.isSignExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002296 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002297 else if (HII.isZeroExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002298 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2299 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002300 .addReg(FoundR, getKillRegState(&MI == &EI));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002301 }
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002302 IM.replaceInstr(&MI, CopyOut);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002303 B.erase(It);
2304 }
2305
2306 // Update the dead map.
2307 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2308 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2309 DM[RR].subtract(Range);
2310 } // for Range in range list
2311 }
2312 }
2313}
2314
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002315void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002316 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002317 MachineBasicBlock &MB = *AI->getParent();
2318 DebugLoc DL = AI->getDebugLoc();
2319 unsigned A = AI->getOperand(2).getImm();
2320
2321 // Have
2322 // Rd = alloca Rs, #A
2323 //
2324 // If Rs and Rd are different registers, use this sequence:
2325 // Rd = sub(r29, Rs)
2326 // r29 = sub(r29, Rs)
2327 // Rd = and(Rd, #-A) ; if necessary
2328 // r29 = and(r29, #-A) ; if necessary
2329 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2330 // otherwise, do
2331 // Rd = sub(r29, Rs)
2332 // Rd = and(Rd, #-A) ; if necessary
2333 // r29 = Rd
2334 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2335
2336 MachineOperand &RdOp = AI->getOperand(0);
2337 MachineOperand &RsOp = AI->getOperand(1);
2338 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2339
2340 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002341 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002342 .addReg(SP)
2343 .addReg(Rs);
2344 if (Rs != Rd) {
2345 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002346 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002347 .addReg(SP)
2348 .addReg(Rs);
2349 }
2350 if (A > 8) {
2351 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002352 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002353 .addReg(Rd)
2354 .addImm(-int64_t(A));
2355 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002356 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002357 .addReg(SP)
2358 .addImm(-int64_t(A));
2359 }
2360 if (Rs == Rd) {
2361 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002362 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002363 .addReg(Rd);
2364 }
2365 if (CF > 0) {
2366 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002367 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002368 .addReg(Rd)
2369 .addImm(CF);
2370 }
2371}
2372
2373bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +00002374 const MachineFrameInfo &MFI = MF.getFrameInfo();
2375 if (!MFI.hasVarSizedObjects())
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002376 return false;
Krzysztof Parzyszek71702172017-06-23 19:47:04 +00002377 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002378 if (MaxA <= getStackAlignment())
2379 return false;
2380 return true;
2381}
2382
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002383const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2384 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002385 for (auto &B : MF)
2386 for (auto &I : B)
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00002387 if (I.getOpcode() == Hexagon::PS_aligna)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002388 return &I;
2389 return nullptr;
2390}
2391
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002392/// Adds all callee-saved registers as implicit uses or defs to the
2393/// instruction.
2394void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2395 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2396 // Add the callee-saved registers as implicit uses.
2397 for (auto &R : CSI)
2398 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2399}
2400
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002401/// Determine whether the callee-saved register saves and restores should
2402/// be generated via inline code. If this function returns "true", inline
2403/// code will be generated. If this function returns "false", additional
2404/// checks are performed, which may still lead to the inline code.
2405bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2406 const CSIVect &CSI) const {
2407 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2408 return true;
2409 if (!isOptSize(MF) && !isMinSize(MF))
2410 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2411 return true;
2412
2413 // Check if CSI only has double registers, and if the registers form
2414 // a contiguous block starting from D8.
2415 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2416 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2417 unsigned R = CSI[i].getReg();
2418 if (!Hexagon::DoubleRegsRegClass.contains(R))
2419 return true;
2420 Regs[R] = true;
2421 }
2422 int F = Regs.find_first();
2423 if (F != Hexagon::D8)
2424 return true;
2425 while (F >= 0) {
2426 int N = Regs.find_next(F);
2427 if (N >= 0 && N != F+1)
2428 return true;
2429 F = N;
2430 }
2431
2432 return false;
2433}
2434
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002435bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2436 const CSIVect &CSI) const {
2437 if (shouldInlineCSR(MF, CSI))
2438 return false;
2439 unsigned NumCSI = CSI.size();
2440 if (NumCSI <= 1)
2441 return false;
2442
2443 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2444 : SpillFuncThreshold;
2445 return Threshold < NumCSI;
2446}
2447
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002448bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2449 const CSIVect &CSI) const {
2450 if (shouldInlineCSR(MF, CSI))
2451 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002452 // The restore functions do a bit more than just restoring registers.
2453 // The non-returning versions will go back directly to the caller's
2454 // caller, others will clean up the stack frame in preparation for
2455 // a tail call. Using them can still save code size even if only one
2456 // register is getting restores. Make the decision based on -Oz:
2457 // using -Os will use inline restore for a single register.
2458 if (isMinSize(MF))
2459 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002460 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002461 if (NumCSI <= 1)
2462 return false;
2463
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002464 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2465 : SpillFuncThreshold;
2466 return Threshold < NumCSI;
2467}
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002468
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002469bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2470 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2471 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2472 // A fairly simplistic guess as to whether a potential load/store to a
Krzysztof Parzyszek69ffba42017-06-22 14:11:23 +00002473 // stack location could require an extra register.
2474 if (HST.useHVXOps() && StackSize > 256)
2475 return true;
2476
2477 // Check if the function has store-immediate instructions that access
2478 // the stack. Since the offset field is not extendable, if the stack
2479 // size exceeds the offset limit (6 bits, shifted), the stores will
2480 // require a new base register.
2481 bool HasImmStack = false;
2482 unsigned MinLS = ~0u; // Log_2 of the memory access size.
2483
2484 for (const MachineBasicBlock &B : MF) {
2485 for (const MachineInstr &MI : B) {
2486 unsigned LS = 0;
2487 switch (MI.getOpcode()) {
2488 case Hexagon::S4_storeirit_io:
2489 case Hexagon::S4_storeirif_io:
2490 case Hexagon::S4_storeiri_io:
2491 ++LS;
2492 LLVM_FALLTHROUGH;
2493 case Hexagon::S4_storeirht_io:
2494 case Hexagon::S4_storeirhf_io:
2495 case Hexagon::S4_storeirh_io:
2496 ++LS;
2497 LLVM_FALLTHROUGH;
2498 case Hexagon::S4_storeirbt_io:
2499 case Hexagon::S4_storeirbf_io:
2500 case Hexagon::S4_storeirb_io:
2501 if (MI.getOperand(0).isFI())
2502 HasImmStack = true;
2503 MinLS = std::min(MinLS, LS);
2504 break;
2505 }
2506 }
2507 }
2508
2509 if (HasImmStack)
2510 return !isUInt<6>(StackSize >> MinLS);
2511
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002512 return false;
2513}