blob: e5e75198b2d18bd6b37dab34eb16da07b3d3cdf7 [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
Craig Topperb25fda92012-03-17 18:46:09 +000011#include "HexagonFrameLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "HexagonBlockRanges.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000013#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonRegisterInfo.h"
16#include "HexagonSubtarget.h"
17#include "HexagonTargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000018#include "MCTargetDesc/HexagonBaseInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000019#include "llvm/ADT/BitVector.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000023#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000024#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/SmallVector.h"
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +000027#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000029#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000030#include "llvm/CodeGen/MachineFrameInfo.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000033#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000035#include "llvm/CodeGen/MachineMemOperand.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000036#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000037#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000038#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000039#include "llvm/CodeGen/MachineRegisterInfo.h"
40#include "llvm/CodeGen/RegisterScavenging.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000041#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Function.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000043#include "llvm/MC/MCDwarf.h"
44#include "llvm/MC/MCRegisterInfo.h"
45#include "llvm/Pass.h"
46#include "llvm/Support/CodeGen.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000048#include "llvm/Support/Debug.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000049#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000051#include "llvm/Support/raw_ostream.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000052#include "llvm/Target/TargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000053#include "llvm/Target/TargetRegisterInfo.h"
54#include <algorithm>
55#include <cassert>
56#include <cstdint>
57#include <iterator>
58#include <limits>
59#include <map>
60#include <new>
61#include <utility>
62#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000063
Jakub Kuderski34327d22017-07-13 20:26:45 +000064#define DEBUG_TYPE "hexagon-pei"
65
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 Parzyszek9eb75c42017-06-30 21:21:40 +0000181static cl::opt<bool> EliminateFramePointer("hexagon-fp-elim", cl::init(true),
182 cl::Hidden, cl::desc("Refrain from using FP whenever possible"));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000183
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();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000553
Krzysztof Parzyszek71702172017-06-23 19:47:04 +0000554 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000555
556 // Calculate the total stack frame size.
557 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000558 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000559 // Round up the max call frame size to the max alignment on the stack.
Matthias Braun941a7052016-07-28 18:40:00 +0000560 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
561 MFI.setMaxCallFrameSize(MaxCFA);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000562
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000563 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Matthias Braun941a7052016-07-28 18:40:00 +0000564 MFI.setStackSize(FrameSize);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000565
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000566 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000567
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000568 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000569 unsigned NumBytes = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000570 unsigned SP = HRI.getStackRegister();
Matthias Braun941a7052016-07-28 18:40:00 +0000571 unsigned MaxCF = MFI.getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000572 MachineBasicBlock::iterator InsertPt = MBB.begin();
573
Krzysztof Parzyszek8849a512016-08-19 18:46:13 +0000574 SmallVector<MachineInstr *, 4> AdjustRegs;
575 for (auto &MBB : MF)
576 for (auto &MI : MBB)
577 if (MI.getOpcode() == Hexagon::PS_alloca)
578 AdjustRegs.push_back(&MI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000579
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000580 for (auto MI : AdjustRegs) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000581 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000582 expandAlloca(MI, HII, SP, MaxCF);
583 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000584 }
585
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000586 DebugLoc dl = MBB.findDebugLoc(InsertPt);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000587
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000588 if (hasFP(MF)) {
589 insertAllocframe(MBB, InsertPt, NumBytes);
590 if (AlignStack) {
591 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
592 .addReg(SP)
593 .addImm(-int64_t(MaxAlign));
594 }
595 // If the stack-checking is enabled, and we spilled the callee-saved
596 // registers inline (i.e. did not use a spill function), then call
597 // the stack checker directly.
598 if (EnableStackOVFSanitizer && !PrologueStubs)
599 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
600 .addExternalSymbol("__runtime_stack_check");
601 } else if (NumBytes > 0) {
602 assert(alignTo(NumBytes, 8) == NumBytes);
603 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000604 .addReg(SP)
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000605 .addImm(-int(NumBytes));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000606 }
607}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000608
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000609void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
610 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000611 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000612 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000613 auto &HRI = *HST.getRegisterInfo();
614 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000615
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000616 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
617 DebugLoc dl = MBB.findDebugLoc(InsertPt);
618
619 if (!hasFP(MF)) {
620 MachineFrameInfo &MFI = MF.getFrameInfo();
621 if (unsigned NumBytes = MFI.getStackSize()) {
622 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
623 .addReg(SP)
624 .addImm(NumBytes);
625 }
626 return;
627 }
628
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000629 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000630 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
631
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000632 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000633 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000634 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
635 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000636 .addReg(SP)
637 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000638 return;
639 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000640
641 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
642 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000643 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000644 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
645 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
646 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000647 MachineBasicBlock::iterator It = RetI;
648 ++It;
649 // Delete all instructions after the RESTORE (except labels).
650 while (It != MBB.end()) {
651 if (!It->isLabel())
652 It = MBB.erase(It);
653 else
654 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000655 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000656 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000657 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000658
659 // It is possible that the restoring code is a call to a library function.
660 // All of the restore* functions include "deallocframe", so we need to make
661 // sure that we don't add an extra one.
662 bool NeedsDeallocframe = true;
663 if (!MBB.empty() && InsertPt != MBB.begin()) {
664 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
665 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000666 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000667 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
668 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
669 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000670 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000671 NeedsDeallocframe = false;
672 }
673
674 if (!NeedsDeallocframe)
675 return;
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000676 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000677 // otherwise just add deallocframe. The function could be returning via a
678 // tail call.
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000679 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000680 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe));
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000681 return;
682 }
683 unsigned NewOpc = Hexagon::L4_return;
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000684 MachineInstr *NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc));
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000685 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000686 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000687 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000688}
689
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000690void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
691 MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
692 MachineFunction &MF = *MBB.getParent();
693 auto &HST = MF.getSubtarget<HexagonSubtarget>();
694 auto &HII = *HST.getInstrInfo();
695 auto &HRI = *HST.getRegisterInfo();
696
697 // Check for overflow.
698 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
699 const unsigned int ALLOCFRAME_MAX = 16384;
700
701 // Create a dummy memory operand to avoid allocframe from being treated as
702 // a volatile memory reference.
703 auto *MMO = MF.getMachineMemOperand(MachinePointerInfo::getStack(MF, 0),
704 MachineMemOperand::MOStore, 4, 4);
705
706 DebugLoc dl = MBB.findDebugLoc(InsertPt);
707
708 if (NumBytes >= ALLOCFRAME_MAX) {
709 // Emit allocframe(#0).
710 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
711 .addImm(0)
712 .addMemOperand(MMO);
713
714 // Subtract the size from the stack pointer.
715 unsigned SP = HRI.getStackRegister();
716 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
717 .addReg(SP)
718 .addImm(-int(NumBytes));
719 } else {
720 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
721 .addImm(NumBytes)
722 .addMemOperand(MMO);
723 }
724}
725
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000726void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
727 MachineBasicBlock &SaveB) const {
728 SetVector<unsigned> Worklist;
729
730 MachineBasicBlock &EntryB = MF.front();
731 Worklist.insert(EntryB.getNumber());
732
733 unsigned SaveN = SaveB.getNumber();
Matthias Braun941a7052016-07-28 18:40:00 +0000734 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000735
736 for (unsigned i = 0; i < Worklist.size(); ++i) {
737 unsigned BN = Worklist[i];
738 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
739 for (auto &R : CSI)
740 if (!MBB.isLiveIn(R.getReg()))
741 MBB.addLiveIn(R.getReg());
742 if (BN != SaveN)
743 for (auto &SB : MBB.successors())
744 Worklist.insert(SB->getNumber());
745 }
746}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000747
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000748bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000749 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000750 BitVector &Path) const {
751 assert(MBB.getNumber() >= 0);
752 unsigned BN = MBB.getNumber();
753 if (Path[BN] || DoneF[BN])
754 return false;
755 if (DoneT[BN])
756 return true;
757
Matthias Braun941a7052016-07-28 18:40:00 +0000758 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000759
760 Path[BN] = true;
761 bool ReachedExit = false;
762 for (auto &SB : MBB.successors())
763 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
764
765 if (!MBB.empty() && MBB.back().isReturn()) {
766 // Add implicit uses of all callee-saved registers to the reached
767 // return instructions. This is to prevent the anti-dependency breaker
768 // from renaming these registers.
769 MachineInstr &RetI = MBB.back();
770 if (!isRestoreCall(RetI.getOpcode()))
771 for (auto &R : CSI)
772 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
773 ReachedExit = true;
774 }
775
776 // We don't want to add unnecessary live-ins to the restore block: since
777 // the callee-saved registers are being defined in it, the entry of the
778 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000779 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000780 for (auto &R : CSI)
781 if (!MBB.isLiveIn(R.getReg()))
782 MBB.addLiveIn(R.getReg());
783 DoneT[BN] = true;
784 }
785 if (!ReachedExit)
786 DoneF[BN] = true;
787
788 Path[BN] = false;
789 return ReachedExit;
790}
791
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000792static Optional<MachineBasicBlock::iterator>
793findCFILocation(MachineBasicBlock &B) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000794 // The CFI instructions need to be inserted right after allocframe.
795 // An exception to this is a situation where allocframe is bundled
796 // with a call: then the CFI instructions need to be inserted before
797 // the packet with the allocframe+call (in case the call throws an
798 // exception).
799 auto End = B.instr_end();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000800
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000801 for (MachineInstr &I : B) {
802 MachineBasicBlock::iterator It = I.getIterator();
803 if (!I.isBundle()) {
804 if (I.getOpcode() == Hexagon::S2_allocframe)
805 return std::next(It);
806 continue;
807 }
808 // I is a bundle.
809 bool HasCall = false, HasAllocFrame = false;
810 auto T = It.getInstrIterator();
811 while (++T != End && T->isBundled()) {
812 if (T->getOpcode() == Hexagon::S2_allocframe)
813 HasAllocFrame = true;
814 else if (T->isCall())
815 HasCall = true;
816 }
817 if (HasAllocFrame)
818 return HasCall ? It : std::next(It);
819 }
820 return None;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000821}
822
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000823void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
824 for (auto &B : MF) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000825 auto At = findCFILocation(B);
826 if (At.hasValue())
827 insertCFIInstructionsAt(B, At.getValue());
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000828 }
829}
830
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000831void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
832 MachineBasicBlock::iterator At) const {
833 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000834 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000835 MachineModuleInfo &MMI = MF.getMMI();
836 auto &HST = MF.getSubtarget<HexagonSubtarget>();
837 auto &HII = *HST.getInstrInfo();
838 auto &HRI = *HST.getRegisterInfo();
839
840 // If CFI instructions have debug information attached, something goes
841 // wrong with the final assembly generation: the prolog_end is placed
842 // in a wrong location.
843 DebugLoc DL;
844 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
845
846 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000847 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000848
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000849 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000850 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
851 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000852
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000853 // Define CFA via an offset from the value of FP.
854 //
855 // -8 -4 0 (SP)
856 // --+----+----+---------------------
857 // | FP | LR | increasing addresses -->
858 // --+----+----+---------------------
859 // | +-- Old SP (before allocframe)
860 // +-- New FP (after allocframe)
861 //
862 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
863 // MCCFIInstruction::createOffset takes the offset without sign change.
864 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
865 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000866 .addCFIIndex(MF.addFrameInst(DefCfa));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000867 // R31 (return addr) = CFA - 4
868 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
869 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000870 .addCFIIndex(MF.addFrameInst(OffR31));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000871 // R30 (frame ptr) = CFA - 8
872 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
873 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000874 .addCFIIndex(MF.addFrameInst(OffR30));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000875 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000876
877 static unsigned int RegsToMove[] = {
878 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
879 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
880 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
881 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
882 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
883 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
884 Hexagon::NoRegister
885 };
886
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000887 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000888
889 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
890 unsigned Reg = RegsToMove[i];
891 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
892 return C.getReg() == Reg;
893 };
David Majnemer562e8292016-08-12 00:18:03 +0000894 auto F = find_if(CSI, IfR);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000895 if (F == CSI.end())
896 continue;
897
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000898 int64_t Offset;
899 if (HasFP) {
900 // If the function has a frame pointer (i.e. has an allocframe),
901 // then the CFA has been defined in terms of FP. Any offsets in
902 // the following CFI instructions have to be defined relative
903 // to FP, which points to the bottom of the stack frame.
904 // The function getFrameIndexReference can still choose to use SP
905 // for the offset calculation, so we cannot simply call it here.
906 // Instead, get the offset (relative to the FP) directly.
907 Offset = MFI.getObjectOffset(F->getFrameIdx());
908 } else {
909 unsigned FrameReg;
910 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
911 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000912 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000913 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000914
915 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
916 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
917 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
918 Offset);
919 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000920 .addCFIIndex(MF.addFrameInst(OffReg));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000921 } else {
922 // Split the double regs into subregs, and generate appropriate
923 // cfi_offsets.
924 // The only reason, we are split double regs is, llvm-mc does not
925 // understand paired registers for cfi_offset.
926 // Eg .cfi_offset r1:0, -64
927
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000928 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
929 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000930 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
931 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
932 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
933 Offset+4);
934 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000935 .addCFIIndex(MF.addFrameInst(OffHi));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000936 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
937 Offset);
938 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000939 .addCFIIndex(MF.addFrameInst(OffLo));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000940 }
941 }
942}
943
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000944bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000945 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
946 return false;
947
Matthias Braun941a7052016-07-28 18:40:00 +0000948 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000949 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000950 bool HasExtraAlign = HRI.needsStackRealignment(MF);
951 bool HasAlloca = MFI.hasVarSizedObjects();
952
953 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
954 // that this shouldn't be required, but doing so now because gcc does and
955 // gdb can't break at the start of the function without it. Will remove if
956 // this turns out to be a gdb bug.
957 //
958 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
959 return true;
960
961 // By default we want to use SP (since it's always there). FP requires
962 // some setup (i.e. ALLOCFRAME).
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000963 // Both, alloca and stack alignment modify the stack pointer by an
964 // undetermined value, so we need to save it at the entry to the function
965 // (i.e. use allocframe).
966 if (HasAlloca || HasExtraAlign)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000967 return true;
968
969 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000970 // If FP-elimination is disabled, we have to use FP at this point.
971 const TargetMachine &TM = MF.getTarget();
972 if (TM.Options.DisableFramePointerElim(MF) || !EliminateFramePointer)
973 return true;
974 if (EnableStackOVFSanitizer)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000975 return true;
976 }
977
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +0000978 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
979 if (MFI.hasCalls() || HMFI.hasClobberLR())
980 return true;
981
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000982 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000983}
984
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000985enum SpillKind {
986 SK_ToMem,
987 SK_FromMem,
988 SK_FromMemTailcall
989};
990
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000991static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
992 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000993 const char * V4SpillToMemoryFunctions[] = {
994 "__save_r16_through_r17",
995 "__save_r16_through_r19",
996 "__save_r16_through_r21",
997 "__save_r16_through_r23",
998 "__save_r16_through_r25",
999 "__save_r16_through_r27" };
1000
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001001 const char * V4SpillToMemoryStkchkFunctions[] = {
1002 "__save_r16_through_r17_stkchk",
1003 "__save_r16_through_r19_stkchk",
1004 "__save_r16_through_r21_stkchk",
1005 "__save_r16_through_r23_stkchk",
1006 "__save_r16_through_r25_stkchk",
1007 "__save_r16_through_r27_stkchk" };
1008
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001009 const char * V4SpillFromMemoryFunctions[] = {
1010 "__restore_r16_through_r17_and_deallocframe",
1011 "__restore_r16_through_r19_and_deallocframe",
1012 "__restore_r16_through_r21_and_deallocframe",
1013 "__restore_r16_through_r23_and_deallocframe",
1014 "__restore_r16_through_r25_and_deallocframe",
1015 "__restore_r16_through_r27_and_deallocframe" };
1016
1017 const char * V4SpillFromMemoryTailcallFunctions[] = {
1018 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1019 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1020 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1021 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1022 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1023 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1024 };
1025
1026 const char **SpillFunc = nullptr;
1027
1028 switch(SpillType) {
1029 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001030 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1031 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001032 break;
1033 case SK_FromMem:
1034 SpillFunc = V4SpillFromMemoryFunctions;
1035 break;
1036 case SK_FromMemTailcall:
1037 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1038 break;
1039 }
1040 assert(SpillFunc && "Unknown spill kind");
1041
1042 // Spill all callee-saved registers up to the highest register used.
1043 switch (MaxReg) {
1044 case Hexagon::R17:
1045 return SpillFunc[0];
1046 case Hexagon::R19:
1047 return SpillFunc[1];
1048 case Hexagon::R21:
1049 return SpillFunc[2];
1050 case Hexagon::R23:
1051 return SpillFunc[3];
1052 case Hexagon::R25:
1053 return SpillFunc[4];
1054 case Hexagon::R27:
1055 return SpillFunc[5];
1056 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001057 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001058 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001059 return nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001060}
1061
James Y Knight5567baf2015-08-15 02:32:35 +00001062int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001063 int FI, unsigned &FrameReg) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001064 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001065 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001066
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001067 int Offset = MFI.getObjectOffset(FI);
1068 bool HasAlloca = MFI.hasVarSizedObjects();
1069 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1070 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001071
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001072 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00001073 unsigned FrameSize = MFI.getStackSize();
1074 unsigned SP = HRI.getStackRegister();
1075 unsigned FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001076 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek918e6d72017-06-26 14:17:58 +00001077 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1078 // is true. HasExtraAlign may be set because of vector spills, without
1079 // aligned locals or aligned outgoing function arguments. Since vector
1080 // spills will ultimately be "unaligned", it is safe to use FP as the
1081 // base register.
1082 // In fact, in such a scenario the stack is actually not required to be
1083 // aligned, although it may end up being aligned anyway, since this
1084 // particular case is not easily detectable. The alignment will be
1085 // unnecessary, but not incorrect.
1086 // Unfortunately there is no quick way to verify that the above is
1087 // indeed the case (and that it's not a result of an error), so just
1088 // assume that missing AP will be replaced by FP.
1089 // (A better fix would be to rematerialize AP from FP and always align
1090 // vector spills.)
1091 if (AP == 0)
1092 AP = FP;
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001093
1094 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1095 // Use FP at -O0, except when there are objects with extra alignment.
1096 // That additional alignment requirement may cause a pad to be inserted,
1097 // which will make it impossible to use FP to access objects located
1098 // past the pad.
1099 if (NoOpt && !HasExtraAlign)
1100 UseFP = true;
1101 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1102 // Fixed and preallocated objects will be located before any padding
1103 // so FP must be used to access them.
1104 UseFP |= (HasAlloca || HasExtraAlign);
1105 } else {
1106 if (HasAlloca) {
1107 if (HasExtraAlign)
1108 UseAP = true;
1109 else
1110 UseFP = true;
1111 }
1112 }
1113
1114 // If FP was picked, then there had better be FP.
1115 bool HasFP = hasFP(MF);
1116 assert((HasFP || !UseFP) && "This function must have frame pointer");
1117
1118 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1119 // FP/LR. If the base register is used to access an object across these
1120 // 8 bytes, then the offset will need to be adjusted by 8.
1121 //
1122 // After allocframe:
1123 // HexagonISelLowering adds 8 to ---+
1124 // the offsets of all stack-based |
1125 // arguments (*) |
1126 // |
1127 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1128 // ------------------------+-----+------------------------> increasing
1129 // <local objects> |FP/LR| <input arguments> addresses
1130 // -----------------+------+-----+------------------------>
1131 // | |
1132 // SP/AP point --+ +-- FP points here (**)
1133 // somewhere on
1134 // this side of FP/LR
1135 //
1136 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1137 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1138
1139 // The lowering assumes that FP/LR is present, and so the offsets of
1140 // the formal arguments start at 8. If FP/LR is not there we need to
1141 // reduce the offset by 8.
1142 if (Offset > 0 && !HasFP)
1143 Offset -= 8;
1144
1145 if (UseFP)
1146 FrameReg = FP;
1147 else if (UseAP)
1148 FrameReg = AP;
1149 else
1150 FrameReg = SP;
1151
1152 // Calculate the actual offset in the instruction. If there is no FP
1153 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1154 // there will be no SP -= FrameSize), so the frame size should not be
1155 // added to the calculated offset.
1156 int RealOffset = Offset;
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00001157 if (!UseFP && !UseAP)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001158 RealOffset = FrameSize+Offset;
1159 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001160}
1161
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001162bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001163 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1164 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001165 if (CSI.empty())
1166 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001167
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001168 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001169 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001170 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001171 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1172 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001173
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001174 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001175 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001176 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001177 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1178 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1179 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001180 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001181 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001182 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001183
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001184 // Call spill function.
1185 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001186 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001187 if (StkOvrFlowEnabled) {
1188 if (LongCalls)
1189 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1190 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1191 else
1192 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1193 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1194 } else {
1195 if (LongCalls)
1196 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1197 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1198 else
1199 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1200 : Hexagon::SAVE_REGISTERS_CALL_V4;
1201 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001202
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001203 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001204 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001205 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001206
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001207 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001208 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001209 // Add live in registers.
1210 for (unsigned I = 0; I < CSI.size(); ++I)
1211 MBB.addLiveIn(CSI[I].getReg());
1212 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001213 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001214
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001215 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001216 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001217 // Add live in registers. We treat eh_return callee saved register r0 - r3
1218 // specially. They are not really callee saved registers as they are not
1219 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001220 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1221 int FI = CSI[i].getFrameIdx();
1222 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001223 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001224 if (IsKill)
1225 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001226 }
1227 return true;
1228}
1229
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001230bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1231 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1232 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001233 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001234
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001235 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1236 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001237 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1238 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001239
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001240 if (useRestoreFunction(MF, CSI)) {
1241 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1242 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1243 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1244 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001245 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001246 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001247 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001248
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001249 // Call spill function.
1250 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1251 : MBB.getLastNonDebugInstr()->getDebugLoc();
1252 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001253
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001254 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001255 unsigned RetOpc;
1256 if (LongCalls)
1257 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1258 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1259 else
1260 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1261 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1262 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001263 .addExternalSymbol(RestoreFn);
1264 } else {
1265 // The block has a return.
1266 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1267 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001268 unsigned RetOpc;
1269 if (LongCalls)
1270 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1271 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1272 else
1273 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1274 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1275 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001276 .addExternalSymbol(RestoreFn);
1277 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001278 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001279 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001280 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001281 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001282 }
1283
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001284 for (unsigned i = 0; i < CSI.size(); ++i) {
1285 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001286 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1287 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001288 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001289 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001290
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001291 return true;
1292}
1293
Hans Wennborge1a2e902016-03-31 18:33:38 +00001294MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1295 MachineFunction &MF, MachineBasicBlock &MBB,
1296 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001297 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001298 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001299 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001300 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1301 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001302 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001303}
1304
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001305void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1306 MachineFunction &MF, RegScavenger *RS) const {
1307 // If this function has uses aligned stack and also has variable sized stack
1308 // objects, then we need to map all spill slots to fixed positions, so that
1309 // they can be accessed through FP. Otherwise they would have to be accessed
1310 // via AP, which may not be available at the particular place in the program.
Matthias Braun941a7052016-07-28 18:40:00 +00001311 MachineFrameInfo &MFI = MF.getFrameInfo();
1312 bool HasAlloca = MFI.hasVarSizedObjects();
1313 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001314
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001315 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001316 return;
1317
Matthias Braun941a7052016-07-28 18:40:00 +00001318 unsigned LFS = MFI.getLocalFrameSize();
1319 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1320 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001321 continue;
Matthias Braun941a7052016-07-28 18:40:00 +00001322 unsigned S = MFI.getObjectSize(i);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001323 // Reduce the alignment to at most 8. This will require unaligned vector
1324 // stores if they happen here.
Matthias Braun941a7052016-07-28 18:40:00 +00001325 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1326 MFI.setObjectAlignment(i, 8);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001327 LFS = alignTo(LFS+S, A);
Matthias Braun941a7052016-07-28 18:40:00 +00001328 MFI.mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001329 }
1330
Matthias Braun941a7052016-07-28 18:40:00 +00001331 MFI.setLocalFrameSize(LFS);
1332 unsigned A = MFI.getLocalFrameMaxAlign();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001333 assert(A <= 8 && "Unexpected local frame alignment");
1334 if (A == 0)
Matthias Braun941a7052016-07-28 18:40:00 +00001335 MFI.setLocalFrameMaxAlign(8);
1336 MFI.setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001337
1338 // Set the physical aligned-stack base address register.
1339 unsigned AP = 0;
1340 if (const MachineInstr *AI = getAlignaInstr(MF))
1341 AP = AI->getOperand(0).getReg();
1342 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1343 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001344}
1345
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001346/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001347static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001348 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001349 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001350
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001351 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1352 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1353 if (MRI.isPhysRegUsed(*AI))
1354 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001355 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001356 };
1357
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001358 // Check for an unused caller-saved register. Callee-saved registers
1359 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001360 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001361 if (!IsUsed(*P))
1362 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001363
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001364 // All caller-saved registers are used.
1365 return true;
1366}
1367
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001368#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001369static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001370 dbgs() << '{';
1371 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1372 unsigned R = x;
1373 dbgs() << ' ' << PrintReg(R, &TRI);
1374 }
1375 dbgs() << " }";
1376}
1377#endif
1378
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001379bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1380 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Reid Kleckner40d72302016-10-20 00:22:23 +00001381 DEBUG(dbgs() << __func__ << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001382 << MF.getFunction()->getName() << '\n');
Matthias Braun941a7052016-07-28 18:40:00 +00001383 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001384 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001385
1386 // Generate a set of unique, callee-saved registers (SRegs), where each
1387 // register in the set is maximal in terms of sub-/super-register relation,
1388 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1389
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001390 // (1) For each callee-saved register, add that register and all of its
1391 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001392 DEBUG(dbgs() << "Initial CS registers: {");
1393 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1394 unsigned R = CSI[i].getReg();
1395 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1396 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1397 SRegs[*SR] = true;
1398 }
1399 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001400 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001401
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001402 // (2) For each reserved register, remove that register and all of its
1403 // sub- and super-registers from SRegs.
1404 BitVector Reserved = TRI->getReservedRegs(MF);
1405 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1406 unsigned R = x;
1407 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1408 SRegs[*SR] = false;
1409 }
1410 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1411 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1412
1413 // (3) Collect all registers that have at least one sub-register in SRegs,
1414 // and also have no sub-registers that are reserved. These will be the can-
1415 // didates for saving as a whole instead of their individual sub-registers.
1416 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1417 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001418 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1419 unsigned R = x;
1420 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1421 TmpSup[*SR] = true;
1422 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001423 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1424 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001425 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1426 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001427 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001428 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001429 break;
1430 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001431 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001432 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001433
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001434 // (4) Include all super-registers found in (3) into SRegs.
1435 SRegs |= TmpSup;
1436 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001437
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001438 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001439 // remove R from SRegs.
1440 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1441 unsigned R = x;
1442 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1443 if (!SRegs[*SR])
1444 continue;
1445 SRegs[R] = false;
1446 break;
1447 }
1448 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001449 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001450
1451 // Now, for each register that has a fixed stack slot, create the stack
1452 // object for it.
1453 CSI.clear();
1454
1455 typedef TargetFrameLowering::SpillSlot SpillSlot;
1456 unsigned NumFixed;
1457 int MinOffset = 0; // CS offsets are negative.
1458 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1459 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1460 if (!SRegs[S->Reg])
1461 continue;
1462 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001463 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001464 MinOffset = std::min(MinOffset, S->Offset);
1465 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1466 SRegs[S->Reg] = false;
1467 }
1468
1469 // There can be some registers that don't have fixed slots. For example,
1470 // we need to store R0-R3 in functions with exception handling. For each
1471 // such register, create a non-fixed stack object.
1472 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1473 unsigned R = x;
1474 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001475 unsigned Size = TRI->getSpillSize(*RC);
1476 int Off = MinOffset - Size;
1477 unsigned Align = std::min(TRI->getSpillAlignment(*RC), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001478 assert(isPowerOf2_32(Align));
1479 Off &= -Align;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001480 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001481 MinOffset = std::min(MinOffset, Off);
1482 CSI.push_back(CalleeSavedInfo(R, FI));
1483 SRegs[R] = false;
1484 }
1485
1486 DEBUG({
1487 dbgs() << "CS information: {";
1488 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1489 int FI = CSI[i].getFrameIdx();
Matthias Braun941a7052016-07-28 18:40:00 +00001490 int Off = MFI.getObjectOffset(FI);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001491 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1492 if (Off >= 0)
1493 dbgs() << '+';
1494 dbgs() << Off;
1495 }
1496 dbgs() << " }\n";
1497 });
1498
1499#ifndef NDEBUG
1500 // Verify that all registers were handled.
1501 bool MissedReg = false;
1502 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1503 unsigned R = x;
1504 dbgs() << PrintReg(R, TRI) << ' ';
1505 MissedReg = true;
1506 }
1507 if (MissedReg)
1508 llvm_unreachable("...there are unhandled callee-saved registers!");
1509#endif
1510
1511 return true;
1512}
1513
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001514bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1515 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1516 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1517 MachineInstr *MI = &*It;
1518 DebugLoc DL = MI->getDebugLoc();
1519 unsigned DstR = MI->getOperand(0).getReg();
1520 unsigned SrcR = MI->getOperand(1).getReg();
1521 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1522 !Hexagon::ModRegsRegClass.contains(SrcR))
1523 return false;
1524
1525 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
Diana Picus116bbab2017-01-13 09:58:52 +00001526 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001527 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1528 .addReg(TmpR, RegState::Kill);
1529
1530 NewRegs.push_back(TmpR);
1531 B.erase(It);
1532 return true;
1533}
1534
1535bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1536 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1537 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1538 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001539 if (!MI->getOperand(0).isFI())
1540 return false;
1541
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001542 DebugLoc DL = MI->getDebugLoc();
1543 unsigned Opc = MI->getOpcode();
1544 unsigned SrcR = MI->getOperand(2).getReg();
1545 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001546 int FI = MI->getOperand(0).getIndex();
1547
1548 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1549 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1550 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1551 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1552 : Hexagon::A2_tfrcrr;
1553 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1554 .addReg(SrcR, getKillRegState(IsKill));
1555
1556 // S2_storeri_io FI, 0, TmpR
1557 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1558 .addFrameIndex(FI)
1559 .addImm(0)
1560 .addReg(TmpR, RegState::Kill)
1561 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1562
1563 NewRegs.push_back(TmpR);
1564 B.erase(It);
1565 return true;
1566}
1567
1568bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1569 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1570 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1571 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001572 if (!MI->getOperand(1).isFI())
1573 return false;
1574
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001575 DebugLoc DL = MI->getDebugLoc();
1576 unsigned Opc = MI->getOpcode();
1577 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001578 int FI = MI->getOperand(1).getIndex();
1579
1580 // TmpR = L2_loadri_io FI, 0
1581 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1582 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1583 .addFrameIndex(FI)
1584 .addImm(0)
1585 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1586
1587 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1588 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1589 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1590 : Hexagon::A2_tfrrcr;
1591 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1592 .addReg(TmpR, RegState::Kill);
1593
1594 NewRegs.push_back(TmpR);
1595 B.erase(It);
1596 return true;
1597}
1598
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001599bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1600 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1601 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1602 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1603 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001604 if (!MI->getOperand(0).isFI())
1605 return false;
1606
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001607 DebugLoc DL = MI->getDebugLoc();
1608 unsigned SrcR = MI->getOperand(2).getReg();
1609 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001610 int FI = MI->getOperand(0).getIndex();
1611
1612 bool Is128B = HST.useHVXDblOps();
1613 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1614 : &Hexagon::VectorRegs128BRegClass;
1615
1616 // Insert transfer to general vector register.
1617 // TmpR0 = A2_tfrsi 0x01010101
1618 // TmpR1 = V6_vandqrt Qx, TmpR0
1619 // store FI, 0, TmpR1
1620 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1621 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1622
1623 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1624 .addImm(0x01010101);
1625
1626 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1627 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1628 .addReg(SrcR, getKillRegState(IsKill))
1629 .addReg(TmpR0, RegState::Kill);
1630
1631 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1632 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1633 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1634
1635 NewRegs.push_back(TmpR0);
1636 NewRegs.push_back(TmpR1);
1637 B.erase(It);
1638 return true;
1639}
1640
1641bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1642 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1643 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1644 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1645 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001646 if (!MI->getOperand(1).isFI())
1647 return false;
1648
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001649 DebugLoc DL = MI->getDebugLoc();
1650 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001651 int FI = MI->getOperand(1).getIndex();
1652
1653 bool Is128B = HST.useHVXDblOps();
1654 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1655 : &Hexagon::VectorRegs128BRegClass;
1656
1657 // TmpR0 = A2_tfrsi 0x01010101
1658 // TmpR1 = load FI, 0
1659 // DstR = V6_vandvrt TmpR1, TmpR0
1660 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1661 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1662
1663 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1664 .addImm(0x01010101);
1665 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1666 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1667 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1668
1669 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1670 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1671 .addReg(TmpR1, RegState::Kill)
1672 .addReg(TmpR0, RegState::Kill);
1673
1674 NewRegs.push_back(TmpR0);
1675 NewRegs.push_back(TmpR1);
1676 B.erase(It);
1677 return true;
1678}
1679
1680bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1681 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1682 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1683 MachineFunction &MF = *B.getParent();
1684 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001685 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001686 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1687 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001688 if (!MI->getOperand(0).isFI())
1689 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001690
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001691 // It is possible that the double vector being stored is only partially
1692 // defined. From the point of view of the liveness tracking, it is ok to
1693 // store it as a whole, but if we break it up we may end up storing a
1694 // register that is entirely undefined.
Matthias Braunac4307c2017-05-26 21:51:00 +00001695 LivePhysRegs LPR(HRI);
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001696 LPR.addLiveIns(B);
1697 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001698 for (auto R = B.begin(); R != It; ++R) {
1699 Clobbers.clear();
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001700 LPR.stepForward(*R, Clobbers);
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001701 // Dead defs are recorded in Clobbers, but are not automatically removed
1702 // from the live set.
1703 for (auto &C : Clobbers)
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +00001704 if (C.second->isReg() && C.second->isDead())
Krzysztof Parzyszek954dd8d2017-01-18 23:11:40 +00001705 LPR.removeReg(C.first);
1706 }
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001707
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001708 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001709 unsigned SrcR = MI->getOperand(2).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001710 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1711 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001712 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001713 int FI = MI->getOperand(0).getIndex();
1714
1715 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001716 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1717 : Hexagon::VectorRegs128BRegClass;
1718 unsigned Size = HRI.getSpillSize(RC);
1719 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001720 unsigned HasAlign = MFI.getObjectAlignment(FI);
1721 unsigned StoreOpc;
1722
1723 // Store low part.
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001724 if (LPR.contains(SrcLo)) {
1725 if (NeedAlign <= HasAlign)
1726 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1727 else
1728 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001729
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001730 BuildMI(B, It, DL, HII.get(StoreOpc))
1731 .addFrameIndex(FI)
1732 .addImm(0)
1733 .addReg(SrcLo, getKillRegState(IsKill))
1734 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1735 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001736
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001737 // Store high part.
1738 if (LPR.contains(SrcHi)) {
1739 if (NeedAlign <= MinAlign(HasAlign, Size))
1740 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1741 else
1742 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001743
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001744 BuildMI(B, It, DL, HII.get(StoreOpc))
1745 .addFrameIndex(FI)
1746 .addImm(Size)
1747 .addReg(SrcHi, getKillRegState(IsKill))
1748 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1749 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001750
1751 B.erase(It);
1752 return true;
1753}
1754
1755bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1756 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1757 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1758 MachineFunction &MF = *B.getParent();
1759 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001760 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001761 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1762 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001763 if (!MI->getOperand(1).isFI())
1764 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001765
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001766 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001767 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001768 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1769 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001770 int FI = MI->getOperand(1).getIndex();
1771
1772 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001773 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1774 : Hexagon::VectorRegs128BRegClass;
1775 unsigned Size = HRI.getSpillSize(RC);
1776 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001777 unsigned HasAlign = MFI.getObjectAlignment(FI);
1778 unsigned LoadOpc;
1779
1780 // Load low part.
1781 if (NeedAlign <= HasAlign)
1782 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1783 else
1784 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1785
1786 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1787 .addFrameIndex(FI)
1788 .addImm(0)
1789 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1790
1791 // Load high part.
1792 if (NeedAlign <= MinAlign(HasAlign, Size))
1793 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1794 else
1795 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1796
1797 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1798 .addFrameIndex(FI)
1799 .addImm(Size)
1800 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1801
1802 B.erase(It);
1803 return true;
1804}
1805
1806bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1807 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1808 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1809 MachineFunction &MF = *B.getParent();
1810 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001811 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001812 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001813 if (!MI->getOperand(0).isFI())
1814 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001815
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001816 auto &HRI = *HST.getRegisterInfo();
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001817 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001818 unsigned SrcR = MI->getOperand(2).getReg();
1819 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001820 int FI = MI->getOperand(0).getIndex();
1821
1822 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001823 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1824 : Hexagon::VectorRegs128BRegClass;
1825 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001826 unsigned HasAlign = MFI.getObjectAlignment(FI);
1827 unsigned StoreOpc;
1828
1829 if (NeedAlign <= HasAlign)
1830 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1831 else
1832 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1833
1834 BuildMI(B, It, DL, HII.get(StoreOpc))
1835 .addFrameIndex(FI)
1836 .addImm(0)
1837 .addReg(SrcR, getKillRegState(IsKill))
1838 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1839
1840 B.erase(It);
1841 return true;
1842}
1843
1844bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1845 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1846 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1847 MachineFunction &MF = *B.getParent();
1848 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001849 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001850 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001851 if (!MI->getOperand(1).isFI())
1852 return false;
1853
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001854 auto &HRI = *HST.getRegisterInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001855 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001856 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001857 int FI = MI->getOperand(1).getIndex();
1858
1859 bool Is128B = HST.useHVXDblOps();
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001860 const auto &RC = !Is128B ? Hexagon::VectorRegsRegClass
1861 : Hexagon::VectorRegs128BRegClass;
1862 unsigned NeedAlign = HRI.getSpillAlignment(RC);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001863 unsigned HasAlign = MFI.getObjectAlignment(FI);
1864 unsigned LoadOpc;
1865
1866 if (NeedAlign <= HasAlign)
1867 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1868 else
1869 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1870
1871 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1872 .addFrameIndex(FI)
1873 .addImm(0)
1874 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1875
1876 B.erase(It);
1877 return true;
1878}
1879
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001880bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1881 SmallVectorImpl<unsigned> &NewRegs) const {
1882 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001883 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001884 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001885 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001886
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001887 for (auto &B : MF) {
1888 // Traverse the basic block.
1889 MachineBasicBlock::iterator NextI;
1890 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1891 MachineInstr *MI = &*I;
1892 NextI = std::next(I);
1893 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001894
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001895 switch (Opc) {
1896 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001897 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001898 break;
1899 case Hexagon::STriw_pred:
1900 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001901 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001902 break;
1903 case Hexagon::LDriw_pred:
1904 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001905 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001906 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001907 case Hexagon::PS_vstorerq_ai:
1908 case Hexagon::PS_vstorerq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001909 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001910 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001911 case Hexagon::PS_vloadrq_ai:
1912 case Hexagon::PS_vloadrq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001913 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001914 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001915 case Hexagon::PS_vloadrw_ai:
1916 case Hexagon::PS_vloadrwu_ai:
1917 case Hexagon::PS_vloadrw_ai_128B:
1918 case Hexagon::PS_vloadrwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001919 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001920 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001921 case Hexagon::PS_vstorerw_ai:
1922 case Hexagon::PS_vstorerwu_ai:
1923 case Hexagon::PS_vstorerw_ai_128B:
1924 case Hexagon::PS_vstorerwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001925 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001926 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001927 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001928 }
1929 }
1930
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001931 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001932}
1933
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001934void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1935 BitVector &SavedRegs,
1936 RegScavenger *RS) const {
1937 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1938 auto &HRI = *HST.getRegisterInfo();
1939
1940 SavedRegs.resize(HRI.getNumRegs());
1941
1942 // If we have a function containing __builtin_eh_return we want to spill and
1943 // restore all callee saved registers. Pretend that they are used.
1944 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1945 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1946 SavedRegs.set(*R);
1947
1948 // Replace predicate register pseudo spill code.
1949 SmallVector<unsigned,8> NewRegs;
1950 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001951 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001952 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001953
1954 // We need to reserve a a spill slot if scavenging could potentially require
1955 // spilling a scavenged register.
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00001956 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +00001957 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001958 MachineRegisterInfo &MRI = MF.getRegInfo();
1959 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001960 // Reserve an int register in any case, because it could be used to hold
1961 // the stack offset in case it does not fit into a spill instruction.
1962 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1963
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001964 for (unsigned VR : NewRegs)
1965 SpillRCs.insert(MRI.getRegClass(VR));
1966
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001967 for (auto *RC : SpillRCs) {
1968 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1969 continue;
1970 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001971 unsigned S = HRI.getSpillSize(*RC), A = HRI.getSpillAlignment(*RC);
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001972 for (unsigned i = 0; i < Num; i++) {
1973 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001974 RS->addScavengingFrameIndex(NewFI);
1975 }
1976 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001977 }
1978
1979 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1980}
1981
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001982unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1983 HexagonBlockRanges::IndexRange &FIR,
1984 HexagonBlockRanges::InstrIndexMap &IndexMap,
1985 HexagonBlockRanges::RegToRangeMap &DeadMap,
1986 const TargetRegisterClass *RC) const {
1987 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1988 auto &MRI = MF.getRegInfo();
1989
1990 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1991 auto F = DeadMap.find({Reg,0});
1992 if (F == DeadMap.end())
1993 return false;
1994 for (auto &DR : F->second)
1995 if (DR.contains(FIR))
1996 return true;
1997 return false;
1998 };
1999
2000 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
2001 bool Dead = true;
2002 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
2003 if (isDead(R.Reg))
2004 continue;
2005 Dead = false;
2006 break;
2007 }
2008 if (Dead)
2009 return Reg;
2010 }
2011 return 0;
2012}
2013
2014void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
2015 SmallVectorImpl<unsigned> &VRegs) const {
2016 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2017 auto &HII = *HST.getInstrInfo();
2018 auto &HRI = *HST.getRegisterInfo();
2019 auto &MRI = MF.getRegInfo();
2020 HexagonBlockRanges HBR(MF);
2021
2022 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
2023 BlockIndexMap;
2024 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
2025 BlockRangeMap;
2026 typedef HexagonBlockRanges::IndexType IndexType;
2027
2028 struct SlotInfo {
2029 BlockRangeMap Map;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00002030 unsigned Size = 0;
2031 const TargetRegisterClass *RC = nullptr;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00002032
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00002033 SlotInfo() = default;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002034 };
2035
2036 BlockIndexMap BlockIndexes;
2037 SmallSet<int,4> BadFIs;
2038 std::map<int,SlotInfo> FIRangeMap;
2039
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002040 // Accumulate register classes: get a common class for a pre-existing
2041 // class HaveRC and a new class NewRC. Return nullptr if a common class
2042 // cannot be found, otherwise return the resulting class. If HaveRC is
2043 // nullptr, assume that it is still unset.
Malcolm Parsons17d266b2017-01-13 17:12:16 +00002044 auto getCommonRC =
2045 [](const TargetRegisterClass *HaveRC,
2046 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002047 if (HaveRC == nullptr || HaveRC == NewRC)
2048 return NewRC;
2049 // Different classes, both non-null. Pick the more general one.
2050 if (HaveRC->hasSubClassEq(NewRC))
2051 return HaveRC;
2052 if (NewRC->hasSubClassEq(HaveRC))
2053 return NewRC;
2054 return nullptr;
2055 };
2056
2057 // Scan all blocks in the function. Check all occurrences of frame indexes,
2058 // and collect relevant information.
2059 for (auto &B : MF) {
2060 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00002061 // Emplace appears not to be supported in gcc 4.7.2-4.
2062 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00002063 auto P = BlockIndexes.insert(
2064 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002065 auto &IndexMap = P.first->second;
2066 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2067 << IndexMap << '\n');
2068
2069 for (auto &In : B) {
2070 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002071 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2072 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002073 if (Load && Store) {
2074 // If it's both a load and a store, then we won't handle it.
2075 BadFIs.insert(LFI);
2076 BadFIs.insert(SFI);
2077 continue;
2078 }
2079 // Check for register classes of the register used as the source for
2080 // the store, and the register used as the destination for the load.
2081 // Also, only accept base+imm_offset addressing modes. Other addressing
2082 // modes can have side-effects (post-increments, etc.). For stack
2083 // slots they are very unlikely, so there is not much loss due to
2084 // this restriction.
2085 if (Load || Store) {
2086 int TFI = Load ? LFI : SFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002087 unsigned AM = HII.getAddrMode(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002088 SlotInfo &SI = FIRangeMap[TFI];
2089 bool Bad = (AM != HexagonII::BaseImmOffset);
2090 if (!Bad) {
2091 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002092 unsigned OpNum = Load ? 0 : 2;
2093 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002094 RC = getCommonRC(SI.RC, RC);
2095 if (RC == nullptr)
2096 Bad = true;
2097 else
2098 SI.RC = RC;
2099 }
2100 if (!Bad) {
2101 // Check sizes.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002102 unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002103 if (SI.Size != 0 && SI.Size != S)
2104 Bad = true;
2105 else
2106 SI.Size = S;
2107 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002108 if (!Bad) {
2109 for (auto *Mo : In.memoperands()) {
2110 if (!Mo->isVolatile())
2111 continue;
2112 Bad = true;
2113 break;
2114 }
2115 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002116 if (Bad)
2117 BadFIs.insert(TFI);
2118 }
2119
2120 // Locate uses of frame indices.
2121 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2122 const MachineOperand &Op = In.getOperand(i);
2123 if (!Op.isFI())
2124 continue;
2125 int FI = Op.getIndex();
2126 // Make sure that the following operand is an immediate and that
2127 // it is 0. This is the offset in the stack object.
2128 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2129 In.getOperand(i+1).getImm() != 0)
2130 BadFIs.insert(FI);
2131 if (BadFIs.count(FI))
2132 continue;
2133
2134 IndexType Index = IndexMap.getIndex(&In);
2135 if (Load) {
2136 if (LastStore[FI] == IndexType::None)
2137 LastStore[FI] = IndexType::Entry;
2138 LastLoad[FI] = Index;
2139 } else if (Store) {
2140 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2141 if (LastStore[FI] != IndexType::None)
2142 RL.add(LastStore[FI], LastLoad[FI], false, false);
2143 else if (LastLoad[FI] != IndexType::None)
2144 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2145 LastLoad[FI] = IndexType::None;
2146 LastStore[FI] = Index;
2147 } else {
2148 BadFIs.insert(FI);
2149 }
2150 }
2151 }
2152
2153 for (auto &I : LastLoad) {
2154 IndexType LL = I.second;
2155 if (LL == IndexType::None)
2156 continue;
2157 auto &RL = FIRangeMap[I.first].Map[&B];
2158 IndexType &LS = LastStore[I.first];
2159 if (LS != IndexType::None)
2160 RL.add(LS, LL, false, false);
2161 else
2162 RL.add(IndexType::Entry, LL, false, false);
2163 LS = IndexType::None;
2164 }
2165 for (auto &I : LastStore) {
2166 IndexType LS = I.second;
2167 if (LS == IndexType::None)
2168 continue;
2169 auto &RL = FIRangeMap[I.first].Map[&B];
2170 RL.add(LS, IndexType::None, false, false);
2171 }
2172 }
2173
2174 DEBUG({
2175 for (auto &P : FIRangeMap) {
2176 dbgs() << "fi#" << P.first;
2177 if (BadFIs.count(P.first))
2178 dbgs() << " (bad)";
2179 dbgs() << " RC: ";
2180 if (P.second.RC != nullptr)
2181 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2182 else
2183 dbgs() << "<null>\n";
2184 for (auto &R : P.second.Map)
2185 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2186 }
2187 });
2188
2189 // When a slot is loaded from in a block without being stored to in the
2190 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2191 // consider this slot to be live-on-exit from all blocks.
2192 SmallSet<int,4> LoxFIs;
2193
2194 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2195
2196 for (auto &P : FIRangeMap) {
2197 // P = pair(FI, map: BB->RangeList)
2198 if (BadFIs.count(P.first))
2199 continue;
2200 for (auto &B : MF) {
2201 auto F = P.second.Map.find(&B);
2202 // F = pair(BB, RangeList)
2203 if (F == P.second.Map.end() || F->second.empty())
2204 continue;
2205 HexagonBlockRanges::IndexRange &IR = F->second.front();
2206 if (IR.start() == IndexType::Entry)
2207 LoxFIs.insert(P.first);
2208 BlockFIMap[&B].push_back(P.first);
2209 }
2210 }
2211
2212 DEBUG({
2213 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2214 for (auto &P : BlockFIMap) {
2215 auto &FIs = P.second;
2216 if (FIs.empty())
2217 continue;
2218 dbgs() << " BB#" << P.first->getNumber() << ": {";
2219 for (auto I : FIs) {
2220 dbgs() << " fi#" << I;
2221 if (LoxFIs.count(I))
2222 dbgs() << '*';
2223 }
2224 dbgs() << " }\n";
2225 }
2226 });
2227
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002228#ifndef NDEBUG
2229 bool HasOptLimit = SpillOptMax.getPosition();
2230#endif
2231
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002232 // eliminate loads, when all loads eliminated, eliminate all stores.
2233 for (auto &B : MF) {
2234 auto F = BlockIndexes.find(&B);
2235 assert(F != BlockIndexes.end());
2236 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2237 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2238 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2239 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2240 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2241
2242 for (auto FI : BlockFIMap[&B]) {
2243 if (BadFIs.count(FI))
2244 continue;
2245 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2246 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2247 for (auto &Range : RL) {
2248 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2249 if (!IndexType::isInstr(Range.start()) ||
2250 !IndexType::isInstr(Range.end()))
2251 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002252 MachineInstr &SI = *IM.getInstr(Range.start());
2253 MachineInstr &EI = *IM.getInstr(Range.end());
2254 assert(SI.mayStore() && "Unexpected start instruction");
2255 assert(EI.mayLoad() && "Unexpected end instruction");
2256 MachineOperand &SrcOp = SI.getOperand(2);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002257
2258 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2259 SrcOp.getSubReg() };
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002260 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002261 // The this-> is needed to unconfuse MSVC.
2262 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2263 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2264 if (FoundR == 0)
2265 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002266#ifndef NDEBUG
2267 if (HasOptLimit) {
2268 if (SpillOptCount >= SpillOptMax)
2269 return;
2270 SpillOptCount++;
2271 }
2272#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002273
2274 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002275 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002276 MachineInstr *CopyIn = nullptr;
2277 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002278 const DebugLoc &DL = SI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002279 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
Diana Picus116bbab2017-01-13 09:58:52 +00002280 .add(SrcOp);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002281 }
2282
2283 ++StartIt;
2284 // Check if this is a last store and the FI is live-on-exit.
2285 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2286 // Update store's source register.
2287 if (unsigned SR = SrcOp.getSubReg())
2288 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2289 else
2290 SrcOp.setReg(FoundR);
2291 SrcOp.setSubReg(0);
2292 // We are keeping this register live.
2293 SrcOp.setIsKill(false);
2294 } else {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002295 B.erase(&SI);
2296 IM.replaceInstr(&SI, CopyIn);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002297 }
2298
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002299 auto EndIt = std::next(EI.getIterator());
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002300 for (auto It = StartIt; It != EndIt; It = NextIt) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002301 MachineInstr &MI = *It;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002302 NextIt = std::next(It);
2303 int TFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002304 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002305 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002306 unsigned DstR = MI.getOperand(0).getReg();
2307 assert(MI.getOperand(0).getSubReg() == 0);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002308 MachineInstr *CopyOut = nullptr;
2309 if (DstR != FoundR) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002310 DebugLoc DL = MI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002311 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2312 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2313 unsigned CopyOpc = TargetOpcode::COPY;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002314 if (HII.isSignExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002315 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002316 else if (HII.isZeroExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002317 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2318 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002319 .addReg(FoundR, getKillRegState(&MI == &EI));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002320 }
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002321 IM.replaceInstr(&MI, CopyOut);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002322 B.erase(It);
2323 }
2324
2325 // Update the dead map.
2326 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2327 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2328 DM[RR].subtract(Range);
2329 } // for Range in range list
2330 }
2331 }
2332}
2333
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002334void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002335 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002336 MachineBasicBlock &MB = *AI->getParent();
2337 DebugLoc DL = AI->getDebugLoc();
2338 unsigned A = AI->getOperand(2).getImm();
2339
2340 // Have
2341 // Rd = alloca Rs, #A
2342 //
2343 // If Rs and Rd are different registers, use this sequence:
2344 // Rd = sub(r29, Rs)
2345 // r29 = sub(r29, Rs)
2346 // Rd = and(Rd, #-A) ; if necessary
2347 // r29 = and(r29, #-A) ; if necessary
2348 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2349 // otherwise, do
2350 // Rd = sub(r29, Rs)
2351 // Rd = and(Rd, #-A) ; if necessary
2352 // r29 = Rd
2353 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2354
2355 MachineOperand &RdOp = AI->getOperand(0);
2356 MachineOperand &RsOp = AI->getOperand(1);
2357 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2358
2359 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002360 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002361 .addReg(SP)
2362 .addReg(Rs);
2363 if (Rs != Rd) {
2364 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002365 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002366 .addReg(SP)
2367 .addReg(Rs);
2368 }
2369 if (A > 8) {
2370 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002371 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002372 .addReg(Rd)
2373 .addImm(-int64_t(A));
2374 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002375 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002376 .addReg(SP)
2377 .addImm(-int64_t(A));
2378 }
2379 if (Rs == Rd) {
2380 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002381 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002382 .addReg(Rd);
2383 }
2384 if (CF > 0) {
2385 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002386 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002387 .addReg(Rd)
2388 .addImm(CF);
2389 }
2390}
2391
2392bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +00002393 const MachineFrameInfo &MFI = MF.getFrameInfo();
2394 if (!MFI.hasVarSizedObjects())
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002395 return false;
Krzysztof Parzyszek71702172017-06-23 19:47:04 +00002396 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002397 if (MaxA <= getStackAlignment())
2398 return false;
2399 return true;
2400}
2401
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002402const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2403 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002404 for (auto &B : MF)
2405 for (auto &I : B)
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00002406 if (I.getOpcode() == Hexagon::PS_aligna)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002407 return &I;
2408 return nullptr;
2409}
2410
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002411/// Adds all callee-saved registers as implicit uses or defs to the
2412/// instruction.
2413void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2414 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2415 // Add the callee-saved registers as implicit uses.
2416 for (auto &R : CSI)
2417 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2418}
2419
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002420/// Determine whether the callee-saved register saves and restores should
2421/// be generated via inline code. If this function returns "true", inline
2422/// code will be generated. If this function returns "false", additional
2423/// checks are performed, which may still lead to the inline code.
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002424bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002425 const CSIVect &CSI) const {
2426 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2427 return true;
Krzysztof Parzyszekf67cd822017-07-11 17:11:54 +00002428 if (!hasFP(MF))
2429 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002430 if (!isOptSize(MF) && !isMinSize(MF))
2431 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2432 return true;
2433
2434 // Check if CSI only has double registers, and if the registers form
2435 // a contiguous block starting from D8.
2436 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2437 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2438 unsigned R = CSI[i].getReg();
2439 if (!Hexagon::DoubleRegsRegClass.contains(R))
2440 return true;
2441 Regs[R] = true;
2442 }
2443 int F = Regs.find_first();
2444 if (F != Hexagon::D8)
2445 return true;
2446 while (F >= 0) {
2447 int N = Regs.find_next(F);
2448 if (N >= 0 && N != F+1)
2449 return true;
2450 F = N;
2451 }
2452
2453 return false;
2454}
2455
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002456bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002457 const CSIVect &CSI) const {
2458 if (shouldInlineCSR(MF, CSI))
2459 return false;
2460 unsigned NumCSI = CSI.size();
2461 if (NumCSI <= 1)
2462 return false;
2463
2464 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2465 : SpillFuncThreshold;
2466 return Threshold < NumCSI;
2467}
2468
Krzysztof Parzyszek9eb75c42017-06-30 21:21:40 +00002469bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002470 const CSIVect &CSI) const {
2471 if (shouldInlineCSR(MF, CSI))
2472 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002473 // The restore functions do a bit more than just restoring registers.
2474 // The non-returning versions will go back directly to the caller's
2475 // caller, others will clean up the stack frame in preparation for
2476 // a tail call. Using them can still save code size even if only one
2477 // register is getting restores. Make the decision based on -Oz:
2478 // using -Os will use inline restore for a single register.
2479 if (isMinSize(MF))
2480 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002481 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002482 if (NumCSI <= 1)
2483 return false;
2484
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002485 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2486 : SpillFuncThreshold;
2487 return Threshold < NumCSI;
2488}
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002489
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002490bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2491 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2492 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2493 // A fairly simplistic guess as to whether a potential load/store to a
Krzysztof Parzyszek69ffba42017-06-22 14:11:23 +00002494 // stack location could require an extra register.
2495 if (HST.useHVXOps() && StackSize > 256)
2496 return true;
2497
2498 // Check if the function has store-immediate instructions that access
2499 // the stack. Since the offset field is not extendable, if the stack
2500 // size exceeds the offset limit (6 bits, shifted), the stores will
2501 // require a new base register.
2502 bool HasImmStack = false;
2503 unsigned MinLS = ~0u; // Log_2 of the memory access size.
2504
2505 for (const MachineBasicBlock &B : MF) {
2506 for (const MachineInstr &MI : B) {
2507 unsigned LS = 0;
2508 switch (MI.getOpcode()) {
2509 case Hexagon::S4_storeirit_io:
2510 case Hexagon::S4_storeirif_io:
2511 case Hexagon::S4_storeiri_io:
2512 ++LS;
2513 LLVM_FALLTHROUGH;
2514 case Hexagon::S4_storeirht_io:
2515 case Hexagon::S4_storeirhf_io:
2516 case Hexagon::S4_storeirh_io:
2517 ++LS;
2518 LLVM_FALLTHROUGH;
2519 case Hexagon::S4_storeirbt_io:
2520 case Hexagon::S4_storeirbf_io:
2521 case Hexagon::S4_storeirb_io:
2522 if (MI.getOperand(0).isFI())
2523 HasImmStack = true;
2524 MinLS = std::min(MinLS, LS);
2525 break;
2526 }
2527 }
2528 }
2529
2530 if (HasImmStack)
2531 return !isUInt<6>(StackSize >> MinLS);
2532
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002533 return false;
2534}