blob: a3f6273f9f67a79c06c6d6aa3170782d310f7182 [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonFrameLowering.cpp - Define frame lowering ------------------===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//
9//===----------------------------------------------------------------------===//
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000010
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000011#define DEBUG_TYPE "hexagon-pei"
12
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +000013#include "HexagonBlockRanges.h"
Craig Topperb25fda92012-03-17 18:46:09 +000014#include "HexagonFrameLowering.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000015#include "HexagonInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000017#include "HexagonRegisterInfo.h"
18#include "HexagonSubtarget.h"
19#include "HexagonTargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000020#include "MCTargetDesc/HexagonBaseInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000021#include "llvm/ADT/BitVector.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000022#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000025#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000026#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/SmallVector.h"
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +000029#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000030#include "llvm/CodeGen/MachineBasicBlock.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000031#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000032#include "llvm/CodeGen/MachineFrameInfo.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000033#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000035#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000037#include "llvm/CodeGen/MachineMemOperand.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000038#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000039#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +000040#include "llvm/CodeGen/MachinePostDominators.h"
Benjamin Kramerae87d7b2012-02-06 10:19:29 +000041#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/RegisterScavenging.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000043#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000045#include "llvm/MC/MCDwarf.h"
46#include "llvm/MC/MCRegisterInfo.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/CodeGen.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Support/CommandLine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000050#include "llvm/Support/Debug.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000051#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/MathExtras.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000053#include "llvm/Support/raw_ostream.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000054#include "llvm/Target/TargetMachine.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000055#include "llvm/Target/TargetRegisterInfo.h"
56#include <algorithm>
57#include <cassert>
58#include <cstdint>
59#include <iterator>
60#include <limits>
61#include <map>
62#include <new>
63#include <utility>
64#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000065
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000066// Hexagon stack frame layout as defined by the ABI:
67//
68// Incoming arguments
69// passed via stack
70// |
71// |
72// SP during function's FP during function's |
73// +-- runtime (top of stack) runtime (bottom) --+ |
74// | | |
75// --++---------------------+------------------+-----------------++-+-------
76// | parameter area for | variable-size | fixed-size |LR| arg
77// | called functions | local objects | local objects |FP|
78// --+----------------------+------------------+-----------------+--+-------
79// <- size known -> <- size unknown -> <- size known ->
80//
81// Low address High address
82//
83// <--- stack growth
84//
85//
86// - In any circumstances, the outgoing function arguments are always accessi-
87// ble using the SP, and the incoming arguments are accessible using the FP.
88// - If the local objects are not aligned, they can always be accessed using
89// the FP.
90// - If there are no variable-sized objects, the local objects can always be
91// accessed using the SP, regardless whether they are aligned or not. (The
92// alignment padding will be at the bottom of the stack (highest address),
93// and so the offset with respect to the SP will be known at the compile-
94// -time.)
95//
96// The only complication occurs if there are both, local aligned objects, and
97// dynamically allocated (variable-sized) objects. The alignment pad will be
98// placed between the FP and the local objects, thus preventing the use of the
99// FP to access the local objects. At the same time, the variable-sized objects
100// will be between the SP and the local objects, thus introducing an unknown
101// distance from the SP to the locals.
102//
103// To avoid this problem, a new register is created that holds the aligned
104// address of the bottom of the stack, referred in the sources as AP (aligned
105// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
106// that aligns AP to the required boundary (a maximum of the alignments of
107// all stack objects, fixed- and variable-sized). All local objects[1] will
108// then use AP as the base pointer.
109// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
110// their name from being allocated at fixed locations on the stack, relative
111// to the FP. In the presence of dynamic allocation and local alignment, such
112// objects can only be accessed through the FP.
113//
114// Illustration of the AP:
115// FP --+
116// |
117// ---------------+---------------------+-----+-----------------------++-+--
118// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
119// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
120// ---------------+---------------------+-----+-----------------+-----+--+--
121// |<-- Multiple of the -->|
122// stack alignment +-- AP
123//
124// The AP is set up at the beginning of the function. Since it is not a dedi-
125// cated (reserved) register, it needs to be kept live throughout the function
126// to be available as the base register for local object accesses.
127// Normally, an address of a stack objects is obtained by a pseudo-instruction
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000128// PS_fi. To access local objects with the AP register present, a different
129// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
130// argument compared to PS_fi: the first input register is the AP register.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000131// This keeps the register live between its definition and its uses.
132
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000133// The AP register is originally set up using pseudo-instruction PS_aligna:
134// AP = PS_aligna A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000135// where
136// A - required stack alignment
137// The alignment value must be the maximum of all alignments required by
138// any stack object.
139
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000140// The dynamic allocation uses a pseudo-instruction PS_alloca:
141// Rd = PS_alloca Rs, A
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000142// where
143// Rd - address of the allocated space
144// Rs - minimum size (the actual allocated can be larger to accommodate
145// alignment)
146// A - required alignment
147
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000148using namespace llvm;
149
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000150static cl::opt<bool> DisableDeallocRet("disable-hexagon-dealloc-ret",
151 cl::Hidden, cl::desc("Disable Dealloc Return for Hexagon target"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000152
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +0000153static cl::opt<unsigned> NumberScavengerSlots("number-scavenger-slots",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000154 cl::Hidden, cl::desc("Set the number of scavenger slots"), cl::init(2),
155 cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000156
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000157static cl::opt<int> SpillFuncThreshold("spill-func-threshold",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000158 cl::Hidden, cl::desc("Specify O2(not Os) spill func threshold"),
159 cl::init(6), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000160
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000161static cl::opt<int> SpillFuncThresholdOs("spill-func-threshold-Os",
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000162 cl::Hidden, cl::desc("Specify Os spill func threshold"),
163 cl::init(1), cl::ZeroOrMore);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000164
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000165static cl::opt<bool> EnableStackOVFSanitizer("enable-stackovf-sanitizer",
166 cl::Hidden, cl::desc("Enable runtime checks for stack overflow."),
167 cl::init(false), cl::ZeroOrMore);
168
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000169static cl::opt<bool> EnableShrinkWrapping("hexagon-shrink-frame",
170 cl::init(true), cl::Hidden, cl::ZeroOrMore,
171 cl::desc("Enable stack frame shrink wrapping"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000172
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000173static cl::opt<unsigned> ShrinkLimit("shrink-frame-limit",
174 cl::init(std::numeric_limits<unsigned>::max()), cl::Hidden, cl::ZeroOrMore,
175 cl::desc("Max count of stack frame shrink-wraps"));
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000176
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000177static cl::opt<bool> EnableSaveRestoreLong("enable-save-restore-long",
178 cl::Hidden, cl::desc("Enable long calls for save-restore stubs."),
179 cl::init(false), cl::ZeroOrMore);
180
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000181static cl::opt<bool> UseAllocframe("use-allocframe", cl::init(true),
182 cl::Hidden, cl::desc("Use allocframe more conservatively"));
183
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +0000184static cl::opt<bool> OptimizeSpillSlots("hexagon-opt-spill", cl::Hidden,
185 cl::init(true), cl::desc("Optimize spill slots"));
186
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000187#ifndef NDEBUG
188static cl::opt<unsigned> SpillOptMax("spill-opt-max", cl::Hidden,
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000189 cl::init(std::numeric_limits<unsigned>::max()));
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +0000190static unsigned SpillOptCount = 0;
191#endif
192
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000193namespace llvm {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000194
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000195 void initializeHexagonCallFrameInformationPass(PassRegistry&);
196 FunctionPass *createHexagonCallFrameInformation();
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000197
198} // end namespace llvm
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000199
200namespace {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000201
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000202 class HexagonCallFrameInformation : public MachineFunctionPass {
203 public:
204 static char ID;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000205
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000206 HexagonCallFrameInformation() : MachineFunctionPass(ID) {
207 PassRegistry &PR = *PassRegistry::getPassRegistry();
208 initializeHexagonCallFrameInformationPass(PR);
209 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000210
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000211 bool runOnMachineFunction(MachineFunction &MF) override;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000212
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000213 MachineFunctionProperties getRequiredProperties() const override {
214 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000215 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000216 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000217 };
218
219 char HexagonCallFrameInformation::ID = 0;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000220
221} // end anonymous namespace
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000222
223bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
224 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
225 bool NeedCFI = MF.getMMI().hasDebugInfo() ||
226 MF.getFunction()->needsUnwindTableEntry();
227
228 if (!NeedCFI)
229 return false;
230 HFI.insertCFIInstructions(MF);
231 return true;
232}
233
234INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
235 "Hexagon call frame information", false, false)
236
237FunctionPass *llvm::createHexagonCallFrameInformation() {
238 return new HexagonCallFrameInformation();
239}
240
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000241/// Map a register pair Reg to the subregister that has the greater "number",
242/// i.e. D3 (aka R7:6) will be mapped to R7, etc.
243static unsigned getMax32BitSubRegister(unsigned Reg,
244 const TargetRegisterInfo &TRI,
245 bool hireg = true) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000246 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
247 return Reg;
248
249 unsigned RegNo = 0;
250 for (MCSubRegIterator SubRegs(Reg, &TRI); SubRegs.isValid(); ++SubRegs) {
251 if (hireg) {
252 if (*SubRegs > RegNo)
253 RegNo = *SubRegs;
254 } else {
255 if (!RegNo || *SubRegs < RegNo)
256 RegNo = *SubRegs;
257 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000258 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000259 return RegNo;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000260}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000261
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000262/// Returns the callee saved register with the largest id in the vector.
263static unsigned getMaxCalleeSavedReg(const std::vector<CalleeSavedInfo> &CSI,
264 const TargetRegisterInfo &TRI) {
Benjamin Kramer3e9a5d32016-05-27 11:36:04 +0000265 static_assert(Hexagon::R1 > 0,
266 "Assume physical registers are encoded as positive integers");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000267 if (CSI.empty())
268 return 0;
269
270 unsigned Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
271 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
272 unsigned Reg = getMax32BitSubRegister(CSI[I].getReg(), TRI);
273 if (Reg > Max)
274 Max = Reg;
275 }
276 return Max;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000277}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000278
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000279/// Checks if the basic block contains any instruction that needs a stack
280/// frame to be already in place.
281static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
282 const HexagonRegisterInfo &HRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000283 for (auto &I : MBB) {
284 const MachineInstr *MI = &I;
285 if (MI->isCall())
286 return true;
287 unsigned Opc = MI->getOpcode();
288 switch (Opc) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000289 case Hexagon::PS_alloca:
290 case Hexagon::PS_aligna:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000291 return true;
292 default:
293 break;
294 }
295 // Check individual operands.
Matthias Braune41e1462015-05-29 02:56:46 +0000296 for (const MachineOperand &MO : MI->operands()) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000297 // While the presence of a frame index does not prove that a stack
298 // frame will be required, all frame indexes should be within alloc-
299 // frame/deallocframe. Otherwise, the code that translates a frame
300 // index into an offset would have to be aware of the placement of
301 // the frame creation/destruction instructions.
Matthias Braune41e1462015-05-29 02:56:46 +0000302 if (MO.isFI())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000303 return true;
Matthias Braune41e1462015-05-29 02:56:46 +0000304 if (!MO.isReg())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000305 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000306 unsigned R = MO.getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000307 // Virtual registers will need scavenging, which then may require
308 // a stack slot.
309 if (TargetRegisterInfo::isVirtualRegister(R))
310 return true;
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000311 for (MCSubRegIterator S(R, &HRI, true); S.isValid(); ++S)
312 if (CSR[*S])
313 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000314 }
315 }
316 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000317}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000318
319 /// Returns true if MBB has a machine instructions that indicates a tail call
320 /// in the block.
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000321static bool hasTailCall(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000322 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
323 unsigned RetOpc = I->getOpcode();
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000324 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000325}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000326
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000327/// Returns true if MBB contains an instruction that returns.
328static bool hasReturn(const MachineBasicBlock &MBB) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000329 for (auto I = MBB.getFirstTerminator(), E = MBB.end(); I != E; ++I)
330 if (I->isReturn())
331 return true;
332 return false;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000333}
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +0000334
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000335/// Returns the "return" instruction from this block, or nullptr if there
336/// isn't any.
337static MachineInstr *getReturn(MachineBasicBlock &MBB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000338 for (auto &I : MBB)
339 if (I.isReturn())
340 return &I;
341 return nullptr;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000342}
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000343
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000344static bool isRestoreCall(unsigned Opc) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000345 switch (Opc) {
346 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
347 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000348 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
349 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
350 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
351 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000352 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
353 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
354 return true;
355 }
356 return false;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000357}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000358
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000359static inline bool isOptNone(const MachineFunction &MF) {
360 return MF.getFunction()->hasFnAttribute(Attribute::OptimizeNone) ||
361 MF.getTarget().getOptLevel() == CodeGenOpt::None;
362}
363
364static inline bool isOptSize(const MachineFunction &MF) {
365 const Function &F = *MF.getFunction();
366 return F.optForSize() && !F.optForMinSize();
367}
368
369static inline bool isMinSize(const MachineFunction &MF) {
370 return MF.getFunction()->optForMinSize();
371}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000372
373/// Implements shrink-wrapping of the stack frame. By default, stack frame
374/// is created in the function entry block, and is cleaned up in every block
375/// that returns. This function finds alternate blocks: one for the frame
376/// setup (prolog) and one for the cleanup (epilog).
377void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
378 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
379 static unsigned ShrinkCounter = 0;
380
381 if (ShrinkLimit.getPosition()) {
382 if (ShrinkCounter >= ShrinkLimit)
383 return;
384 ShrinkCounter++;
385 }
386
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000387 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000388 auto &HRI = *HST.getRegisterInfo();
389
390 MachineDominatorTree MDT;
391 MDT.runOnMachineFunction(MF);
392 MachinePostDominatorTree MPT;
393 MPT.runOnMachineFunction(MF);
394
395 typedef DenseMap<unsigned,unsigned> UnsignedMap;
396 UnsignedMap RPO;
397 typedef ReversePostOrderTraversal<const MachineFunction*> RPOTType;
398 RPOTType RPOT(&MF);
399 unsigned RPON = 0;
400 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I)
401 RPO[(*I)->getNumber()] = RPON++;
402
403 // Don't process functions that have loops, at least for now. Placement
404 // of prolog and epilog must take loop structure into account. For simpli-
405 // city don't do it right now.
406 for (auto &I : MF) {
407 unsigned BN = RPO[I.getNumber()];
408 for (auto SI = I.succ_begin(), SE = I.succ_end(); SI != SE; ++SI) {
409 // If found a back-edge, return.
410 if (RPO[(*SI)->getNumber()] <= BN)
411 return;
412 }
413 }
414
415 // Collect the set of blocks that need a stack frame to execute. Scan
416 // each block for uses/defs of callee-saved registers, calls, etc.
417 SmallVector<MachineBasicBlock*,16> SFBlocks;
418 BitVector CSR(Hexagon::NUM_TARGET_REGS);
419 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000420 for (MCSubRegIterator S(*P, &HRI, true); S.isValid(); ++S)
421 CSR[*S] = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000422
423 for (auto &I : MF)
Krzysztof Parzyszek01598de2016-03-24 20:31:41 +0000424 if (needsStackFrame(I, CSR, HRI))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000425 SFBlocks.push_back(&I);
426
427 DEBUG({
428 dbgs() << "Blocks needing SF: {";
429 for (auto &B : SFBlocks)
430 dbgs() << " BB#" << B->getNumber();
431 dbgs() << " }\n";
432 });
433 // No frame needed?
434 if (SFBlocks.empty())
435 return;
436
437 // Pick a common dominator and a common post-dominator.
438 MachineBasicBlock *DomB = SFBlocks[0];
439 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
440 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
441 if (!DomB)
442 break;
443 }
444 MachineBasicBlock *PDomB = SFBlocks[0];
445 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
446 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
447 if (!PDomB)
448 break;
449 }
450 DEBUG({
451 dbgs() << "Computed dom block: BB#";
452 if (DomB) dbgs() << DomB->getNumber();
453 else dbgs() << "<null>";
454 dbgs() << ", computed pdom block: BB#";
455 if (PDomB) dbgs() << PDomB->getNumber();
456 else dbgs() << "<null>";
457 dbgs() << "\n";
458 });
459 if (!DomB || !PDomB)
460 return;
461
462 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
463 if (!MDT.dominates(DomB, PDomB)) {
464 DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
465 return;
466 }
467 if (!MPT.dominates(PDomB, DomB)) {
468 DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
469 return;
470 }
471
472 // Finally, everything seems right.
473 PrologB = DomB;
474 EpilogB = PDomB;
475}
476
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000477/// Perform most of the PEI work here:
478/// - saving/restoring of the callee-saved registers,
479/// - stack frame creation and destruction.
480/// Normally, this work is distributed among various functions, but doing it
481/// in one place allows shrink-wrapping of the stack frame.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000482void HexagonFrameLowering::emitPrologue(MachineFunction &MF,
483 MachineBasicBlock &MBB) const {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000484 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000485 auto &HRI = *HST.getRegisterInfo();
486
Matthias Braun941a7052016-07-28 18:40:00 +0000487 MachineFrameInfo &MFI = MF.getFrameInfo();
488 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000489
490 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
491 if (EnableShrinkWrapping)
492 findShrunkPrologEpilog(MF, PrologB, EpilogB);
493
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000494 bool PrologueStubs = false;
495 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
496 insertPrologueInBlock(*PrologB, PrologueStubs);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000497 updateEntryPaths(MF, *PrologB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000498
499 if (EpilogB) {
500 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
501 insertEpilogueInBlock(*EpilogB);
502 } else {
503 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000504 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000505 insertCSRRestoresInBlock(B, CSI, HRI);
506
507 for (auto &B : MF)
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000508 if (B.isReturnBlock())
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000509 insertEpilogueInBlock(B);
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000510
511 for (auto &B : MF) {
512 if (B.empty())
513 continue;
514 MachineInstr *RetI = getReturn(B);
515 if (!RetI || isRestoreCall(RetI->getOpcode()))
516 continue;
517 for (auto &R : CSI)
518 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
519 }
520 }
521
522 if (EpilogB) {
523 // If there is an epilog block, it may not have a return instruction.
524 // In such case, we need to add the callee-saved registers as live-ins
525 // in all blocks on all paths from the epilog to any return block.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000526 unsigned MaxBN = MF.getNumBlockIDs();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000527 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000528 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000529 }
530}
531
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000532void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
533 bool PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000534 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000535 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000536 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000537 auto &HII = *HST.getInstrInfo();
538 auto &HRI = *HST.getRegisterInfo();
539 DebugLoc dl;
540
Matthias Braun941a7052016-07-28 18:40:00 +0000541 unsigned MaxAlign = std::max(MFI.getMaxAlignment(), getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000542
543 // Calculate the total stack frame size.
544 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000545 unsigned FrameSize = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000546 // Round up the max call frame size to the max alignment on the stack.
Matthias Braun941a7052016-07-28 18:40:00 +0000547 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
548 MFI.setMaxCallFrameSize(MaxCFA);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000549
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000550 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
Matthias Braun941a7052016-07-28 18:40:00 +0000551 MFI.setStackSize(FrameSize);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000552
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000553 bool AlignStack = (MaxAlign > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000554
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000555 // Get the number of bytes to allocate from the FrameInfo.
Matthias Braun941a7052016-07-28 18:40:00 +0000556 unsigned NumBytes = MFI.getStackSize();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000557 unsigned SP = HRI.getStackRegister();
Matthias Braun941a7052016-07-28 18:40:00 +0000558 unsigned MaxCF = MFI.getMaxCallFrameSize();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000559 MachineBasicBlock::iterator InsertPt = MBB.begin();
560
Krzysztof Parzyszek8849a512016-08-19 18:46:13 +0000561 SmallVector<MachineInstr *, 4> AdjustRegs;
562 for (auto &MBB : MF)
563 for (auto &MI : MBB)
564 if (MI.getOpcode() == Hexagon::PS_alloca)
565 AdjustRegs.push_back(&MI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000566
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000567 for (auto MI : AdjustRegs) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000568 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000569 expandAlloca(MI, HII, SP, MaxCF);
570 MI->eraseFromParent();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000571 }
572
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000573 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000574 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000575
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000576 // Check for overflow.
577 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
578 const unsigned int ALLOCFRAME_MAX = 16384;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000579
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000580 // Create a dummy memory operand to avoid allocframe from being treated as
581 // a volatile memory reference.
582 MachineMemOperand *MMO =
583 MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOStore,
584 4, 4);
585
586 if (NumBytes >= ALLOCFRAME_MAX) {
587 // Emit allocframe(#0).
588 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
589 .addImm(0)
590 .addMemOperand(MMO);
591
592 // Subtract offset from frame pointer.
593 // We use a caller-saved non-parameter register for that.
594 unsigned CallerSavedReg = HRI.getFirstCallerSavedNonParamReg();
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000595 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::CONST32),
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000596 CallerSavedReg).addImm(NumBytes);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000597 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_sub), SP)
598 .addReg(SP)
599 .addReg(CallerSavedReg);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000600 } else {
601 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
602 .addImm(NumBytes)
603 .addMemOperand(MMO);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000604 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000605
606 if (AlignStack) {
607 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
608 .addReg(SP)
609 .addImm(-int64_t(MaxAlign));
610 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000611
612 // If the stack-checking is enabled, and we spilled the callee-saved
613 // registers inline (i.e. did not use a spill function), then call
614 // the stack checker directly.
615 if (EnableStackOVFSanitizer && !PrologueStubs)
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000616 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000617 .addExternalSymbol("__runtime_stack_check");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000618}
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000619
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000620void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
621 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000622 if (!hasFP(MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000623 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000624
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +0000625 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000626 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000627 auto &HRI = *HST.getRegisterInfo();
628 unsigned SP = HRI.getStackRegister();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000629
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000630 MachineInstr *RetI = getReturn(MBB);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000631 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
632
633 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
634 DebugLoc DL;
635 if (InsertPt != MBB.end())
636 DL = InsertPt->getDebugLoc();
637 else if (!MBB.empty())
638 DL = std::prev(MBB.end())->getDebugLoc();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000639
640 // Handle EH_RETURN.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000641 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000642 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
643 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::A2_add), SP)
644 .addReg(SP)
645 .addReg(Hexagon::R28);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000646 return;
647 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000648
649 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
650 // frame instruction if we encounter it.
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000651 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000652 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
653 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
654 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000655 MachineBasicBlock::iterator It = RetI;
656 ++It;
657 // Delete all instructions after the RESTORE (except labels).
658 while (It != MBB.end()) {
659 if (!It->isLabel())
660 It = MBB.erase(It);
661 else
662 ++It;
Jyotsna Verma300f0b92013-05-10 20:27:34 +0000663 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000664 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000665 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000666
667 // It is possible that the restoring code is a call to a library function.
668 // All of the restore* functions include "deallocframe", so we need to make
669 // sure that we don't add an extra one.
670 bool NeedsDeallocframe = true;
671 if (!MBB.empty() && InsertPt != MBB.begin()) {
672 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
673 unsigned COpc = PrevIt->getOpcode();
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +0000674 if (COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
Krzysztof Parzyszekfae79862016-07-27 18:47:25 +0000675 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
676 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
677 COpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000678 COpc == Hexagon::PS_call_nr || COpc == Hexagon::PS_callr_nr)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000679 NeedsDeallocframe = false;
680 }
681
682 if (!NeedsDeallocframe)
683 return;
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000684 // If the returning instruction is PS_jmpret, replace it with dealloc_return,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000685 // otherwise just add deallocframe. The function could be returning via a
686 // tail call.
Krzysztof Parzyszekbe976d42016-08-12 11:12:02 +0000687 if (RetOpc != Hexagon::PS_jmpret || DisableDeallocRet) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000688 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::L2_deallocframe));
689 return;
690 }
691 unsigned NewOpc = Hexagon::L4_return;
692 MachineInstr *NewI = BuildMI(MBB, RetI, DL, HII.get(NewOpc));
693 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +0000694 NewI->copyImplicitOps(MF, *RetI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000695 MBB.erase(RetI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000696}
697
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000698void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
699 MachineBasicBlock &SaveB) const {
700 SetVector<unsigned> Worklist;
701
702 MachineBasicBlock &EntryB = MF.front();
703 Worklist.insert(EntryB.getNumber());
704
705 unsigned SaveN = SaveB.getNumber();
Matthias Braun941a7052016-07-28 18:40:00 +0000706 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000707
708 for (unsigned i = 0; i < Worklist.size(); ++i) {
709 unsigned BN = Worklist[i];
710 MachineBasicBlock &MBB = *MF.getBlockNumbered(BN);
711 for (auto &R : CSI)
712 if (!MBB.isLiveIn(R.getReg()))
713 MBB.addLiveIn(R.getReg());
714 if (BN != SaveN)
715 for (auto &SB : MBB.successors())
716 Worklist.insert(SB->getNumber());
717 }
718}
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +0000719
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000720bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000721 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000722 BitVector &Path) const {
723 assert(MBB.getNumber() >= 0);
724 unsigned BN = MBB.getNumber();
725 if (Path[BN] || DoneF[BN])
726 return false;
727 if (DoneT[BN])
728 return true;
729
Matthias Braun941a7052016-07-28 18:40:00 +0000730 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000731
732 Path[BN] = true;
733 bool ReachedExit = false;
734 for (auto &SB : MBB.successors())
735 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
736
737 if (!MBB.empty() && MBB.back().isReturn()) {
738 // Add implicit uses of all callee-saved registers to the reached
739 // return instructions. This is to prevent the anti-dependency breaker
740 // from renaming these registers.
741 MachineInstr &RetI = MBB.back();
742 if (!isRestoreCall(RetI.getOpcode()))
743 for (auto &R : CSI)
744 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
745 ReachedExit = true;
746 }
747
748 // We don't want to add unnecessary live-ins to the restore block: since
749 // the callee-saved registers are being defined in it, the entry of the
750 // restore block cannot be on the path from the definitions to any exit.
Krzysztof Parzyszeka34d6392016-07-27 16:26:39 +0000751 if (ReachedExit && &MBB != &RestoreB) {
Krzysztof Parzyszekda0b9a92016-05-26 19:44:28 +0000752 for (auto &R : CSI)
753 if (!MBB.isLiveIn(R.getReg()))
754 MBB.addLiveIn(R.getReg());
755 DoneT[BN] = true;
756 }
757 if (!ReachedExit)
758 DoneF[BN] = true;
759
760 Path[BN] = false;
761 return ReachedExit;
762}
763
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000764static Optional<MachineBasicBlock::iterator>
765findCFILocation(MachineBasicBlock &B) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000766 // The CFI instructions need to be inserted right after allocframe.
767 // An exception to this is a situation where allocframe is bundled
768 // with a call: then the CFI instructions need to be inserted before
769 // the packet with the allocframe+call (in case the call throws an
770 // exception).
771 auto End = B.instr_end();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000772
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000773 for (MachineInstr &I : B) {
774 MachineBasicBlock::iterator It = I.getIterator();
775 if (!I.isBundle()) {
776 if (I.getOpcode() == Hexagon::S2_allocframe)
777 return std::next(It);
778 continue;
779 }
780 // I is a bundle.
781 bool HasCall = false, HasAllocFrame = false;
782 auto T = It.getInstrIterator();
783 while (++T != End && T->isBundled()) {
784 if (T->getOpcode() == Hexagon::S2_allocframe)
785 HasAllocFrame = true;
786 else if (T->isCall())
787 HasCall = true;
788 }
789 if (HasAllocFrame)
790 return HasCall ? It : std::next(It);
791 }
792 return None;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000793}
794
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000795void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const {
796 for (auto &B : MF) {
Krzysztof Parzyszekc43644d2016-07-28 19:13:46 +0000797 auto At = findCFILocation(B);
798 if (At.hasValue())
799 insertCFIInstructionsAt(B, At.getValue());
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000800 }
801}
802
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000803void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
804 MachineBasicBlock::iterator At) const {
805 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000806 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000807 MachineModuleInfo &MMI = MF.getMMI();
808 auto &HST = MF.getSubtarget<HexagonSubtarget>();
809 auto &HII = *HST.getInstrInfo();
810 auto &HRI = *HST.getRegisterInfo();
811
812 // If CFI instructions have debug information attached, something goes
813 // wrong with the final assembly generation: the prolog_end is placed
814 // in a wrong location.
815 DebugLoc DL;
816 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
817
818 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000819 bool HasFP = hasFP(MF);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000820
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000821 if (HasFP) {
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000822 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
823 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000824
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000825 // Define CFA via an offset from the value of FP.
826 //
827 // -8 -4 0 (SP)
828 // --+----+----+---------------------
829 // | FP | LR | increasing addresses -->
830 // --+----+----+---------------------
831 // | +-- Old SP (before allocframe)
832 // +-- New FP (after allocframe)
833 //
834 // MCCFIInstruction::createDefCfa subtracts the offset from the register.
835 // MCCFIInstruction::createOffset takes the offset without sign change.
836 auto DefCfa = MCCFIInstruction::createDefCfa(FrameLabel, DwFPReg, -8);
837 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000838 .addCFIIndex(MF.addFrameInst(DefCfa));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000839 // R31 (return addr) = CFA - 4
840 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
841 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000842 .addCFIIndex(MF.addFrameInst(OffR31));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000843 // R30 (frame ptr) = CFA - 8
844 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
845 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000846 .addCFIIndex(MF.addFrameInst(OffR30));
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000847 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000848
849 static unsigned int RegsToMove[] = {
850 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
851 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
852 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
853 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
854 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
855 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13,
856 Hexagon::NoRegister
857 };
858
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000859 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000860
861 for (unsigned i = 0; RegsToMove[i] != Hexagon::NoRegister; ++i) {
862 unsigned Reg = RegsToMove[i];
863 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
864 return C.getReg() == Reg;
865 };
David Majnemer562e8292016-08-12 00:18:03 +0000866 auto F = find_if(CSI, IfR);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000867 if (F == CSI.end())
868 continue;
869
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000870 int64_t Offset;
871 if (HasFP) {
872 // If the function has a frame pointer (i.e. has an allocframe),
873 // then the CFA has been defined in terms of FP. Any offsets in
874 // the following CFI instructions have to be defined relative
875 // to FP, which points to the bottom of the stack frame.
876 // The function getFrameIndexReference can still choose to use SP
877 // for the offset calculation, so we cannot simply call it here.
878 // Instead, get the offset (relative to the FP) directly.
879 Offset = MFI.getObjectOffset(F->getFrameIdx());
880 } else {
881 unsigned FrameReg;
882 Offset = getFrameIndexReference(MF, F->getFrameIdx(), FrameReg);
883 }
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000884 // Subtract 8 to make room for R30 and R31, which are added above.
Krzysztof Parzyszekc2c78682016-05-11 14:53:07 +0000885 Offset -= 8;
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000886
887 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
888 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
889 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
890 Offset);
891 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000892 .addCFIIndex(MF.addFrameInst(OffReg));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000893 } else {
894 // Split the double regs into subregs, and generate appropriate
895 // cfi_offsets.
896 // The only reason, we are split double regs is, llvm-mc does not
897 // understand paired registers for cfi_offset.
898 // Eg .cfi_offset r1:0, -64
899
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000900 unsigned HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
901 unsigned LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000902 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
903 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
904 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
905 Offset+4);
906 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000907 .addCFIIndex(MF.addFrameInst(OffHi));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000908 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
909 Offset);
910 BuildMI(MBB, At, DL, CFID)
Matthias Braunf23ef432016-11-30 23:48:42 +0000911 .addCFIIndex(MF.addFrameInst(OffLo));
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +0000912 }
913 }
914}
915
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000916bool HexagonFrameLowering::hasFP(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000917 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000918 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
919
920 bool HasFixed = MFI.getNumFixedObjects();
921 bool HasPrealloc = const_cast<MachineFrameInfo&>(MFI)
922 .getLocalFrameObjectCount();
923 bool HasExtraAlign = HRI.needsStackRealignment(MF);
924 bool HasAlloca = MFI.hasVarSizedObjects();
925
926 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
927 // that this shouldn't be required, but doing so now because gcc does and
928 // gdb can't break at the start of the function without it. Will remove if
929 // this turns out to be a gdb bug.
930 //
931 if (MF.getTarget().getOptLevel() == CodeGenOpt::None)
932 return true;
933
934 // By default we want to use SP (since it's always there). FP requires
935 // some setup (i.e. ALLOCFRAME).
936 // Fixed and preallocated objects need FP if the distance from them to
937 // the SP is unknown (as is with alloca or aligna).
938 if ((HasFixed || HasPrealloc) && (HasAlloca || HasExtraAlign))
939 return true;
940
941 if (MFI.getStackSize() > 0) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000942 if (EnableStackOVFSanitizer || UseAllocframe)
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +0000943 return true;
944 }
945
946 if (MFI.hasCalls() ||
947 MF.getInfo<HexagonMachineFunctionInfo>()->hasClobberLR())
948 return true;
949
950 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000951}
952
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000953enum SpillKind {
954 SK_ToMem,
955 SK_FromMem,
956 SK_FromMemTailcall
957};
958
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000959static const char *getSpillFunctionFor(unsigned MaxReg, SpillKind SpillType,
960 bool Stkchk = false) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000961 const char * V4SpillToMemoryFunctions[] = {
962 "__save_r16_through_r17",
963 "__save_r16_through_r19",
964 "__save_r16_through_r21",
965 "__save_r16_through_r23",
966 "__save_r16_through_r25",
967 "__save_r16_through_r27" };
968
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000969 const char * V4SpillToMemoryStkchkFunctions[] = {
970 "__save_r16_through_r17_stkchk",
971 "__save_r16_through_r19_stkchk",
972 "__save_r16_through_r21_stkchk",
973 "__save_r16_through_r23_stkchk",
974 "__save_r16_through_r25_stkchk",
975 "__save_r16_through_r27_stkchk" };
976
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000977 const char * V4SpillFromMemoryFunctions[] = {
978 "__restore_r16_through_r17_and_deallocframe",
979 "__restore_r16_through_r19_and_deallocframe",
980 "__restore_r16_through_r21_and_deallocframe",
981 "__restore_r16_through_r23_and_deallocframe",
982 "__restore_r16_through_r25_and_deallocframe",
983 "__restore_r16_through_r27_and_deallocframe" };
984
985 const char * V4SpillFromMemoryTailcallFunctions[] = {
986 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
987 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
988 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
989 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
990 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
991 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
992 };
993
994 const char **SpillFunc = nullptr;
995
996 switch(SpillType) {
997 case SK_ToMem:
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +0000998 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
999 : V4SpillToMemoryFunctions;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001000 break;
1001 case SK_FromMem:
1002 SpillFunc = V4SpillFromMemoryFunctions;
1003 break;
1004 case SK_FromMemTailcall:
1005 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1006 break;
1007 }
1008 assert(SpillFunc && "Unknown spill kind");
1009
1010 // Spill all callee-saved registers up to the highest register used.
1011 switch (MaxReg) {
1012 case Hexagon::R17:
1013 return SpillFunc[0];
1014 case Hexagon::R19:
1015 return SpillFunc[1];
1016 case Hexagon::R21:
1017 return SpillFunc[2];
1018 case Hexagon::R23:
1019 return SpillFunc[3];
1020 case Hexagon::R25:
1021 return SpillFunc[4];
1022 case Hexagon::R27:
1023 return SpillFunc[5];
1024 default:
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001025 llvm_unreachable("Unhandled maximum callee save register");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001026 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001027 return nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001028}
1029
James Y Knight5567baf2015-08-15 02:32:35 +00001030int HexagonFrameLowering::getFrameIndexReference(const MachineFunction &MF,
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001031 int FI, unsigned &FrameReg) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001032 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001033 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001034
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001035 int Offset = MFI.getObjectOffset(FI);
1036 bool HasAlloca = MFI.hasVarSizedObjects();
1037 bool HasExtraAlign = HRI.needsStackRealignment(MF);
1038 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOpt::None;
James Y Knight5567baf2015-08-15 02:32:35 +00001039
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001040 unsigned SP = HRI.getStackRegister(), FP = HRI.getFrameRegister();
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001041 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1042 unsigned AP = HMFI.getStackAlignBasePhysReg();
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001043 unsigned FrameSize = MFI.getStackSize();
1044
1045 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1046 // Use FP at -O0, except when there are objects with extra alignment.
1047 // That additional alignment requirement may cause a pad to be inserted,
1048 // which will make it impossible to use FP to access objects located
1049 // past the pad.
1050 if (NoOpt && !HasExtraAlign)
1051 UseFP = true;
1052 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1053 // Fixed and preallocated objects will be located before any padding
1054 // so FP must be used to access them.
1055 UseFP |= (HasAlloca || HasExtraAlign);
1056 } else {
1057 if (HasAlloca) {
1058 if (HasExtraAlign)
1059 UseAP = true;
1060 else
1061 UseFP = true;
1062 }
1063 }
1064
1065 // If FP was picked, then there had better be FP.
1066 bool HasFP = hasFP(MF);
1067 assert((HasFP || !UseFP) && "This function must have frame pointer");
1068
1069 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1070 // FP/LR. If the base register is used to access an object across these
1071 // 8 bytes, then the offset will need to be adjusted by 8.
1072 //
1073 // After allocframe:
1074 // HexagonISelLowering adds 8 to ---+
1075 // the offsets of all stack-based |
1076 // arguments (*) |
1077 // |
1078 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1079 // ------------------------+-----+------------------------> increasing
1080 // <local objects> |FP/LR| <input arguments> addresses
1081 // -----------------+------+-----+------------------------>
1082 // | |
1083 // SP/AP point --+ +-- FP points here (**)
1084 // somewhere on
1085 // this side of FP/LR
1086 //
1087 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1088 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1089
1090 // The lowering assumes that FP/LR is present, and so the offsets of
1091 // the formal arguments start at 8. If FP/LR is not there we need to
1092 // reduce the offset by 8.
1093 if (Offset > 0 && !HasFP)
1094 Offset -= 8;
1095
1096 if (UseFP)
1097 FrameReg = FP;
1098 else if (UseAP)
1099 FrameReg = AP;
1100 else
1101 FrameReg = SP;
1102
1103 // Calculate the actual offset in the instruction. If there is no FP
1104 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1105 // there will be no SP -= FrameSize), so the frame size should not be
1106 // added to the calculated offset.
1107 int RealOffset = Offset;
1108 if (!UseFP && !UseAP && HasFP)
1109 RealOffset = FrameSize+Offset;
1110 return RealOffset;
Jakob Stoklund Olesen0b97dbc2012-05-30 22:40:03 +00001111}
1112
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001113bool HexagonFrameLowering::insertCSRSpillsInBlock(MachineBasicBlock &MBB,
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001114 const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1115 bool &PrologueStubs) const {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001116 if (CSI.empty())
1117 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001118
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001119 MachineBasicBlock::iterator MI = MBB.begin();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001120 PrologueStubs = false;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001121 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001122 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1123 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001124
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001125 if (useSpillFunction(MF, CSI)) {
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001126 PrologueStubs = true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001127 unsigned MaxReg = getMaxCalleeSavedReg(CSI, HRI);
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001128 bool StkOvrFlowEnabled = EnableStackOVFSanitizer;
1129 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1130 StkOvrFlowEnabled);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001131 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001132 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001133 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001134
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001135 // Call spill function.
1136 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001137 unsigned SpillOpc;
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001138 if (StkOvrFlowEnabled) {
1139 if (LongCalls)
1140 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1141 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1142 else
1143 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1144 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1145 } else {
1146 if (LongCalls)
1147 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1148 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1149 else
1150 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1151 : Hexagon::SAVE_REGISTERS_CALL_V4;
1152 }
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001153
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001154 MachineInstr *SaveRegsCall =
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001155 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001156 .addExternalSymbol(SpillFun);
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001157
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001158 // Add callee-saved registers as use.
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001159 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001160 // Add live in registers.
1161 for (unsigned I = 0; I < CSI.size(); ++I)
1162 MBB.addLiveIn(CSI[I].getReg());
1163 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001164 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001165
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001166 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001167 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001168 // Add live in registers. We treat eh_return callee saved register r0 - r3
1169 // specially. They are not really callee saved registers as they are not
1170 // supposed to be killed.
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001171 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1172 int FI = CSI[i].getFrameIdx();
1173 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001174 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, &HRI);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001175 if (IsKill)
1176 MBB.addLiveIn(Reg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001177 }
1178 return true;
1179}
1180
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001181bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1182 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1183 if (CSI.empty())
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001184 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001185
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001186 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
1187 MachineFunction &MF = *MBB.getParent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001188 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1189 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001190
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001191 if (useRestoreFunction(MF, CSI)) {
1192 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1193 unsigned MaxR = getMaxCalleeSavedReg(CSI, HRI);
1194 SpillKind Kind = HasTC ? SK_FromMemTailcall : SK_FromMem;
1195 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
Krzysztof Parzyszek181fdbd2016-03-24 19:18:48 +00001196 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
Rafael Espindolab1556c42016-06-28 20:13:36 +00001197 bool IsPIC = HTM.isPositionIndependent();
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001198 bool LongCalls = HST.useLongCalls() || EnableSaveRestoreLong;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001199
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001200 // Call spill function.
1201 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1202 : MBB.getLastNonDebugInstr()->getDebugLoc();
1203 MachineInstr *DeallocCall = nullptr;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001204
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001205 if (HasTC) {
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001206 unsigned RetOpc;
1207 if (LongCalls)
1208 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1209 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1210 else
1211 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1212 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1213 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001214 .addExternalSymbol(RestoreFn);
1215 } else {
1216 // The block has a return.
1217 MachineBasicBlock::iterator It = MBB.getFirstTerminator();
1218 assert(It->isReturn() && std::next(It) == MBB.end());
Krzysztof Parzyszek080bebd2016-07-25 14:42:11 +00001219 unsigned RetOpc;
1220 if (LongCalls)
1221 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1222 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1223 else
1224 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1225 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1226 DeallocCall = BuildMI(MBB, It, DL, HII.get(RetOpc))
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001227 .addExternalSymbol(RestoreFn);
1228 // Transfer the function live-out registers.
Duncan P. N. Exon Smithfd8cc232016-02-27 20:01:33 +00001229 DeallocCall->copyImplicitOps(MF, *It);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001230 }
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001231 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001232 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001233 }
1234
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001235 for (unsigned i = 0; i < CSI.size(); ++i) {
1236 unsigned Reg = CSI[i].getReg();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001237 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1238 int FI = CSI[i].getFrameIdx();
Krzysztof Parzyszekdb867702015-10-19 17:46:01 +00001239 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, &HRI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001240 }
Krzysztof Parzyszekc9d4caa2016-03-24 20:20:07 +00001241
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001242 return true;
1243}
1244
Hans Wennborge1a2e902016-03-31 18:33:38 +00001245MachineBasicBlock::iterator HexagonFrameLowering::eliminateCallFramePseudoInstr(
1246 MachineFunction &MF, MachineBasicBlock &MBB,
1247 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00001248 MachineInstr &MI = *I;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001249 unsigned Opc = MI.getOpcode();
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001250 (void)Opc; // Silence compiler warning.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001251 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1252 "Cannot handle this call frame pseudo instruction");
Hans Wennborge1a2e902016-03-31 18:33:38 +00001253 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00001254}
1255
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001256void HexagonFrameLowering::processFunctionBeforeFrameFinalized(
1257 MachineFunction &MF, RegScavenger *RS) const {
1258 // If this function has uses aligned stack and also has variable sized stack
1259 // objects, then we need to map all spill slots to fixed positions, so that
1260 // they can be accessed through FP. Otherwise they would have to be accessed
1261 // via AP, which may not be available at the particular place in the program.
Matthias Braun941a7052016-07-28 18:40:00 +00001262 MachineFrameInfo &MFI = MF.getFrameInfo();
1263 bool HasAlloca = MFI.hasVarSizedObjects();
1264 bool NeedsAlign = (MFI.getMaxAlignment() > getStackAlignment());
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001265
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00001266 if (!HasAlloca || !NeedsAlign)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001267 return;
1268
Matthias Braun941a7052016-07-28 18:40:00 +00001269 unsigned LFS = MFI.getLocalFrameSize();
1270 for (int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1271 if (!MFI.isSpillSlotObjectIndex(i) || MFI.isDeadObjectIndex(i))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001272 continue;
Matthias Braun941a7052016-07-28 18:40:00 +00001273 unsigned S = MFI.getObjectSize(i);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001274 // Reduce the alignment to at most 8. This will require unaligned vector
1275 // stores if they happen here.
Matthias Braun941a7052016-07-28 18:40:00 +00001276 unsigned A = std::max(MFI.getObjectAlignment(i), 8U);
1277 MFI.setObjectAlignment(i, 8);
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001278 LFS = alignTo(LFS+S, A);
Matthias Braun941a7052016-07-28 18:40:00 +00001279 MFI.mapLocalFrameObject(i, -LFS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001280 }
1281
Matthias Braun941a7052016-07-28 18:40:00 +00001282 MFI.setLocalFrameSize(LFS);
1283 unsigned A = MFI.getLocalFrameMaxAlign();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001284 assert(A <= 8 && "Unexpected local frame alignment");
1285 if (A == 0)
Matthias Braun941a7052016-07-28 18:40:00 +00001286 MFI.setLocalFrameMaxAlign(8);
1287 MFI.setUseLocalStackAllocationBlock(true);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001288
1289 // Set the physical aligned-stack base address register.
1290 unsigned AP = 0;
1291 if (const MachineInstr *AI = getAlignaInstr(MF))
1292 AP = AI->getOperand(0).getReg();
1293 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1294 HMFI.setStackAlignBasePhysReg(AP);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001295}
1296
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001297/// Returns true if there are no caller-saved registers available in class RC.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001298static bool needToReserveScavengingSpillSlots(MachineFunction &MF,
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001299 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001300 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001301
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001302 auto IsUsed = [&HRI,&MRI] (unsigned Reg) -> bool {
1303 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1304 if (MRI.isPhysRegUsed(*AI))
1305 return true;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001306 return false;
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001307 };
1308
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001309 // Check for an unused caller-saved register. Callee-saved registers
1310 // have become pristine by now.
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001311 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
Krzysztof Parzyszek6514a882016-03-21 19:57:08 +00001312 if (!IsUsed(*P))
1313 return false;
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001314
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001315 // All caller-saved registers are used.
1316 return true;
1317}
1318
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001319#ifndef NDEBUG
Krzysztof Parzyszeke5689672015-04-23 20:26:21 +00001320static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI) {
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001321 dbgs() << '{';
1322 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1323 unsigned R = x;
1324 dbgs() << ' ' << PrintReg(R, &TRI);
1325 }
1326 dbgs() << " }";
1327}
1328#endif
1329
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001330bool HexagonFrameLowering::assignCalleeSavedSpillSlots(MachineFunction &MF,
1331 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
Reid Kleckner40d72302016-10-20 00:22:23 +00001332 DEBUG(dbgs() << __func__ << " on "
Krzysztof Parzyszeked75e7a2015-04-23 20:57:39 +00001333 << MF.getFunction()->getName() << '\n');
Matthias Braun941a7052016-07-28 18:40:00 +00001334 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001335 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001336
1337 // Generate a set of unique, callee-saved registers (SRegs), where each
1338 // register in the set is maximal in terms of sub-/super-register relation,
1339 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
1340
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001341 // (1) For each callee-saved register, add that register and all of its
1342 // sub-registers to SRegs.
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001343 DEBUG(dbgs() << "Initial CS registers: {");
1344 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1345 unsigned R = CSI[i].getReg();
1346 DEBUG(dbgs() << ' ' << PrintReg(R, TRI));
1347 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1348 SRegs[*SR] = true;
1349 }
1350 DEBUG(dbgs() << " }\n");
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001351 DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001352
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001353 // (2) For each reserved register, remove that register and all of its
1354 // sub- and super-registers from SRegs.
1355 BitVector Reserved = TRI->getReservedRegs(MF);
1356 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
1357 unsigned R = x;
1358 for (MCSuperRegIterator SR(R, TRI, true); SR.isValid(); ++SR)
1359 SRegs[*SR] = false;
1360 }
1361 DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI); dbgs() << "\n");
1362 DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
1363
1364 // (3) Collect all registers that have at least one sub-register in SRegs,
1365 // and also have no sub-registers that are reserved. These will be the can-
1366 // didates for saving as a whole instead of their individual sub-registers.
1367 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
1368 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001369 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1370 unsigned R = x;
1371 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR)
1372 TmpSup[*SR] = true;
1373 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001374 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
1375 unsigned R = x;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001376 for (MCSubRegIterator SR(R, TRI, true); SR.isValid(); ++SR) {
1377 if (!Reserved[*SR])
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001378 continue;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001379 TmpSup[R] = false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001380 break;
1381 }
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001382 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001383 DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001384
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001385 // (4) Include all super-registers found in (3) into SRegs.
1386 SRegs |= TmpSup;
1387 DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001388
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001389 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001390 // remove R from SRegs.
1391 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1392 unsigned R = x;
1393 for (MCSuperRegIterator SR(R, TRI); SR.isValid(); ++SR) {
1394 if (!SRegs[*SR])
1395 continue;
1396 SRegs[R] = false;
1397 break;
1398 }
1399 }
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00001400 DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI); dbgs() << "\n");
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001401
1402 // Now, for each register that has a fixed stack slot, create the stack
1403 // object for it.
1404 CSI.clear();
1405
1406 typedef TargetFrameLowering::SpillSlot SpillSlot;
1407 unsigned NumFixed;
1408 int MinOffset = 0; // CS offsets are negative.
1409 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
1410 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
1411 if (!SRegs[S->Reg])
1412 continue;
1413 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
Matthias Braun941a7052016-07-28 18:40:00 +00001414 int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), S->Offset);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001415 MinOffset = std::min(MinOffset, S->Offset);
1416 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
1417 SRegs[S->Reg] = false;
1418 }
1419
1420 // There can be some registers that don't have fixed slots. For example,
1421 // we need to store R0-R3 in functions with exception handling. For each
1422 // such register, create a non-fixed stack object.
1423 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1424 unsigned R = x;
1425 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
1426 int Off = MinOffset - RC->getSize();
1427 unsigned Align = std::min(RC->getAlignment(), getStackAlignment());
1428 assert(isPowerOf2_32(Align));
1429 Off &= -Align;
Matthias Braun941a7052016-07-28 18:40:00 +00001430 int FI = MFI.CreateFixedSpillStackObject(RC->getSize(), Off);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001431 MinOffset = std::min(MinOffset, Off);
1432 CSI.push_back(CalleeSavedInfo(R, FI));
1433 SRegs[R] = false;
1434 }
1435
1436 DEBUG({
1437 dbgs() << "CS information: {";
1438 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
1439 int FI = CSI[i].getFrameIdx();
Matthias Braun941a7052016-07-28 18:40:00 +00001440 int Off = MFI.getObjectOffset(FI);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001441 dbgs() << ' ' << PrintReg(CSI[i].getReg(), TRI) << ":fi#" << FI << ":sp";
1442 if (Off >= 0)
1443 dbgs() << '+';
1444 dbgs() << Off;
1445 }
1446 dbgs() << " }\n";
1447 });
1448
1449#ifndef NDEBUG
1450 // Verify that all registers were handled.
1451 bool MissedReg = false;
1452 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
1453 unsigned R = x;
1454 dbgs() << PrintReg(R, TRI) << ' ';
1455 MissedReg = true;
1456 }
1457 if (MissedReg)
1458 llvm_unreachable("...there are unhandled callee-saved registers!");
1459#endif
1460
1461 return true;
1462}
1463
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001464bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
1465 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1466 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1467 MachineInstr *MI = &*It;
1468 DebugLoc DL = MI->getDebugLoc();
1469 unsigned DstR = MI->getOperand(0).getReg();
1470 unsigned SrcR = MI->getOperand(1).getReg();
1471 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
1472 !Hexagon::ModRegsRegClass.contains(SrcR))
1473 return false;
1474
1475 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1476 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR)
1477 .addOperand(MI->getOperand(1));
1478 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
1479 .addReg(TmpR, RegState::Kill);
1480
1481 NewRegs.push_back(TmpR);
1482 B.erase(It);
1483 return true;
1484}
1485
1486bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
1487 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1488 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1489 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001490 if (!MI->getOperand(0).isFI())
1491 return false;
1492
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001493 DebugLoc DL = MI->getDebugLoc();
1494 unsigned Opc = MI->getOpcode();
1495 unsigned SrcR = MI->getOperand(2).getReg();
1496 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001497 int FI = MI->getOperand(0).getIndex();
1498
1499 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
1500 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
1501 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1502 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
1503 : Hexagon::A2_tfrcrr;
1504 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
1505 .addReg(SrcR, getKillRegState(IsKill));
1506
1507 // S2_storeri_io FI, 0, TmpR
1508 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
1509 .addFrameIndex(FI)
1510 .addImm(0)
1511 .addReg(TmpR, RegState::Kill)
1512 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1513
1514 NewRegs.push_back(TmpR);
1515 B.erase(It);
1516 return true;
1517}
1518
1519bool HexagonFrameLowering::expandLoadInt(MachineBasicBlock &B,
1520 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1521 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1522 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001523 if (!MI->getOperand(1).isFI())
1524 return false;
1525
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001526 DebugLoc DL = MI->getDebugLoc();
1527 unsigned Opc = MI->getOpcode();
1528 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001529 int FI = MI->getOperand(1).getIndex();
1530
1531 // TmpR = L2_loadri_io FI, 0
1532 unsigned TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1533 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
1534 .addFrameIndex(FI)
1535 .addImm(0)
1536 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1537
1538 // DstR = C2_tfrrp TmpR if DstR is a predicate register
1539 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
1540 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
1541 : Hexagon::A2_tfrrcr;
1542 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
1543 .addReg(TmpR, RegState::Kill);
1544
1545 NewRegs.push_back(TmpR);
1546 B.erase(It);
1547 return true;
1548}
1549
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001550bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
1551 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1552 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1553 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1554 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001555 if (!MI->getOperand(0).isFI())
1556 return false;
1557
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001558 DebugLoc DL = MI->getDebugLoc();
1559 unsigned SrcR = MI->getOperand(2).getReg();
1560 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001561 int FI = MI->getOperand(0).getIndex();
1562
1563 bool Is128B = HST.useHVXDblOps();
1564 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1565 : &Hexagon::VectorRegs128BRegClass;
1566
1567 // Insert transfer to general vector register.
1568 // TmpR0 = A2_tfrsi 0x01010101
1569 // TmpR1 = V6_vandqrt Qx, TmpR0
1570 // store FI, 0, TmpR1
1571 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1572 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1573
1574 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1575 .addImm(0x01010101);
1576
1577 unsigned VandOpc = !Is128B ? Hexagon::V6_vandqrt : Hexagon::V6_vandqrt_128B;
1578 BuildMI(B, It, DL, HII.get(VandOpc), TmpR1)
1579 .addReg(SrcR, getKillRegState(IsKill))
1580 .addReg(TmpR0, RegState::Kill);
1581
1582 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1583 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, HRI);
1584 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
1585
1586 NewRegs.push_back(TmpR0);
1587 NewRegs.push_back(TmpR1);
1588 B.erase(It);
1589 return true;
1590}
1591
1592bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
1593 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1594 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1595 auto &HST = B.getParent()->getSubtarget<HexagonSubtarget>();
1596 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001597 if (!MI->getOperand(1).isFI())
1598 return false;
1599
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001600 DebugLoc DL = MI->getDebugLoc();
1601 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001602 int FI = MI->getOperand(1).getIndex();
1603
1604 bool Is128B = HST.useHVXDblOps();
1605 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1606 : &Hexagon::VectorRegs128BRegClass;
1607
1608 // TmpR0 = A2_tfrsi 0x01010101
1609 // TmpR1 = load FI, 0
1610 // DstR = V6_vandvrt TmpR1, TmpR0
1611 unsigned TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
1612 unsigned TmpR1 = MRI.createVirtualRegister(RC);
1613
1614 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
1615 .addImm(0x01010101);
1616 auto *HRI = B.getParent()->getSubtarget<HexagonSubtarget>().getRegisterInfo();
1617 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, HRI);
1618 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
1619
1620 unsigned VandOpc = !Is128B ? Hexagon::V6_vandvrt : Hexagon::V6_vandvrt_128B;
1621 BuildMI(B, It, DL, HII.get(VandOpc), DstR)
1622 .addReg(TmpR1, RegState::Kill)
1623 .addReg(TmpR0, RegState::Kill);
1624
1625 NewRegs.push_back(TmpR0);
1626 NewRegs.push_back(TmpR1);
1627 B.erase(It);
1628 return true;
1629}
1630
1631bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
1632 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1633 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1634 MachineFunction &MF = *B.getParent();
1635 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001636 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001637 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1638 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001639 if (!MI->getOperand(0).isFI())
1640 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001641
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001642 // It is possible that the double vector being stored is only partially
1643 // defined. From the point of view of the liveness tracking, it is ok to
1644 // store it as a whole, but if we break it up we may end up storing a
1645 // register that is entirely undefined.
1646 LivePhysRegs LPR(&HRI);
1647 LPR.addLiveIns(B);
1648 SmallVector<std::pair<unsigned, const MachineOperand*>,2> Clobbers;
1649 for (auto R = B.begin(); R != It; ++R)
1650 LPR.stepForward(*R, Clobbers);
1651
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001652 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001653 unsigned SrcR = MI->getOperand(2).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001654 unsigned SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
1655 unsigned SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001656 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001657 int FI = MI->getOperand(0).getIndex();
1658
1659 bool Is128B = HST.useHVXDblOps();
1660 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1661 : &Hexagon::VectorRegs128BRegClass;
1662 unsigned Size = RC->getSize();
1663 unsigned NeedAlign = RC->getAlignment();
1664 unsigned HasAlign = MFI.getObjectAlignment(FI);
1665 unsigned StoreOpc;
1666
1667 // Store low part.
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001668 if (LPR.contains(SrcLo)) {
1669 if (NeedAlign <= HasAlign)
1670 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1671 else
1672 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001673
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001674 BuildMI(B, It, DL, HII.get(StoreOpc))
1675 .addFrameIndex(FI)
1676 .addImm(0)
1677 .addReg(SrcLo, getKillRegState(IsKill))
1678 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1679 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001680
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001681 // Store high part.
1682 if (LPR.contains(SrcHi)) {
1683 if (NeedAlign <= MinAlign(HasAlign, Size))
1684 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1685 else
1686 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001687
Krzysztof Parzyszekb71085b2016-10-21 16:38:29 +00001688 BuildMI(B, It, DL, HII.get(StoreOpc))
1689 .addFrameIndex(FI)
1690 .addImm(Size)
1691 .addReg(SrcHi, getKillRegState(IsKill))
1692 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1693 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001694
1695 B.erase(It);
1696 return true;
1697}
1698
1699bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
1700 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1701 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1702 MachineFunction &MF = *B.getParent();
1703 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001704 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001705 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1706 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001707 if (!MI->getOperand(1).isFI())
1708 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001709
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001710 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001711 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001712 unsigned DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
1713 unsigned DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001714 int FI = MI->getOperand(1).getIndex();
1715
1716 bool Is128B = HST.useHVXDblOps();
1717 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1718 : &Hexagon::VectorRegs128BRegClass;
1719 unsigned Size = RC->getSize();
1720 unsigned NeedAlign = RC->getAlignment();
1721 unsigned HasAlign = MFI.getObjectAlignment(FI);
1722 unsigned LoadOpc;
1723
1724 // Load low part.
1725 if (NeedAlign <= HasAlign)
1726 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1727 else
1728 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1729
1730 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
1731 .addFrameIndex(FI)
1732 .addImm(0)
1733 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1734
1735 // Load high part.
1736 if (NeedAlign <= MinAlign(HasAlign, Size))
1737 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1738 else
1739 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1740
1741 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
1742 .addFrameIndex(FI)
1743 .addImm(Size)
1744 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1745
1746 B.erase(It);
1747 return true;
1748}
1749
1750bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
1751 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1752 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1753 MachineFunction &MF = *B.getParent();
1754 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001755 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001756 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001757 if (!MI->getOperand(0).isFI())
1758 return false;
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001759
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001760 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001761 unsigned SrcR = MI->getOperand(2).getReg();
1762 bool IsKill = MI->getOperand(2).isKill();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001763 int FI = MI->getOperand(0).getIndex();
1764
1765 bool Is128B = HST.useHVXDblOps();
1766 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1767 : &Hexagon::VectorRegs128BRegClass;
1768
1769 unsigned NeedAlign = RC->getAlignment();
1770 unsigned HasAlign = MFI.getObjectAlignment(FI);
1771 unsigned StoreOpc;
1772
1773 if (NeedAlign <= HasAlign)
1774 StoreOpc = !Is128B ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32b_ai_128B;
1775 else
1776 StoreOpc = !Is128B ? Hexagon::V6_vS32Ub_ai : Hexagon::V6_vS32Ub_ai_128B;
1777
1778 BuildMI(B, It, DL, HII.get(StoreOpc))
1779 .addFrameIndex(FI)
1780 .addImm(0)
1781 .addReg(SrcR, getKillRegState(IsKill))
1782 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1783
1784 B.erase(It);
1785 return true;
1786}
1787
1788bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
1789 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
1790 const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const {
1791 MachineFunction &MF = *B.getParent();
1792 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Matthias Braun941a7052016-07-28 18:40:00 +00001793 auto &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001794 MachineInstr *MI = &*It;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001795 if (!MI->getOperand(1).isFI())
1796 return false;
1797
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001798 DebugLoc DL = MI->getDebugLoc();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001799 unsigned DstR = MI->getOperand(0).getReg();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001800 int FI = MI->getOperand(1).getIndex();
1801
1802 bool Is128B = HST.useHVXDblOps();
1803 auto *RC = !Is128B ? &Hexagon::VectorRegsRegClass
1804 : &Hexagon::VectorRegs128BRegClass;
1805
1806 unsigned NeedAlign = RC->getAlignment();
1807 unsigned HasAlign = MFI.getObjectAlignment(FI);
1808 unsigned LoadOpc;
1809
1810 if (NeedAlign <= HasAlign)
1811 LoadOpc = !Is128B ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32b_ai_128B;
1812 else
1813 LoadOpc = !Is128B ? Hexagon::V6_vL32Ub_ai : Hexagon::V6_vL32Ub_ai_128B;
1814
1815 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
1816 .addFrameIndex(FI)
1817 .addImm(0)
1818 .setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1819
1820 B.erase(It);
1821 return true;
1822}
1823
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001824bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
1825 SmallVectorImpl<unsigned> &NewRegs) const {
1826 auto &HST = MF.getSubtarget<HexagonSubtarget>();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001827 auto &HII = *HST.getInstrInfo();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001828 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001829 bool Changed = false;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001830
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001831 for (auto &B : MF) {
1832 // Traverse the basic block.
1833 MachineBasicBlock::iterator NextI;
1834 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
1835 MachineInstr *MI = &*I;
1836 NextI = std::next(I);
1837 unsigned Opc = MI->getOpcode();
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001838
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001839 switch (Opc) {
1840 case TargetOpcode::COPY:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001841 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001842 break;
1843 case Hexagon::STriw_pred:
1844 case Hexagon::STriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001845 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001846 break;
1847 case Hexagon::LDriw_pred:
1848 case Hexagon::LDriw_mod:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001849 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001850 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001851 case Hexagon::PS_vstorerq_ai:
1852 case Hexagon::PS_vstorerq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001853 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001854 break;
Krzysztof Parzyszek17aa4132016-08-16 15:43:54 +00001855 case Hexagon::PS_vloadrq_ai:
1856 case Hexagon::PS_vloadrq_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001857 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001858 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001859 case Hexagon::PS_vloadrw_ai:
1860 case Hexagon::PS_vloadrwu_ai:
1861 case Hexagon::PS_vloadrw_ai_128B:
1862 case Hexagon::PS_vloadrwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001863 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001864 break;
Krzysztof Parzyszekf2859632016-08-12 21:05:05 +00001865 case Hexagon::PS_vstorerw_ai:
1866 case Hexagon::PS_vstorerwu_ai:
1867 case Hexagon::PS_vstorerw_ai_128B:
1868 case Hexagon::PS_vstorerwu_ai_128B:
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00001869 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001870 break;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001871 }
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001872 }
1873 }
1874
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001875 return Changed;
Krzysztof Parzyszek7b413c62016-01-22 19:15:58 +00001876}
1877
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001878void HexagonFrameLowering::determineCalleeSaves(MachineFunction &MF,
1879 BitVector &SavedRegs,
1880 RegScavenger *RS) const {
1881 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1882 auto &HRI = *HST.getRegisterInfo();
1883
1884 SavedRegs.resize(HRI.getNumRegs());
1885
1886 // If we have a function containing __builtin_eh_return we want to spill and
1887 // restore all callee saved registers. Pretend that they are used.
1888 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
1889 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
1890 SavedRegs.set(*R);
1891
1892 // Replace predicate register pseudo spill code.
1893 SmallVector<unsigned,8> NewRegs;
1894 expandSpillMacros(MF, NewRegs);
Krzysztof Parzyszeka34901a2016-03-28 14:42:03 +00001895 if (OptimizeSpillSlots && !isOptNone(MF))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001896 optimizeSpillSlots(MF, NewRegs);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001897
1898 // We need to reserve a a spill slot if scavenging could potentially require
1899 // spilling a scavenged register.
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00001900 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +00001901 MachineFrameInfo &MFI = MF.getFrameInfo();
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001902 MachineRegisterInfo &MRI = MF.getRegInfo();
1903 SetVector<const TargetRegisterClass*> SpillRCs;
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001904 // Reserve an int register in any case, because it could be used to hold
1905 // the stack offset in case it does not fit into a spill instruction.
1906 SpillRCs.insert(&Hexagon::IntRegsRegClass);
1907
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001908 for (unsigned VR : NewRegs)
1909 SpillRCs.insert(MRI.getRegClass(VR));
1910
Krzysztof Parzyszeka5bd29542016-05-16 18:02:28 +00001911 for (auto *RC : SpillRCs) {
1912 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
1913 continue;
1914 unsigned Num = RC == &Hexagon::IntRegsRegClass ? NumberScavengerSlots : 1;
1915 unsigned S = RC->getSize(), A = RC->getAlignment();
1916 for (unsigned i = 0; i < Num; i++) {
1917 int NewFI = MFI.CreateSpillStackObject(S, A);
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001918 RS->addScavengingFrameIndex(NewFI);
1919 }
1920 }
Krzysztof Parzyszek996ad1f2016-02-12 18:19:53 +00001921 }
1922
1923 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1924}
1925
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001926unsigned HexagonFrameLowering::findPhysReg(MachineFunction &MF,
1927 HexagonBlockRanges::IndexRange &FIR,
1928 HexagonBlockRanges::InstrIndexMap &IndexMap,
1929 HexagonBlockRanges::RegToRangeMap &DeadMap,
1930 const TargetRegisterClass *RC) const {
1931 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1932 auto &MRI = MF.getRegInfo();
1933
1934 auto isDead = [&FIR,&DeadMap] (unsigned Reg) -> bool {
1935 auto F = DeadMap.find({Reg,0});
1936 if (F == DeadMap.end())
1937 return false;
1938 for (auto &DR : F->second)
1939 if (DR.contains(FIR))
1940 return true;
1941 return false;
1942 };
1943
1944 for (unsigned Reg : RC->getRawAllocationOrder(MF)) {
1945 bool Dead = true;
1946 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
1947 if (isDead(R.Reg))
1948 continue;
1949 Dead = false;
1950 break;
1951 }
1952 if (Dead)
1953 return Reg;
1954 }
1955 return 0;
1956}
1957
1958void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
1959 SmallVectorImpl<unsigned> &VRegs) const {
1960 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1961 auto &HII = *HST.getInstrInfo();
1962 auto &HRI = *HST.getRegisterInfo();
1963 auto &MRI = MF.getRegInfo();
1964 HexagonBlockRanges HBR(MF);
1965
1966 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::InstrIndexMap>
1967 BlockIndexMap;
1968 typedef std::map<MachineBasicBlock*,HexagonBlockRanges::RangeList>
1969 BlockRangeMap;
1970 typedef HexagonBlockRanges::IndexType IndexType;
1971
1972 struct SlotInfo {
1973 BlockRangeMap Map;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001974 unsigned Size = 0;
1975 const TargetRegisterClass *RC = nullptr;
NAKAMURA Takumic2cc8702016-02-13 07:29:49 +00001976
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001977 SlotInfo() = default;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001978 };
1979
1980 BlockIndexMap BlockIndexes;
1981 SmallSet<int,4> BadFIs;
1982 std::map<int,SlotInfo> FIRangeMap;
1983
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00001984 // Accumulate register classes: get a common class for a pre-existing
1985 // class HaveRC and a new class NewRC. Return nullptr if a common class
1986 // cannot be found, otherwise return the resulting class. If HaveRC is
1987 // nullptr, assume that it is still unset.
1988 auto getCommonRC = [&HRI] (const TargetRegisterClass *HaveRC,
1989 const TargetRegisterClass *NewRC)
1990 -> const TargetRegisterClass* {
1991 if (HaveRC == nullptr || HaveRC == NewRC)
1992 return NewRC;
1993 // Different classes, both non-null. Pick the more general one.
1994 if (HaveRC->hasSubClassEq(NewRC))
1995 return HaveRC;
1996 if (NewRC->hasSubClassEq(HaveRC))
1997 return NewRC;
1998 return nullptr;
1999 };
2000
2001 // Scan all blocks in the function. Check all occurrences of frame indexes,
2002 // and collect relevant information.
2003 for (auto &B : MF) {
2004 std::map<int,IndexType> LastStore, LastLoad;
Krzysztof Parzyszek280a50e2016-02-13 14:06:01 +00002005 // Emplace appears not to be supported in gcc 4.7.2-4.
2006 //auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
Krzysztof Parzyszekde697d42016-02-17 15:02:07 +00002007 auto P = BlockIndexes.insert(
2008 std::make_pair(&B, HexagonBlockRanges::InstrIndexMap(B)));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002009 auto &IndexMap = P.first->second;
2010 DEBUG(dbgs() << "Index map for BB#" << B.getNumber() << "\n"
2011 << IndexMap << '\n');
2012
2013 for (auto &In : B) {
2014 int LFI, SFI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00002015 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2016 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002017 if (Load && Store) {
2018 // If it's both a load and a store, then we won't handle it.
2019 BadFIs.insert(LFI);
2020 BadFIs.insert(SFI);
2021 continue;
2022 }
2023 // Check for register classes of the register used as the source for
2024 // the store, and the register used as the destination for the load.
2025 // Also, only accept base+imm_offset addressing modes. Other addressing
2026 // modes can have side-effects (post-increments, etc.). For stack
2027 // slots they are very unlikely, so there is not much loss due to
2028 // this restriction.
2029 if (Load || Store) {
2030 int TFI = Load ? LFI : SFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002031 unsigned AM = HII.getAddrMode(In);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002032 SlotInfo &SI = FIRangeMap[TFI];
2033 bool Bad = (AM != HexagonII::BaseImmOffset);
2034 if (!Bad) {
2035 // If the addressing mode is ok, check the register class.
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002036 unsigned OpNum = Load ? 0 : 2;
2037 auto *RC = HII.getRegClass(In.getDesc(), OpNum, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002038 RC = getCommonRC(SI.RC, RC);
2039 if (RC == nullptr)
2040 Bad = true;
2041 else
2042 SI.RC = RC;
2043 }
2044 if (!Bad) {
2045 // Check sizes.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002046 unsigned S = (1U << (HII.getMemAccessSize(In) - 1));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002047 if (SI.Size != 0 && SI.Size != S)
2048 Bad = true;
2049 else
2050 SI.Size = S;
2051 }
Krzysztof Parzyszek5241b8e2016-07-27 20:50:42 +00002052 if (!Bad) {
2053 for (auto *Mo : In.memoperands()) {
2054 if (!Mo->isVolatile())
2055 continue;
2056 Bad = true;
2057 break;
2058 }
2059 }
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002060 if (Bad)
2061 BadFIs.insert(TFI);
2062 }
2063
2064 // Locate uses of frame indices.
2065 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2066 const MachineOperand &Op = In.getOperand(i);
2067 if (!Op.isFI())
2068 continue;
2069 int FI = Op.getIndex();
2070 // Make sure that the following operand is an immediate and that
2071 // it is 0. This is the offset in the stack object.
2072 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2073 In.getOperand(i+1).getImm() != 0)
2074 BadFIs.insert(FI);
2075 if (BadFIs.count(FI))
2076 continue;
2077
2078 IndexType Index = IndexMap.getIndex(&In);
2079 if (Load) {
2080 if (LastStore[FI] == IndexType::None)
2081 LastStore[FI] = IndexType::Entry;
2082 LastLoad[FI] = Index;
2083 } else if (Store) {
2084 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2085 if (LastStore[FI] != IndexType::None)
2086 RL.add(LastStore[FI], LastLoad[FI], false, false);
2087 else if (LastLoad[FI] != IndexType::None)
2088 RL.add(IndexType::Entry, LastLoad[FI], false, false);
2089 LastLoad[FI] = IndexType::None;
2090 LastStore[FI] = Index;
2091 } else {
2092 BadFIs.insert(FI);
2093 }
2094 }
2095 }
2096
2097 for (auto &I : LastLoad) {
2098 IndexType LL = I.second;
2099 if (LL == IndexType::None)
2100 continue;
2101 auto &RL = FIRangeMap[I.first].Map[&B];
2102 IndexType &LS = LastStore[I.first];
2103 if (LS != IndexType::None)
2104 RL.add(LS, LL, false, false);
2105 else
2106 RL.add(IndexType::Entry, LL, false, false);
2107 LS = IndexType::None;
2108 }
2109 for (auto &I : LastStore) {
2110 IndexType LS = I.second;
2111 if (LS == IndexType::None)
2112 continue;
2113 auto &RL = FIRangeMap[I.first].Map[&B];
2114 RL.add(LS, IndexType::None, false, false);
2115 }
2116 }
2117
2118 DEBUG({
2119 for (auto &P : FIRangeMap) {
2120 dbgs() << "fi#" << P.first;
2121 if (BadFIs.count(P.first))
2122 dbgs() << " (bad)";
2123 dbgs() << " RC: ";
2124 if (P.second.RC != nullptr)
2125 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2126 else
2127 dbgs() << "<null>\n";
2128 for (auto &R : P.second.Map)
2129 dbgs() << " BB#" << R.first->getNumber() << " { " << R.second << "}\n";
2130 }
2131 });
2132
2133 // When a slot is loaded from in a block without being stored to in the
2134 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2135 // consider this slot to be live-on-exit from all blocks.
2136 SmallSet<int,4> LoxFIs;
2137
2138 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2139
2140 for (auto &P : FIRangeMap) {
2141 // P = pair(FI, map: BB->RangeList)
2142 if (BadFIs.count(P.first))
2143 continue;
2144 for (auto &B : MF) {
2145 auto F = P.second.Map.find(&B);
2146 // F = pair(BB, RangeList)
2147 if (F == P.second.Map.end() || F->second.empty())
2148 continue;
2149 HexagonBlockRanges::IndexRange &IR = F->second.front();
2150 if (IR.start() == IndexType::Entry)
2151 LoxFIs.insert(P.first);
2152 BlockFIMap[&B].push_back(P.first);
2153 }
2154 }
2155
2156 DEBUG({
2157 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2158 for (auto &P : BlockFIMap) {
2159 auto &FIs = P.second;
2160 if (FIs.empty())
2161 continue;
2162 dbgs() << " BB#" << P.first->getNumber() << ": {";
2163 for (auto I : FIs) {
2164 dbgs() << " fi#" << I;
2165 if (LoxFIs.count(I))
2166 dbgs() << '*';
2167 }
2168 dbgs() << " }\n";
2169 }
2170 });
2171
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002172#ifndef NDEBUG
2173 bool HasOptLimit = SpillOptMax.getPosition();
2174#endif
2175
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002176 // eliminate loads, when all loads eliminated, eliminate all stores.
2177 for (auto &B : MF) {
2178 auto F = BlockIndexes.find(&B);
2179 assert(F != BlockIndexes.end());
2180 HexagonBlockRanges::InstrIndexMap &IM = F->second;
2181 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
2182 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
2183 DEBUG(dbgs() << "BB#" << B.getNumber() << " dead map\n"
2184 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
2185
2186 for (auto FI : BlockFIMap[&B]) {
2187 if (BadFIs.count(FI))
2188 continue;
2189 DEBUG(dbgs() << "Working on fi#" << FI << '\n');
2190 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2191 for (auto &Range : RL) {
2192 DEBUG(dbgs() << "--Examining range:" << RL << '\n');
2193 if (!IndexType::isInstr(Range.start()) ||
2194 !IndexType::isInstr(Range.end()))
2195 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002196 MachineInstr &SI = *IM.getInstr(Range.start());
2197 MachineInstr &EI = *IM.getInstr(Range.end());
2198 assert(SI.mayStore() && "Unexpected start instruction");
2199 assert(EI.mayLoad() && "Unexpected end instruction");
2200 MachineOperand &SrcOp = SI.getOperand(2);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002201
2202 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
2203 SrcOp.getSubReg() };
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002204 auto *RC = HII.getRegClass(SI.getDesc(), 2, &HRI, MF);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002205 // The this-> is needed to unconfuse MSVC.
2206 unsigned FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
2207 DEBUG(dbgs() << "Replacement reg:" << PrintReg(FoundR, &HRI) << '\n');
2208 if (FoundR == 0)
2209 continue;
Krzysztof Parzyszekdc421642016-07-27 20:58:43 +00002210#ifndef NDEBUG
2211 if (HasOptLimit) {
2212 if (SpillOptCount >= SpillOptMax)
2213 return;
2214 SpillOptCount++;
2215 }
2216#endif
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002217
2218 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002219 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002220 MachineInstr *CopyIn = nullptr;
2221 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002222 const DebugLoc &DL = SI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002223 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
2224 .addOperand(SrcOp);
2225 }
2226
2227 ++StartIt;
2228 // Check if this is a last store and the FI is live-on-exit.
2229 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
2230 // Update store's source register.
2231 if (unsigned SR = SrcOp.getSubReg())
2232 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
2233 else
2234 SrcOp.setReg(FoundR);
2235 SrcOp.setSubReg(0);
2236 // We are keeping this register live.
2237 SrcOp.setIsKill(false);
2238 } else {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002239 B.erase(&SI);
2240 IM.replaceInstr(&SI, CopyIn);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002241 }
2242
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002243 auto EndIt = std::next(EI.getIterator());
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002244 for (auto It = StartIt; It != EndIt; It = NextIt) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002245 MachineInstr &MI = *It;
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002246 NextIt = std::next(It);
2247 int TFI;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002248 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002249 continue;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002250 unsigned DstR = MI.getOperand(0).getReg();
2251 assert(MI.getOperand(0).getSubReg() == 0);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002252 MachineInstr *CopyOut = nullptr;
2253 if (DstR != FoundR) {
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002254 DebugLoc DL = MI.getDebugLoc();
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002255 unsigned MemSize = (1U << (HII.getMemAccessSize(MI) - 1));
2256 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
2257 unsigned CopyOpc = TargetOpcode::COPY;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002258 if (HII.isSignExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002259 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002260 else if (HII.isZeroExtendingLoad(MI))
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002261 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
2262 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002263 .addReg(FoundR, getKillRegState(&MI == &EI));
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002264 }
Krzysztof Parzyszekf0b34a52016-07-29 21:49:42 +00002265 IM.replaceInstr(&MI, CopyOut);
Krzysztof Parzyszek7793ddb2016-02-12 22:53:35 +00002266 B.erase(It);
2267 }
2268
2269 // Update the dead map.
2270 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
2271 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
2272 DM[RR].subtract(Range);
2273 } // for Range in range list
2274 }
2275 }
2276}
2277
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002278void HexagonFrameLowering::expandAlloca(MachineInstr *AI,
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002279 const HexagonInstrInfo &HII, unsigned SP, unsigned CF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002280 MachineBasicBlock &MB = *AI->getParent();
2281 DebugLoc DL = AI->getDebugLoc();
2282 unsigned A = AI->getOperand(2).getImm();
2283
2284 // Have
2285 // Rd = alloca Rs, #A
2286 //
2287 // If Rs and Rd are different registers, use this sequence:
2288 // Rd = sub(r29, Rs)
2289 // r29 = sub(r29, Rs)
2290 // Rd = and(Rd, #-A) ; if necessary
2291 // r29 = and(r29, #-A) ; if necessary
2292 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2293 // otherwise, do
2294 // Rd = sub(r29, Rs)
2295 // Rd = and(Rd, #-A) ; if necessary
2296 // r29 = Rd
2297 // Rd = add(Rd, #CF) ; CF size aligned to at most A
2298
2299 MachineOperand &RdOp = AI->getOperand(0);
2300 MachineOperand &RsOp = AI->getOperand(1);
2301 unsigned Rd = RdOp.getReg(), Rs = RsOp.getReg();
2302
2303 // Rd = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002304 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002305 .addReg(SP)
2306 .addReg(Rs);
2307 if (Rs != Rd) {
2308 // r29 = sub(r29, Rs)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002309 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002310 .addReg(SP)
2311 .addReg(Rs);
2312 }
2313 if (A > 8) {
2314 // Rd = and(Rd, #-A)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002315 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002316 .addReg(Rd)
2317 .addImm(-int64_t(A));
2318 if (Rs != Rd)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002319 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002320 .addReg(SP)
2321 .addImm(-int64_t(A));
2322 }
2323 if (Rs == Rd) {
2324 // r29 = Rd
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002325 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002326 .addReg(Rd);
2327 }
2328 if (CF > 0) {
2329 // Rd = add(Rd, #CF)
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002330 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002331 .addReg(Rd)
2332 .addImm(CF);
2333 }
2334}
2335
2336bool HexagonFrameLowering::needsAligna(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +00002337 const MachineFrameInfo &MFI = MF.getFrameInfo();
2338 if (!MFI.hasVarSizedObjects())
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002339 return false;
Matthias Braun941a7052016-07-28 18:40:00 +00002340 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002341 if (MaxA <= getStackAlignment())
2342 return false;
2343 return true;
2344}
2345
Krzysztof Parzyszek23920ec2015-10-19 18:30:27 +00002346const MachineInstr *HexagonFrameLowering::getAlignaInstr(
2347 const MachineFunction &MF) const {
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002348 for (auto &B : MF)
2349 for (auto &I : B)
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +00002350 if (I.getOpcode() == Hexagon::PS_aligna)
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00002351 return &I;
2352 return nullptr;
2353}
2354
Krzysztof Parzyszeke8e754d2016-04-25 17:49:44 +00002355/// Adds all callee-saved registers as implicit uses or defs to the
2356/// instruction.
2357void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
2358 const CSIVect &CSI, bool IsDef, bool IsKill) const {
2359 // Add the callee-saved registers as implicit uses.
2360 for (auto &R : CSI)
2361 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
2362}
2363
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002364/// Determine whether the callee-saved register saves and restores should
2365/// be generated via inline code. If this function returns "true", inline
2366/// code will be generated. If this function returns "false", additional
2367/// checks are performed, which may still lead to the inline code.
2368bool HexagonFrameLowering::shouldInlineCSR(MachineFunction &MF,
2369 const CSIVect &CSI) const {
2370 if (MF.getInfo<HexagonMachineFunctionInfo>()->hasEHReturn())
2371 return true;
2372 if (!isOptSize(MF) && !isMinSize(MF))
2373 if (MF.getTarget().getOptLevel() > CodeGenOpt::Default)
2374 return true;
2375
2376 // Check if CSI only has double registers, and if the registers form
2377 // a contiguous block starting from D8.
2378 BitVector Regs(Hexagon::NUM_TARGET_REGS);
2379 for (unsigned i = 0, n = CSI.size(); i < n; ++i) {
2380 unsigned R = CSI[i].getReg();
2381 if (!Hexagon::DoubleRegsRegClass.contains(R))
2382 return true;
2383 Regs[R] = true;
2384 }
2385 int F = Regs.find_first();
2386 if (F != Hexagon::D8)
2387 return true;
2388 while (F >= 0) {
2389 int N = Regs.find_next(F);
2390 if (N >= 0 && N != F+1)
2391 return true;
2392 F = N;
2393 }
2394
2395 return false;
2396}
2397
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002398bool HexagonFrameLowering::useSpillFunction(MachineFunction &MF,
2399 const CSIVect &CSI) const {
2400 if (shouldInlineCSR(MF, CSI))
2401 return false;
2402 unsigned NumCSI = CSI.size();
2403 if (NumCSI <= 1)
2404 return false;
2405
2406 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs
2407 : SpillFuncThreshold;
2408 return Threshold < NumCSI;
2409}
2410
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002411bool HexagonFrameLowering::useRestoreFunction(MachineFunction &MF,
2412 const CSIVect &CSI) const {
2413 if (shouldInlineCSR(MF, CSI))
2414 return false;
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002415 // The restore functions do a bit more than just restoring registers.
2416 // The non-returning versions will go back directly to the caller's
2417 // caller, others will clean up the stack frame in preparation for
2418 // a tail call. Using them can still save code size even if only one
2419 // register is getting restores. Make the decision based on -Oz:
2420 // using -Os will use inline restore for a single register.
2421 if (isMinSize(MF))
2422 return true;
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002423 unsigned NumCSI = CSI.size();
Krzysztof Parzyszekbb63f662016-03-28 14:52:21 +00002424 if (NumCSI <= 1)
2425 return false;
2426
Krzysztof Parzyszek876a19d2015-04-23 16:05:39 +00002427 unsigned Threshold = isOptSize(MF) ? SpillFuncThresholdOs-1
2428 : SpillFuncThreshold;
2429 return Threshold < NumCSI;
2430}
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002431
Krzysztof Parzyszekddafa2c2016-08-01 17:15:30 +00002432bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
2433 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
2434 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2435 // A fairly simplistic guess as to whether a potential load/store to a
2436 // stack location could require an extra register. It does not account
2437 // for store-immediate instructions.
2438 if (HST.useHVXOps())
2439 return StackSize > 256;
2440 return false;
2441}