blob: 1f14546a25b1c5daa2250359356c81510cc5b495 [file] [log] [blame]
Eugene Zelenko9375b782017-10-10 22:33:29 +00001//===- MachineFunction.cpp ------------------------------------------------===//
Alkis Evlogimenosb9209992004-09-05 18:41:35 +00002//
Chandler Carruthca6d7192019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alkis Evlogimenosb9209992004-09-05 18:41:35 +00006//
John Criswell287baed2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Alkis Evlogimenosb9209992004-09-05 18:41:35 +00008//
Chris Lattner45ffeff2002-10-28 01:16:38 +00009// Collect native machine code information for a function. This allows
10// target-specific information about the generated code to be stored with each
11// function.
12//
13//===----------------------------------------------------------------------===//
Chris Lattner3eb005a2002-02-03 07:54:50 +000014
David Greene284ccd02009-08-19 22:16:11 +000015#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000016#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
Chandler Carruth345b8272012-12-03 16:50:05 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallString.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
Chandler Carruth345b8272012-12-03 16:50:05 +000024#include "llvm/Analysis/ConstantFolding.h"
Han Shenc5e85272023-06-28 22:18:53 -070025#include "llvm/Analysis/ProfileSummaryInfo.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Chris Lattner00016e82012-01-27 01:47:28 +000027#include "llvm/CodeGen/MachineConstantPool.h"
Chris Lattner6534a422007-12-31 04:13:23 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstr.h"
Nate Begeman83e5f082006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000031#include "llvm/CodeGen/MachineMemOperand.h"
Chris Lattner06737802010-04-05 05:49:50 +000032#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner6534a422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Alex Lorenz00e26a12015-08-11 23:09:45 +000034#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikiecee844d2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetFrameLowering.h"
Sriraman Tallamccf30a72020-03-16 15:56:02 -070036#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiecee844d2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetLowering.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
Heejin Ahn06f97e32018-06-19 00:26:39 +000040#include "llvm/CodeGen/WasmEHFuncInfo.h"
Reid Kleckner832a5392015-11-17 21:10:25 +000041#include "llvm/CodeGen/WinEHFuncInfo.h"
Nico Webere8872402018-04-30 14:59:11 +000042#include "llvm/Config/llvm-config.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000043#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constant.h"
Chandler Carruth1d569b62013-01-02 11:36:10 +000046#include "llvm/IR/DataLayout.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000047#include "llvm/IR/DerivedTypes.h"
Stefan Gränitz51a75df2023-01-24 12:29:53 +010048#include "llvm/IR/EHPersonalities.h"
Chandler Carruth1d569b62013-01-02 11:36:10 +000049#include "llvm/IR/Function.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000050#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Metadata.h"
Mehdi Aminic0a24f62015-07-07 18:20:57 +000054#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith318caae2015-06-26 22:04:20 +000055#include "llvm/IR/ModuleSlotTracker.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000056#include "llvm/IR/Value.h"
Chris Lattner80a68492010-01-26 05:58:28 +000057#include "llvm/MC/MCContext.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000058#include "llvm/MC/MCSymbol.h"
59#include "llvm/MC/SectionKind.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Compiler.h"
63#include "llvm/Support/DOTGraphTraits.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000064#include "llvm/Support/ErrorHandling.h"
Chris Lattner744980f2006-10-03 20:19:23 +000065#include "llvm/Support/GraphWriter.h"
Chris Lattnerabed3472008-08-23 22:23:09 +000066#include "llvm/Support/raw_ostream.h"
Chandler Carruth345b8272012-12-03 16:50:05 +000067#include "llvm/Target/TargetMachine.h"
Eugene Zelenko9375b782017-10-10 22:33:29 +000068#include <algorithm>
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <iterator>
73#include <string>
Sriraman Tallamccf30a72020-03-16 15:56:02 -070074#include <type_traits>
Eugene Zelenko9375b782017-10-10 22:33:29 +000075#include <utility>
76#include <vector>
77
Jeremy Morse55507042022-01-12 12:35:36 +000078#include "LiveDebugValues/LiveDebugValues.h"
79
Chris Lattner46c2a2a2003-12-20 09:17:07 +000080using namespace llvm;
Chris Lattner3eb005a2002-02-03 07:54:50 +000081
Chandler Carruth636c0712014-04-21 22:55:11 +000082#define DEBUG_TYPE "codegen"
83
Guillaume Chatelet0f686772019-09-05 10:00:22 +000084static cl::opt<unsigned> AlignAllFunctions(
85 "align-all-functions",
86 cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
87 "means align on 16B boundaries)."),
88 cl::init(0), cl::Hidden);
Chad Rosier7fc299b2015-12-29 18:18:07 +000089
Matthias Braun88257e92016-08-19 22:31:45 +000090static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
Eugene Zelenko9375b782017-10-10 22:33:29 +000091 using P = MachineFunctionProperties::Property;
92
Jack Andersene6f03ce2021-12-05 14:55:20 -050093 // clang-format off
Matthias Braun88257e92016-08-19 22:31:45 +000094 switch(Prop) {
Quentin Colombete468a572016-08-26 23:49:01 +000095 case P::FailedISel: return "FailedISel";
Matthias Braun88257e92016-08-19 22:31:45 +000096 case P::IsSSA: return "IsSSA";
97 case P::Legalized: return "Legalized";
Matthias Braunb93e0fa2016-08-23 21:19:49 +000098 case P::NoPHIs: return "NoPHIs";
Matthias Braun60d47202016-08-25 01:27:13 +000099 case P::NoVRegs: return "NoVRegs";
Matthias Braun88257e92016-08-19 22:31:45 +0000100 case P::RegBankSelected: return "RegBankSelected";
101 case P::Selected: return "Selected";
102 case P::TracksLiveness: return "TracksLiveness";
Kang Zhangd13b1c62020-06-09 07:39:42 +0000103 case P::TiedOpsRewritten: return "TiedOpsRewritten";
Jay Foad82d04632021-10-15 11:26:48 +0100104 case P::FailsVerification: return "FailsVerification";
Jack Andersene6f03ce2021-12-05 14:55:20 -0500105 case P::TracksDebugUserValues: return "TracksDebugUserValues";
Derek Schuff690a2c82016-03-29 20:28:20 +0000106 }
Jack Andersene6f03ce2021-12-05 14:55:20 -0500107 // clang-format on
Matthias Braund6aa4ae2016-08-19 23:03:28 +0000108 llvm_unreachable("Invalid machine function property");
Matthias Braun88257e92016-08-19 22:31:45 +0000109}
110
Paul Kirth4524b532022-04-19 16:34:23 +0000111void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
112 if (!F.hasFnAttribute(Attribute::SafeStack))
113 return;
114
115 auto *Existing =
116 dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
117
118 if (!Existing || Existing->getNumOperands() != 2)
119 return;
120
121 auto *MetadataName = "unsafe-stack-size";
122 if (auto &N = Existing->getOperand(0)) {
Zain Jaffal749bae62023-05-09 17:15:13 +0300123 if (N.equalsStr(MetadataName)) {
Paul Kirth4524b532022-04-19 16:34:23 +0000124 if (auto &Op = Existing->getOperand(1)) {
125 auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
126 FrameInfo.setUnsafeStackSize(Val);
127 }
128 }
129 }
130}
131
Aditya Nandakumarfb367002018-09-20 23:01:56 +0000132// Pin the vtable to this file.
133void MachineFunction::Delegate::anchor() {}
134
Matthias Braun88257e92016-08-19 22:31:45 +0000135void MachineFunctionProperties::print(raw_ostream &OS) const {
136 const char *Separator = "";
137 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
138 if (!Properties[I])
139 continue;
140 OS << Separator << getPropertyName(static_cast<Property>(I));
141 Separator = ", ";
142 }
Derek Schuff690a2c82016-03-29 20:28:20 +0000143}
144
Chris Lattner88f25f22010-01-26 04:35:26 +0000145//===----------------------------------------------------------------------===//
Chris Lattner49eb81b2002-10-28 01:12:41 +0000146// MachineFunction implementation
Chris Lattner88f25f22010-01-26 04:35:26 +0000147//===----------------------------------------------------------------------===//
Chris Lattner38fa7292005-01-29 18:41:25 +0000148
Sanjay Patela3bab492015-06-13 15:32:45 +0000149// Out-of-line virtual method.
Eugene Zelenko9375b782017-10-10 22:33:29 +0000150MachineFunctionInfo::~MachineFunctionInfo() = default;
Chris Lattnercdbc2a212009-09-15 22:44:26 +0000151
Duncan P. N. Exon Smith183446f2016-08-30 18:40:47 +0000152void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
Mircea Trofine4cd8682021-12-08 17:36:37 -0800153 MBB->getParent()->deleteMachineBasicBlock(MBB);
Tanya Lattner4158d132004-05-24 06:11:51 +0000154}
Chris Lattner49eb81b2002-10-28 01:12:41 +0000155
Guillaume Chatelet01930452022-06-17 15:13:10 +0000156static inline Align getFnStackAlignment(const TargetSubtargetInfo *STI,
Matthias Braundc823382017-12-15 22:22:46 +0000157 const Function &F) {
Arthur Eubanks577fcdd2021-08-18 10:43:17 -0700158 if (auto MA = F.getFnStackAlign())
Guillaume Chatelet01930452022-06-17 15:13:10 +0000159 return *MA;
160 return STI->getFrameLowering()->getStackAlign();
Charles Davis3ff19ce2016-04-09 23:34:42 +0000161}
162
Daniel Sanders5d27a232020-04-03 15:55:15 -0700163MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
Matthias Braundc823382017-12-15 22:22:46 +0000164 const TargetSubtargetInfo &STI,
Rafael Espindolaca4806b2014-10-14 18:53:16 +0000165 unsigned FunctionNum, MachineModuleInfo &mmi)
Matthias Braundc823382017-12-15 22:22:46 +0000166 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
Quentin Colombet9f61c382016-08-26 22:32:53 +0000167 FunctionNumber = FunctionNum;
168 init();
169}
170
Aditya Nandakumard7b5c2e2019-01-16 00:40:37 +0000171void MachineFunction::handleInsertion(MachineInstr &MI) {
Aditya Nandakumarfb367002018-09-20 23:01:56 +0000172 if (TheDelegate)
173 TheDelegate->MF_HandleInsertion(MI);
174}
175
Aditya Nandakumard7b5c2e2019-01-16 00:40:37 +0000176void MachineFunction::handleRemoval(MachineInstr &MI) {
Aditya Nandakumarfb367002018-09-20 23:01:56 +0000177 if (TheDelegate)
178 TheDelegate->MF_HandleRemoval(MI);
179}
180
Quentin Colombet9f61c382016-08-26 22:32:53 +0000181void MachineFunction::init() {
Derek Schuffab6e5452016-04-11 23:32:13 +0000182 // Assume the function starts in SSA form with correct liveness.
Derek Schuff02e90622016-04-04 18:03:29 +0000183 Properties.set(MachineFunctionProperties::Property::IsSSA);
Derek Schuffab6e5452016-04-11 23:32:13 +0000184 Properties.set(MachineFunctionProperties::Property::TracksLiveness);
Eric Christopherf69bb7a2014-10-08 07:51:41 +0000185 if (STI->getRegisterInfo())
Eric Christopher8eb35a92014-08-12 08:00:56 +0000186 RegInfo = new (Allocator) MachineRegisterInfo(this);
Matthijs Kooijman7167be42008-10-13 12:37:16 +0000187 else
Craig Topper64a7a812014-04-14 00:51:57 +0000188 RegInfo = nullptr;
Bill Wendlinge6d6f3e2013-06-17 20:41:25 +0000189
Craig Topper64a7a812014-04-14 00:51:57 +0000190 MFInfo = nullptr;
Matt Arsenaultc951faf2020-06-18 09:00:16 -0400191
Reid Kleckner9b464c7a2016-04-11 17:54:03 +0000192 // We can realign the stack if the target supports it and the user hasn't
193 // explicitly asked us not to.
194 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
Matthias Braundc823382017-12-15 22:22:46 +0000195 !F.hasFnAttribute("no-realign-stack");
Reid Kleckner9b464c7a2016-04-11 17:54:03 +0000196 FrameInfo = new (Allocator) MachineFrameInfo(
Matthias Braundc823382017-12-15 22:22:46 +0000197 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
Rui Ueyama08343a22019-07-16 04:46:31 +0000198 /*ForcedRealign=*/CanRealignSP &&
Matthias Braundc823382017-12-15 22:22:46 +0000199 F.hasFnAttribute(Attribute::StackAlignment));
Bill Wendlinge6d6f3e2013-06-17 20:41:25 +0000200
Paul Kirth4524b532022-04-19 16:34:23 +0000201 setUnsafeStackSize(F, *FrameInfo);
202
Matthias Braundc823382017-12-15 22:22:46 +0000203 if (F.hasFnAttribute(Attribute::StackAlignment))
Guillaume Chatelet76848e62020-03-18 17:04:10 +0100204 FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
Bill Wendlinge6d6f3e2013-06-17 20:41:25 +0000205
Mehdi Aminic0a24f62015-07-07 18:20:57 +0000206 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
Guillaume Chateletd6190122019-09-11 11:16:48 +0000207 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
Bill Wendlinge6d6f3e2013-06-17 20:41:25 +0000208
Matthias Braundc823382017-12-15 22:22:46 +0000209 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
Evandro Menezese09b2ad2019-04-04 22:40:06 +0000210 // FIXME: Use Function::hasOptSize().
Matthias Braundc823382017-12-15 22:22:46 +0000211 if (!F.hasFnAttribute(Attribute::OptimizeForSize))
Guillaume Chateletd6190122019-09-11 11:16:48 +0000212 Alignment = std::max(Alignment,
213 STI->getTargetLowering()->getPrefFunctionAlignment());
Bill Wendlinge6d6f3e2013-06-17 20:41:25 +0000214
Fangrui Song32938e02023-06-30 09:13:19 -0700215 // -fsanitize=function and -fsanitize=kcfi instrument indirect function calls
216 // to load a type hash before the function label. Ensure functions are aligned
217 // by a least 4 to avoid unaligned access, which is especially important for
218 // -mno-unaligned-access.
219 if (F.hasMetadata(LLVMContext::MD_func_sanitize) ||
220 F.getMetadata(LLVMContext::MD_kcfi_type))
221 Alignment = std::max(Alignment, Align(4));
222
Chad Rosier7fc299b2015-12-29 18:18:07 +0000223 if (AlignAllFunctions)
Guillaume Chatelet549dc0a2019-09-27 12:54:21 +0000224 Alignment = Align(1ULL << AlignAllFunctions);
Chad Rosier7fc299b2015-12-29 18:18:07 +0000225
Craig Topper64a7a812014-04-14 00:51:57 +0000226 JumpTableInfo = nullptr;
Tobias Grosser318a7dc2015-08-17 10:58:03 +0000227
Reid Kleckner832a5392015-11-17 21:10:25 +0000228 if (isFuncletEHPersonality(classifyEHPersonality(
Matthias Braundc823382017-12-15 22:22:46 +0000229 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
Reid Kleckner832a5392015-11-17 21:10:25 +0000230 WinEHInfo = new (Allocator) WinEHFuncInfo();
231 }
232
Heejin Ahn06f97e32018-06-19 00:26:39 +0000233 if (isScopedEHPersonality(classifyEHPersonality(
234 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
235 WasmEHInfo = new (Allocator) WasmEHFuncInfo();
236 }
237
Quentin Colombet9f61c382016-08-26 22:32:53 +0000238 assert(Target.isCompatibleDataLayout(getDataLayout()) &&
Tobias Grosser318a7dc2015-08-17 10:58:03 +0000239 "Can't create a MachineFunction using a Module with a "
240 "Target-incompatible DataLayout attached\n");
241
Matt Arsenault1d05d402022-04-26 20:35:01 -0400242 PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
Chris Lattnera55f6462002-12-25 05:03:22 +0000243}
244
Matt Arsenaultc951faf2020-06-18 09:00:16 -0400245void MachineFunction::initTargetMachineFunctionInfo(
246 const TargetSubtargetInfo &STI) {
247 assert(!MFInfo && "MachineFunctionInfo already set");
248 MFInfo = Target.createMachineFunctionInfo(Allocator, F, &STI);
249}
250
Alkis Evlogimenosb9209992004-09-05 18:41:35 +0000251MachineFunction::~MachineFunction() {
Quentin Colombet9f61c382016-08-26 22:32:53 +0000252 clear();
253}
254
255void MachineFunction::clear() {
256 Properties.reset();
Jakob Stoklund Olesen70d9c472013-01-05 05:05:51 +0000257 // Don't call destructors on MachineInstr and MachineOperand. All of their
258 // memory comes from the BumpPtrAllocator which is about to be purged.
259 //
260 // Do call MachineBasicBlock destructors, it contains std::vectors.
261 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
262 I->Insts.clearAndLeakNodesUnsafely();
Roman Tereshin59714452018-04-30 18:58:57 +0000263 MBBNumbering.clear();
Jakob Stoklund Olesen70d9c472013-01-05 05:05:51 +0000264
Dan Gohman1f4347b2008-07-07 23:14:23 +0000265 InstructionRecycler.clear(Allocator);
Jakob Stoklund Olesen1828d3f2013-01-05 05:00:09 +0000266 OperandRecycler.clear(Allocator);
Dan Gohman1f4347b2008-07-07 23:14:23 +0000267 BasicBlockRecycler.clear(Allocator);
Reid Klecknerf9e77342017-09-05 20:14:58 +0000268 CodeViewAnnotations.clear();
Tim Northover4ead40c2017-03-09 21:12:06 +0000269 VariableDbgInfos.clear();
Bill Wendling027af702009-06-25 00:32:48 +0000270 if (RegInfo) {
271 RegInfo->~MachineRegisterInfo();
272 Allocator.Deallocate(RegInfo);
273 }
Dan Gohman1f4347b2008-07-07 23:14:23 +0000274 if (MFInfo) {
Bill Wendling027af702009-06-25 00:32:48 +0000275 MFInfo->~MachineFunctionInfo();
276 Allocator.Deallocate(MFInfo);
Dan Gohman1f4347b2008-07-07 23:14:23 +0000277 }
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000278
279 FrameInfo->~MachineFrameInfo();
280 Allocator.Deallocate(FrameInfo);
281
282 ConstantPool->~MachineConstantPool();
283 Allocator.Deallocate(ConstantPool);
284
Chris Lattner5b5cc062010-01-25 23:26:13 +0000285 if (JumpTableInfo) {
286 JumpTableInfo->~MachineJumpTableInfo();
287 Allocator.Deallocate(JumpTableInfo);
288 }
Reid Kleckner832a5392015-11-17 21:10:25 +0000289
290 if (WinEHInfo) {
291 WinEHInfo->~WinEHFuncInfo();
292 Allocator.Deallocate(WinEHInfo);
293 }
Heejin Ahnddc0e4b2018-09-28 20:54:04 +0000294
295 if (WasmEHInfo) {
296 WasmEHInfo->~WasmEHFuncInfo();
297 Allocator.Deallocate(WasmEHInfo);
298 }
Chris Lattnera7f707c2002-10-30 00:48:05 +0000299}
300
Mehdi Aminic0a24f62015-07-07 18:20:57 +0000301const DataLayout &MachineFunction::getDataLayout() const {
Matthias Braundc823382017-12-15 22:22:46 +0000302 return F.getParent()->getDataLayout();
Mehdi Aminic0a24f62015-07-07 18:20:57 +0000303}
304
Sanjay Patela3bab492015-06-13 15:32:45 +0000305/// Get the JumpTableInfo for this function.
306/// If it does not already exist, allocate one.
Chris Lattner5b5cc062010-01-25 23:26:13 +0000307MachineJumpTableInfo *MachineFunction::
308getOrCreateJumpTableInfo(unsigned EntryKind) {
309 if (JumpTableInfo) return JumpTableInfo;
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000310
Dan Gohman7874c612010-03-18 18:49:47 +0000311 JumpTableInfo = new (Allocator)
Chris Lattner5b5cc062010-01-25 23:26:13 +0000312 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
313 return JumpTableInfo;
314}
Chris Lattner743066a2006-10-03 19:18:57 +0000315
Matt Arsenault6d0718c2019-10-29 16:16:05 -0700316DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
Matt Arsenault47daf8f2020-09-17 17:50:42 -0400317 return F.getDenormalMode(FPType);
Matt Arsenault6d0718c2019-10-29 16:16:05 -0700318}
319
Reid Kleckner14068032014-04-10 22:58:43 +0000320/// Should we be emitting segmented stack stuff for the function
Quentin Colombetcd8d5eb2016-01-19 22:31:12 +0000321bool MachineFunction::shouldSplitStack() const {
Matthias Braun5863fee2017-12-15 22:22:58 +0000322 return getFunction().hasFnAttribute("split-stack");
Reid Kleckner14068032014-04-10 22:58:43 +0000323}
324
Fangrui Songd0c2e952022-08-07 00:26:33 +0000325[[nodiscard]] unsigned
Eric Christopher2df87142019-04-12 06:31:59 +0000326MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
327 FrameInstructions.push_back(Inst);
328 return FrameInstructions.size() - 1;
329}
330
Sanjay Patela3bab492015-06-13 15:32:45 +0000331/// This discards all of the MachineBasicBlock numbers and recomputes them.
332/// This guarantees that the MBB numbers are sequential, dense, and match the
333/// ordering of the blocks within the function. If a specific MachineBasicBlock
334/// is specified, only that block and those after it are renumbered.
Chris Lattner743066a2006-10-03 19:18:57 +0000335void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
336 if (empty()) { MBBNumbering.clear(); return; }
337 MachineFunction::iterator MBBI, E = end();
Craig Topper64a7a812014-04-14 00:51:57 +0000338 if (MBB == nullptr)
Chris Lattner743066a2006-10-03 19:18:57 +0000339 MBBI = begin();
340 else
Duncan P. N. Exon Smith41887612015-10-09 19:40:45 +0000341 MBBI = MBB->getIterator();
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000342
Chris Lattner743066a2006-10-03 19:18:57 +0000343 // Figure out the block number this should have.
344 unsigned BlockNo = 0;
Chris Lattner744980f2006-10-03 20:19:23 +0000345 if (MBBI != begin())
Benjamin Kramer52ceb712014-03-02 12:27:27 +0000346 BlockNo = std::prev(MBBI)->getNumber() + 1;
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000347
Chris Lattner743066a2006-10-03 19:18:57 +0000348 for (; MBBI != E; ++MBBI, ++BlockNo) {
349 if (MBBI->getNumber() != (int)BlockNo) {
350 // Remove use of the old number.
351 if (MBBI->getNumber() != -1) {
352 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
353 "MBB number mismatch!");
Craig Topper64a7a812014-04-14 00:51:57 +0000354 MBBNumbering[MBBI->getNumber()] = nullptr;
Chris Lattner743066a2006-10-03 19:18:57 +0000355 }
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000356
Chris Lattner743066a2006-10-03 19:18:57 +0000357 // If BlockNo is already taken, set that block's number to -1.
358 if (MBBNumbering[BlockNo])
359 MBBNumbering[BlockNo]->setNumber(-1);
360
Duncan P. N. Exon Smith41887612015-10-09 19:40:45 +0000361 MBBNumbering[BlockNo] = &*MBBI;
Chris Lattner743066a2006-10-03 19:18:57 +0000362 MBBI->setNumber(BlockNo);
363 }
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000364 }
Chris Lattner743066a2006-10-03 19:18:57 +0000365
366 // Okay, all the blocks are renumbered. If we have compactified the block
367 // numbering, shrink MBBNumbering now.
368 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
369 MBBNumbering.resize(BlockNo);
370}
371
Rahman Lavaee9e2e75e2020-04-13 12:14:42 -0700372/// This method iterates over the basic blocks and assigns their IsBeginSection
373/// and IsEndSection fields. This must be called after MBB layout is finalized
374/// and the SectionID's are assigned to MBBs.
375void MachineFunction::assignBeginEndSections() {
376 front().setIsBeginSection();
377 auto CurrentSectionID = front().getSectionID();
378 for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
379 if (MBBI->getSectionID() == CurrentSectionID)
380 continue;
381 MBBI->setIsBeginSection();
382 std::prev(MBBI)->setIsEndSection();
383 CurrentSectionID = MBBI->getSectionID();
384 }
385 back().setIsEndSection();
386}
387
Sanjay Patela3bab492015-06-13 15:32:45 +0000388/// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
Benjamin Kramerf0389a82016-06-12 15:39:02 +0000389MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
Mircea Trofin06b3f022021-12-06 17:33:13 -0800390 DebugLoc DL,
Fangrui Song53054552020-09-19 20:41:25 -0700391 bool NoImplicit) {
Dan Gohman1f4347b2008-07-07 23:14:23 +0000392 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
Mircea Trofin06b3f022021-12-06 17:33:13 -0800393 MachineInstr(*this, MCID, std::move(DL), NoImplicit);
Dan Gohman1f4347b2008-07-07 23:14:23 +0000394}
Chris Lattner743066a2006-10-03 19:18:57 +0000395
Sanjay Patela3bab492015-06-13 15:32:45 +0000396/// Create a new MachineInstr which is a copy of the 'Orig' instruction,
397/// identical in all ways except the instruction has no parent, prev, or next.
Dan Gohman1f4347b2008-07-07 23:14:23 +0000398MachineInstr *
399MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
400 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
401 MachineInstr(*this, *Orig);
402}
403
Mircea Trofina77637a2021-12-08 21:12:54 -0800404MachineInstr &MachineFunction::cloneMachineInstrBundle(
405 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
406 const MachineInstr &Orig) {
Matthias Braun09082232017-08-22 23:56:30 +0000407 MachineInstr *FirstClone = nullptr;
408 MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
Eugene Zelenko9375b782017-10-10 22:33:29 +0000409 while (true) {
Matthias Braun09082232017-08-22 23:56:30 +0000410 MachineInstr *Cloned = CloneMachineInstr(&*I);
411 MBB.insert(InsertBefore, Cloned);
412 if (FirstClone == nullptr) {
413 FirstClone = Cloned;
414 } else {
415 Cloned->bundleWithPred();
416 }
417
418 if (!I->isBundledWithSucc())
419 break;
420 ++I;
421 }
Vedant Kumar6c71c582020-04-07 13:09:29 -0700422 // Copy over call site info to the cloned instruction if needed. If Orig is in
423 // a bundle, copyCallSiteInfo takes care of finding the call instruction in
424 // the bundle.
425 if (Orig.shouldUpdateCallSiteInfo())
426 copyCallSiteInfo(&Orig, FirstClone);
Matthias Braun09082232017-08-22 23:56:30 +0000427 return *FirstClone;
428}
429
Sanjay Patela3bab492015-06-13 15:32:45 +0000430/// Delete the given MachineInstr.
Dan Gohman1f4347b2008-07-07 23:14:23 +0000431///
Jakob Stoklund Olesen70d9c472013-01-05 05:05:51 +0000432/// This function also serves as the MachineInstr destructor - the real
433/// ~MachineInstr() destructor must be empty.
Mircea Trofin8134d492021-12-08 20:35:33 -0800434void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
Djordje Todorovicb4e1c252019-06-27 13:10:29 +0000435 // Verify that a call site info is at valid state. This assertion should
436 // be triggered during the implementation of support for the
437 // call site info of a new architecture. If the assertion is triggered,
438 // back trace will tell where to insert a call to updateCallSiteInfo().
Kazu Hirata03cf9562023-03-15 18:06:32 -0700439 assert((!MI->isCandidateForCallSiteEntry() || !CallSitesInfo.contains(MI)) &&
Djordje Todorovicb4e1c252019-06-27 13:10:29 +0000440 "Call site info was not updated!");
Jakob Stoklund Olesen1828d3f2013-01-05 05:00:09 +0000441 // Strip it for parts. The operand array and the MI object itself are
442 // independently recyclable.
443 if (MI->Operands)
444 deallocateOperandArray(MI->CapOperands, MI->Operands);
Jakob Stoklund Olesen70d9c472013-01-05 05:05:51 +0000445 // Don't call ~MachineInstr() which must be trivial anyway because
446 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
447 // destructors.
Dan Gohman1f4347b2008-07-07 23:14:23 +0000448 InstructionRecycler.Deallocate(Allocator, MI);
449}
450
Sanjay Patela3bab492015-06-13 15:32:45 +0000451/// Allocate a new MachineBasicBlock. Use this instead of
452/// `new MachineBasicBlock'.
Dan Gohman1f4347b2008-07-07 23:14:23 +0000453MachineBasicBlock *
454MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
Rahman Lavaee050b8da2022-12-06 22:37:33 -0800455 MachineBasicBlock *MBB =
456 new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
457 MachineBasicBlock(*this, bb);
458 // Set BBID for `-basic-block=sections=labels` and
459 // `-basic-block-sections=list` to allow robust mapping of profiles to basic
460 // blocks.
461 if (Target.getBBSectionsType() == BasicBlockSection::Labels ||
462 Target.getBBSectionsType() == BasicBlockSection::List)
463 MBB->setBBID(NextBBID++);
464 return MBB;
Dan Gohman1f4347b2008-07-07 23:14:23 +0000465}
466
Sanjay Patela3bab492015-06-13 15:32:45 +0000467/// Delete the given MachineBasicBlock.
Mircea Trofine4cd8682021-12-08 17:36:37 -0800468void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
Dan Gohman1f4347b2008-07-07 23:14:23 +0000469 assert(MBB->getParent() == this && "MBB parent mismatch!");
Victor Huang347c4612020-11-16 10:33:06 -0600470 // Clean up any references to MBB in jump tables before deleting it.
471 if (JumpTableInfo)
472 JumpTableInfo->RemoveMBBFromJumpTables(MBB);
Dan Gohman1f4347b2008-07-07 23:14:23 +0000473 MBB->~MachineBasicBlock();
474 BasicBlockRecycler.Deallocate(Allocator, MBB);
475}
476
Justin Lebarf4c231a2016-07-15 18:26:59 +0000477MachineMemOperand *MachineFunction::getMachineMemOperand(
478 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
Guillaume Chatelet8b16e932020-03-30 09:38:44 +0000479 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
Konstantin Zhuravlyovdf2c53c2017-07-11 22:23:00 +0000480 SyncScope::ID SSID, AtomicOrdering Ordering,
Konstantin Zhuravlyoveef4c7a2016-10-15 22:01:18 +0000481 AtomicOrdering FailureOrdering) {
Justin Lebar4dd3ec92016-07-14 17:07:44 +0000482 return new (Allocator)
Konstantin Zhuravlyoveef4c7a2016-10-15 22:01:18 +0000483 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
Konstantin Zhuravlyovdf2c53c2017-07-11 22:23:00 +0000484 SSID, Ordering, FailureOrdering);
Dan Gohman4ba02752009-09-25 20:36:54 +0000485}
486
David Sherwooddd10b5f2020-07-14 13:50:21 +0100487MachineMemOperand *MachineFunction::getMachineMemOperand(
Matt Arsenaultd08403b2021-05-19 22:06:14 -0400488 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
489 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
490 SyncScope::ID SSID, AtomicOrdering Ordering,
491 AtomicOrdering FailureOrdering) {
492 return new (Allocator)
493 MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
494 Ordering, FailureOrdering);
495}
496
497MachineMemOperand *MachineFunction::getMachineMemOperand(
Matt Arsenault6b91eca2021-06-08 17:10:51 -0400498 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
Eli Friedman4d7b2bb2021-06-21 16:34:02 -0700499 return new (Allocator)
500 MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
501 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
502 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
David Sherwooddd10b5f2020-07-14 13:50:21 +0100503}
504
Matt Arsenaultd08403b2021-05-19 22:06:14 -0400505MachineMemOperand *MachineFunction::getMachineMemOperand(
506 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
507 return new (Allocator)
508 MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
509 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
510 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
511}
512
Dan Gohman4ba02752009-09-25 20:36:54 +0000513MachineMemOperand *
514MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
Matt Arsenaultd08403b2021-05-19 22:06:14 -0400515 int64_t Offset, LLT Ty) {
Matt Arsenault4f8479b2019-01-31 01:49:58 +0000516 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
517
518 // If there is no pointer value, the offset isn't tracked so we need to adjust
519 // the base alignment.
Guillaume Chatelete2bfff52020-03-27 13:51:59 +0000520 Align Alignment = PtrInfo.V.isNull()
521 ? commonAlignment(MMO->getBaseAlign(), Offset)
522 : MMO->getBaseAlign();
Matt Arsenault4f8479b2019-01-31 01:49:58 +0000523
Matt Arsenaultad611432020-08-08 12:22:40 -0400524 // Do not preserve ranges, since we don't necessarily know what the high bits
525 // are anymore.
Eli Friedman4d7b2bb2021-06-21 16:34:02 -0700526 return new (Allocator) MachineMemOperand(
Matt Arsenaultd08403b2021-05-19 22:06:14 -0400527 PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
Eli Friedman4d7b2bb2021-06-21 16:34:02 -0700528 MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
529 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
Dan Gohman4ba02752009-09-25 20:36:54 +0000530}
531
Hiroshi Inoued8d9f8a2017-08-01 03:32:15 +0000532MachineMemOperand *
533MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
534 const AAMDNodes &AAInfo) {
535 MachinePointerInfo MPI = MMO->getValue() ?
536 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
537 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
538
Guillaume Chatelete2bfff52020-03-27 13:51:59 +0000539 return new (Allocator) MachineMemOperand(
Guillaume Chatelet8b16e932020-03-30 09:38:44 +0000540 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
Eli Friedman4d7b2bb2021-06-21 16:34:02 -0700541 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
Guillaume Chatelete2bfff52020-03-27 13:51:59 +0000542 MMO->getFailureOrdering());
Hiroshi Inoued8d9f8a2017-08-01 03:32:15 +0000543}
544
Simon Pilgrimb92a4722019-06-13 12:58:55 +0000545MachineMemOperand *
546MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
547 MachineMemOperand::Flags Flags) {
548 return new (Allocator) MachineMemOperand(
Guillaume Chatelet8b16e932020-03-30 09:38:44 +0000549 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
Simon Pilgrimb92a4722019-06-13 12:58:55 +0000550 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
Eli Friedman4d7b2bb2021-06-21 16:34:02 -0700551 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
Simon Pilgrimb92a4722019-06-13 12:58:55 +0000552}
553
Amy Huangf93660a2019-10-28 14:53:32 -0700554MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
555 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
Marco Elver94f3cfb2022-09-06 15:48:41 +0200556 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
557 uint32_t CFIType) {
Chandler Carruth0cda7b92018-08-16 21:30:05 +0000558 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
Sami Tolvanen72b40da2022-02-15 14:32:08 -0800559 PostInstrSymbol, HeapAllocMarker,
Marco Elver94f3cfb2022-09-06 15:48:41 +0200560 PCSections, CFIType);
Dan Gohmand2f9d072009-10-09 18:10:05 +0000561}
562
Alex Lorenz5304ab12015-07-21 16:59:53 +0000563const char *MachineFunction::createExternalSymbolName(StringRef Name) {
564 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
Fangrui Song6aa48782018-11-17 01:44:25 +0000565 llvm::copy(Name, Dest);
Alex Lorenz5304ab12015-07-21 16:59:53 +0000566 Dest[Name.size()] = 0;
567 return Dest;
568}
569
Matthias Braun5b535e72018-07-26 00:27:47 +0000570uint32_t *MachineFunction::allocateRegMask() {
571 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
572 unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
573 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
574 memset(Mask, 0, Size * sizeof(Mask[0]));
575 return Mask;
576}
577
Eli Friedman098e2582020-01-13 15:32:45 -0800578ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
579 int* AllocMask = Allocator.Allocate<int>(Mask.size());
580 copy(Mask, AllocMask);
581 return {AllocMask, Mask.size()};
582}
583
Aaron Ballman7fced3f2017-10-15 14:32:27 +0000584#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Keren33afa9a2016-01-29 20:50:44 +0000585LLVM_DUMP_METHOD void MachineFunction::dump() const {
David Greene03fa6882010-01-04 23:39:17 +0000586 print(dbgs());
Dan Gohman1f4347b2008-07-07 23:14:23 +0000587}
Manman Ren4f061be2012-09-06 19:06:06 +0000588#endif
Chris Lattnera7f707c2002-10-30 00:48:05 +0000589
Craig Topper53cc3762012-08-22 06:07:19 +0000590StringRef MachineFunction::getName() const {
Matthias Braun5863fee2017-12-15 22:22:58 +0000591 return getFunction().getName();
Craig Topper53cc3762012-08-22 06:07:19 +0000592}
593
Matthias Braun25e9c812016-05-05 18:14:43 +0000594void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
David Blaikieac7a4902012-08-22 17:18:53 +0000595 OS << "# Machine code for function " << getName() << ": ";
Derek Schuff690a2c82016-03-29 20:28:20 +0000596 getProperties().print(OS);
Matthias Braun804dc542016-09-29 01:47:42 +0000597 OS << '\n';
Chris Lattner5b841ff2002-12-28 20:37:16 +0000598
599 // Print Frame Information
Dan Gohman1f4347b2008-07-07 23:14:23 +0000600 FrameInfo->print(*this, OS);
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000601
Nate Begeman83e5f082006-04-22 18:53:45 +0000602 // Print JumpTable Information
Chris Lattner5b5cc062010-01-25 23:26:13 +0000603 if (JumpTableInfo)
604 JumpTableInfo->print(OS);
Chris Lattnere1511612003-01-13 00:23:03 +0000605
606 // Print Constant Pool
Chris Lattnerb1d55db2009-08-23 01:12:47 +0000607 ConstantPool->print(OS);
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000608
Eric Christopher156c9f02014-08-05 02:39:49 +0000609 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000610
Matthijs Kooijman7167be42008-10-13 12:37:16 +0000611 if (RegInfo && !RegInfo->livein_empty()) {
Dan Gohman89871b62009-10-31 20:19:03 +0000612 OS << "Function Live Ins: ";
Chris Lattner6534a422007-12-31 04:13:23 +0000613 for (MachineRegisterInfo::livein_iterator
614 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
Francis Visoiu Mistrih8442f282017-11-28 12:42:37 +0000615 OS << printReg(I->first, TRI);
Chris Lattner02554c32006-05-16 05:55:30 +0000616 if (I->second)
Francis Visoiu Mistrih8442f282017-11-28 12:42:37 +0000617 OS << " in " << printReg(I->second, TRI);
Benjamin Kramer52ceb712014-03-02 12:27:27 +0000618 if (std::next(I) != E)
Dan Gohman89871b62009-10-31 20:19:03 +0000619 OS << ", ";
Chris Lattner2818f792005-08-31 22:34:59 +0000620 }
Chris Lattnerb1d55db2009-08-23 01:12:47 +0000621 OS << '\n';
Chris Lattner2818f792005-08-31 22:34:59 +0000622 }
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000623
Matthias Braun5863fee2017-12-15 22:22:58 +0000624 ModuleSlotTracker MST(getFunction().getParent());
625 MST.incorporateFunction(getFunction());
Alexey Samsonovea3bb3e2014-04-30 18:29:51 +0000626 for (const auto &BB : *this) {
Dan Gohman89871b62009-10-31 20:19:03 +0000627 OS << '\n';
Francis Visoiu Mistrih7e0b1762018-02-26 15:23:42 +0000628 // If we print the whole function, print it at its most verbose level.
629 BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
Dan Gohman89871b62009-10-31 20:19:03 +0000630 }
Brian Gaeke4bc33fe2004-03-29 21:58:31 +0000631
David Blaikieac7a4902012-08-22 17:18:53 +0000632 OS << "\n# End machine code for function " << getName() << ".\n\n";
Chris Lattnera7f707c2002-10-30 00:48:05 +0000633}
634
David Candler48a56192019-10-31 08:55:57 +0000635/// True if this function needs frame moves for debug or exceptions.
636bool MachineFunction::needsFrameMoves() const {
637 return getMMI().hasDebugInfo() ||
638 getTarget().Options.ForceDwarfFrameSection ||
639 F.needsUnwindTableEntry();
640}
641
Alkis Evlogimenos8dccb672004-07-08 00:47:58 +0000642namespace llvm {
Eugene Zelenko9375b782017-10-10 22:33:29 +0000643
Alkis Evlogimenosb9209992004-09-05 18:41:35 +0000644 template<>
645 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
Eugene Zelenko9375b782017-10-10 22:33:29 +0000646 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grossera2927b22009-11-30 12:38:13 +0000647
Alkis Evlogimenosb9209992004-09-05 18:41:35 +0000648 static std::string getGraphName(const MachineFunction *F) {
Yaron Keren9b9119a2015-03-27 17:51:30 +0000649 return ("CFG for '" + F->getName() + "' function").str();
Alkis Evlogimenos8dccb672004-07-08 00:47:58 +0000650 }
651
Tobias Grosserd9680642009-11-30 12:38:47 +0000652 std::string getNodeLabel(const MachineBasicBlock *Node,
653 const MachineFunction *Graph) {
Chris Lattner167270f2009-08-23 03:13:20 +0000654 std::string OutStr;
655 {
656 raw_string_ostream OSS(OutStr);
Jakob Stoklund Oleseneb5ac7d2010-10-30 01:26:19 +0000657
658 if (isSimple()) {
Francis Visoiu Mistrih987af562017-12-04 17:18:51 +0000659 OSS << printMBBReference(*Node);
Jakob Stoklund Oleseneb5ac7d2010-10-30 01:26:19 +0000660 if (const BasicBlock *BB = Node->getBasicBlock())
661 OSS << ": " << BB->getName();
662 } else
Chris Lattner167270f2009-08-23 03:13:20 +0000663 Node->print(OSS);
Alkis Evlogimenos8dccb672004-07-08 00:47:58 +0000664 }
Alkis Evlogimenosb9209992004-09-05 18:41:35 +0000665
Alkis Evlogimenosb9209992004-09-05 18:41:35 +0000666 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
667
668 // Process string output to make it nicer...
669 for (unsigned i = 0; i != OutStr.length(); ++i)
670 if (OutStr[i] == '\n') { // Left justify
671 OutStr[i] = '\\';
672 OutStr.insert(OutStr.begin()+i+1, 'l');
673 }
674 return OutStr;
675 }
676 };
Eugene Zelenko9375b782017-10-10 22:33:29 +0000677
678} // end namespace llvm
Alkis Evlogimenos8dccb672004-07-08 00:47:58 +0000679
680void MachineFunction::viewCFG() const
681{
Jim Laskey8042f222005-10-12 12:09:05 +0000682#ifndef NDEBUG
David Blaikieac7a4902012-08-22 17:18:53 +0000683 ViewGraph(this, "mf" + getName());
Reid Spencer8bc07062006-06-27 16:49:46 +0000684#else
Dan Gohmand2868a02010-07-07 17:28:45 +0000685 errs() << "MachineFunction::viewCFG is only available in debug builds on "
Daniel Dunbar84bf5462009-08-23 08:50:52 +0000686 << "systems with Graphviz or gv!\n";
Reid Spencer8bc07062006-06-27 16:49:46 +0000687#endif // NDEBUG
Alkis Evlogimenos8dccb672004-07-08 00:47:58 +0000688}
689
690void MachineFunction::viewCFGOnly() const
691{
Owen Anderson5709d5a2009-06-24 17:37:09 +0000692#ifndef NDEBUG
David Blaikieac7a4902012-08-22 17:18:53 +0000693 ViewGraph(this, "mf" + getName(), true);
Owen Anderson5709d5a2009-06-24 17:37:09 +0000694#else
Dan Gohmand2868a02010-07-07 17:28:45 +0000695 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
Daniel Dunbar84bf5462009-08-23 08:50:52 +0000696 << "systems with Graphviz or gv!\n";
Owen Anderson5709d5a2009-06-24 17:37:09 +0000697#endif // NDEBUG
Alkis Evlogimenos8dccb672004-07-08 00:47:58 +0000698}
699
Sanjay Patela3bab492015-06-13 15:32:45 +0000700/// Add the specified physical register as a live-in value and
Bob Wilson59fbc9a2009-04-20 18:36:57 +0000701/// create a corresponding virtual register for it.
Matt Arsenault1bd85892020-05-19 13:01:19 -0400702Register MachineFunction::addLiveIn(MCRegister PReg,
Devang Pateld17405d2011-02-21 23:21:26 +0000703 const TargetRegisterClass *RC) {
Evan Chengc5dd7ec2010-05-24 21:33:37 +0000704 MachineRegisterInfo &MRI = getRegInfo();
Matt Arsenault1bd85892020-05-19 13:01:19 -0400705 Register VReg = MRI.getLiveInVirtReg(PReg);
Evan Chengc5dd7ec2010-05-24 21:33:37 +0000706 if (VReg) {
Quentin Colombetf88a6cb2013-12-12 00:15:47 +0000707 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
708 (void)VRegRC;
709 // A physical register can be added several times.
710 // Between two calls, the register class of the related virtual register
711 // may have been constrained to match some operation constraints.
712 // In that case, check that the current register class includes the
713 // physical register and is a sub class of the specified RC.
714 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
715 RC->hasSubClassEq(VRegRC))) &&
716 "Register class mismatch!");
Evan Chengc5dd7ec2010-05-24 21:33:37 +0000717 return VReg;
718 }
719 VReg = MRI.createVirtualRegister(RC);
720 MRI.addLiveIn(PReg, VReg);
Bob Wilson59fbc9a2009-04-20 18:36:57 +0000721 return VReg;
722}
723
Sanjay Patela3bab492015-06-13 15:32:45 +0000724/// Return the MCSymbol for the specified non-empty jump table.
Bill Wendling5c86eaf2010-06-29 22:34:52 +0000725/// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
726/// normal 'L' label is returned.
NAKAMURA Takumie82ebbb2014-06-25 12:40:56 +0000727MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
Bill Wendling5c86eaf2010-06-29 22:34:52 +0000728 bool isLinkerPrivate) const {
Mehdi Aminic0a24f62015-07-07 18:20:57 +0000729 const DataLayout &DL = getDataLayout();
Chris Lattnerf2e86a72010-01-26 06:28:43 +0000730 assert(JumpTableInfo && "No jump tables");
Chandler Carruthd6b2d162010-01-27 10:27:10 +0000731 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
Chad Rosierbe02a0a2012-06-19 23:37:57 +0000732
Mehdi Aminia2120aa2016-10-01 05:57:55 +0000733 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
734 : DL.getPrivateGlobalPrefix();
Alp Tokerbf3e6862014-06-26 22:52:05 +0000735 SmallString<60> Name;
736 raw_svector_ostream(Name)
737 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
Jim Grosbach3e3edb42015-05-18 18:43:14 +0000738 return Ctx.getOrCreateSymbol(Name);
Chris Lattnerf2e86a72010-01-26 06:28:43 +0000739}
740
Sanjay Patela3bab492015-06-13 15:32:45 +0000741/// Return a function-local symbol to represent the PIC base.
Chris Lattnereef1e042010-11-14 22:48:15 +0000742MCSymbol *MachineFunction::getPICBaseSymbol() const {
Mehdi Aminic0a24f62015-07-07 18:20:57 +0000743 const DataLayout &DL = getDataLayout();
744 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
745 Twine(getFunctionNumber()) + "$pb");
Chris Lattnereef1e042010-11-14 22:48:15 +0000746}
Chris Lattnerf2e86a72010-01-26 06:28:43 +0000747
Matthias Braun1520f7a2016-12-01 19:32:15 +0000748/// \name Exception Handling
749/// \{
750
751LandingPadInfo &
752MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
753 unsigned N = LandingPads.size();
754 for (unsigned i = 0; i < N; ++i) {
755 LandingPadInfo &LP = LandingPads[i];
756 if (LP.LandingPadBlock == LandingPad)
757 return LP;
758 }
759
760 LandingPads.push_back(LandingPadInfo(LandingPad));
761 return LandingPads[N];
762}
763
764void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
765 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
766 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
767 LP.BeginLabels.push_back(BeginLabel);
768 LP.EndLabels.push_back(EndLabel);
769}
770
771MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
772 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
773 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
774 LP.LandingPadLabel = LandingPadLabel;
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000775
776 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
777 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
James Y Knight2c6535d2023-01-06 13:26:03 -0500778 // If there's no typeid list specified, then "cleanup" is implicit.
779 // Otherwise, id 0 is reserved for the cleanup action.
780 if (LPI->isCleanup() && LPI->getNumClauses() != 0)
781 LP.TypeIds.push_back(0);
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000782
783 // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
Heejin Ahnca240182018-09-29 09:22:25 +0000784 // correct, but we need to do it this way because of how the DWARF EH
785 // emitter processes the clauses.
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000786 for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
787 Value *Val = LPI->getClause(I - 1);
788 if (LPI->isCatch(I - 1)) {
James Y Knight2c6535d2023-01-06 13:26:03 -0500789 LP.TypeIds.push_back(
790 getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000791 } else {
792 // Add filters in a list.
793 auto *CVal = cast<Constant>(Val);
James Y Knight2c6535d2023-01-06 13:26:03 -0500794 SmallVector<unsigned, 4> FilterList;
Kazu Hirataf7812f02021-11-14 09:32:38 -0800795 for (const Use &U : CVal->operands())
James Y Knight2c6535d2023-01-06 13:26:03 -0500796 FilterList.push_back(
797 getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000798
James Y Knight2c6535d2023-01-06 13:26:03 -0500799 LP.TypeIds.push_back(getFilterIDFor(FilterList));
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000800 }
801 }
802
Heejin Ahn19fb95c2018-10-25 23:55:10 +0000803 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
Kazu Hirata8fb02782022-10-17 10:15:10 -0700804 for (unsigned I = CPI->arg_size(); I != 0; --I) {
James Y Knight2c6535d2023-01-06 13:26:03 -0500805 auto *TypeInfo =
806 dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
807 LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
Heejin Ahn19fb95c2018-10-25 23:55:10 +0000808 }
Heejin Ahn8f1949a2018-09-25 19:56:44 +0000809
810 } else {
811 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
812 }
813
Matthias Braun1520f7a2016-12-01 19:32:15 +0000814 return LandingPadLabel;
815}
816
Matthias Braun1520f7a2016-12-01 19:32:15 +0000817void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
818 ArrayRef<unsigned> Sites) {
819 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
820}
821
822unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
823 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
824 if (TypeInfos[i] == TI) return i + 1;
825
826 TypeInfos.push_back(TI);
827 return TypeInfos.size();
828}
829
James Y Knight2c6535d2023-01-06 13:26:03 -0500830int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
Matthias Braun1520f7a2016-12-01 19:32:15 +0000831 // If the new filter coincides with the tail of an existing filter, then
832 // re-use the existing filter. Folding filters more than this requires
833 // re-ordering filters and/or their elements - probably not worth it.
Kazu Hirata44969dc2021-02-15 14:46:10 -0800834 for (unsigned i : FilterEnds) {
835 unsigned j = TyIds.size();
Matthias Braun1520f7a2016-12-01 19:32:15 +0000836
837 while (i && j)
838 if (FilterIds[--i] != TyIds[--j])
839 goto try_next;
840
841 if (!j)
842 // The new filter coincides with range [i, end) of the existing filter.
843 return -(1 + i);
844
845try_next:;
846 }
847
848 // Add the new filter.
849 int FilterID = -(1 + FilterIds.size());
850 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
Kazu Hiratadfce3852020-12-28 19:55:16 -0800851 llvm::append_range(FilterIds, TyIds);
Matthias Braun1520f7a2016-12-01 19:32:15 +0000852 FilterEnds.push_back(FilterIds.size());
853 FilterIds.push_back(0); // terminator
854 return FilterID;
855}
856
Reid Kleckner2f271892019-11-13 15:33:12 -0800857MachineFunction::CallSiteInfoMap::iterator
858MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
Djordje Todoroviceef604de2020-02-10 09:49:14 +0100859 assert(MI->isCandidateForCallSiteEntry() &&
860 "Call site info refers only to call (MI) candidates");
Djordje Todorovicc60bf152020-02-20 13:43:01 +0100861
Djordje Todorovic7caa8252020-03-09 11:02:35 +0100862 if (!Target.Options.EmitCallSiteInfo)
Reid Kleckner2f271892019-11-13 15:33:12 -0800863 return CallSitesInfo.end();
864 return CallSitesInfo.find(MI);
865}
866
Djordje Todorovic90818832020-02-27 11:44:53 +0100867/// Return the call machine instruction or find a call within bundle.
868static const MachineInstr *getCallInstr(const MachineInstr *MI) {
869 if (!MI->isBundle())
870 return MI;
Djordje Todoroviceef604de2020-02-10 09:49:14 +0100871
Kazu Hirata6219a472022-07-17 01:33:28 -0700872 for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
873 getBundleEnd(MI->getIterator())))
Djordje Todorovic90818832020-02-27 11:44:53 +0100874 if (BMI.isCandidateForCallSiteEntry())
875 return &BMI;
Djordje Todorovicb4e1c252019-06-27 13:10:29 +0000876
Djordje Todorovic90818832020-02-27 11:44:53 +0100877 llvm_unreachable("Unexpected bundle without a call site candidate");
Nikola Prica3c33bf72019-10-08 15:43:12 +0000878}
879
880void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
Djordje Todorovic90818832020-02-27 11:44:53 +0100881 assert(MI->shouldUpdateCallSiteInfo() &&
882 "Call site info refers only to call (MI) candidates or "
883 "candidates inside bundles");
884
885 const MachineInstr *CallMI = getCallInstr(MI);
886 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
Nikola Prica3c33bf72019-10-08 15:43:12 +0000887 if (CSIt == CallSitesInfo.end())
888 return;
889 CallSitesInfo.erase(CSIt);
890}
891
892void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
893 const MachineInstr *New) {
Djordje Todorovic90818832020-02-27 11:44:53 +0100894 assert(Old->shouldUpdateCallSiteInfo() &&
895 "Call site info refers only to call (MI) candidates or "
896 "candidates inside bundles");
Djordje Todoroviceef604de2020-02-10 09:49:14 +0100897
898 if (!New->isCandidateForCallSiteEntry())
899 return eraseCallSiteInfo(Old);
Nikola Prica3c33bf72019-10-08 15:43:12 +0000900
Djordje Todorovic90818832020-02-27 11:44:53 +0100901 const MachineInstr *OldCallMI = getCallInstr(Old);
902 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
Nikola Prica3c33bf72019-10-08 15:43:12 +0000903 if (CSIt == CallSitesInfo.end())
904 return;
905
906 CallSiteInfo CSInfo = CSIt->second;
907 CallSitesInfo[New] = CSInfo;
Djordje Todorovicb4e1c252019-06-27 13:10:29 +0000908}
909
Djordje Todorovic90818832020-02-27 11:44:53 +0100910void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
911 const MachineInstr *New) {
912 assert(Old->shouldUpdateCallSiteInfo() &&
913 "Call site info refers only to call (MI) candidates or "
914 "candidates inside bundles");
915
916 if (!New->isCandidateForCallSiteEntry())
917 return eraseCallSiteInfo(Old);
918
919 const MachineInstr *OldCallMI = getCallInstr(Old);
920 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
921 if (CSIt == CallSitesInfo.end())
922 return;
923
924 CallSiteInfo CSInfo = std::move(CSIt->second);
925 CallSitesInfo.erase(CSIt);
926 CallSitesInfo[New] = CSInfo;
927}
928
Jeremy Morsec3f1c282020-10-14 10:47:44 +0100929void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
930 DebugInstrNumberingCount = Num;
931}
932
Jeremy Morse3cfcd542020-10-15 11:20:29 +0100933void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
Jeremy Morse21b94182021-07-01 10:59:22 +0100934 DebugInstrOperandPair B,
935 unsigned Subreg) {
936 // Catch any accidental self-loops.
937 assert(A.first != B.first);
Jeremy Morsea4f93742021-10-25 15:09:42 +0100938 // Don't allow any substitutions _from_ the memory operand number.
939 assert(A.second != DebugOperandMemNumber);
940
Jeremy Morse4af1bec2021-07-09 15:32:30 +0100941 DebugValueSubstitutions.push_back({A, B, Subreg});
Jeremy Morse3cfcd542020-10-15 11:20:29 +0100942}
943
944void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
Jeremy Morse06e15d02020-10-21 14:28:28 +0100945 MachineInstr &New,
946 unsigned MaxOperand) {
Jeremy Morse3cfcd542020-10-15 11:20:29 +0100947 // If the Old instruction wasn't tracked at all, there is no work to do.
948 unsigned OldInstrNum = Old.peekDebugInstrNum();
949 if (!OldInstrNum)
950 return;
951
952 // Iterate over all operands looking for defs to create substitutions for.
953 // Avoid creating new instr numbers unless we create a new substitution.
954 // While this has no functional effect, it risks confusing someone reading
955 // MIR output.
Jeremy Morse06e15d02020-10-21 14:28:28 +0100956 // Examine all the operands, or the first N specified by the caller.
957 MaxOperand = std::min(MaxOperand, Old.getNumOperands());
Jeremy Morse9aaf24c2021-07-20 10:43:21 +0100958 for (unsigned int I = 0; I < MaxOperand; ++I) {
Jeremy Morse3cfcd542020-10-15 11:20:29 +0100959 const auto &OldMO = Old.getOperand(I);
Jeremy Morse06e15d02020-10-21 14:28:28 +0100960 auto &NewMO = New.getOperand(I);
961 (void)NewMO;
Jeremy Morse3cfcd542020-10-15 11:20:29 +0100962
963 if (!OldMO.isReg() || !OldMO.isDef())
964 continue;
Jeremy Morse06e15d02020-10-21 14:28:28 +0100965 assert(NewMO.isDef());
Jeremy Morse3cfcd542020-10-15 11:20:29 +0100966
967 unsigned NewInstrNum = New.getDebugInstrNum();
968 makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
969 std::make_pair(NewInstrNum, I));
970 }
971}
972
Jeremy Morsee11d27e2022-05-03 09:42:27 +0100973auto MachineFunction::salvageCopySSA(
974 MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
975 -> DebugInstrOperandPair {
976 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
977
978 // Check whether this copy-like instruction has already been salvaged into
979 // an operand pair.
980 Register Dest;
981 if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
982 Dest = CopyDstSrc->Destination->getReg();
983 } else {
984 assert(MI.isSubregToReg());
985 Dest = MI.getOperand(0).getReg();
986 }
987
988 auto CacheIt = DbgPHICache.find(Dest);
989 if (CacheIt != DbgPHICache.end())
990 return CacheIt->second;
991
992 // Calculate the instruction number to use, or install a DBG_PHI.
993 auto OperandPair = salvageCopySSAImpl(MI);
994 DbgPHICache.insert({Dest, OperandPair});
995 return OperandPair;
996}
997
998auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
Jeremy Morseb9133962021-06-02 15:14:37 +0100999 -> DebugInstrOperandPair {
1000 MachineRegisterInfo &MRI = getRegInfo();
1001 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1002 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1003
1004 // Chase the value read by a copy-like instruction back to the instruction
1005 // that ultimately _defines_ that value. This may pass:
1006 // * Through multiple intermediate copies, including subregister moves /
1007 // copies,
1008 // * Copies from physical registers that must then be traced back to the
1009 // defining instruction,
1010 // * Or, physical registers may be live-in to (only) the entry block, which
1011 // requires a DBG_PHI to be created.
1012 // We can pursue this problem in that order: trace back through copies,
1013 // optionally through a physical register, to a defining instruction. We
1014 // should never move from physreg to vreg. As we're still in SSA form, no need
1015 // to worry about partial definitions of registers.
1016
1017 // Helper lambda to interpret a copy-like instruction. Takes instruction,
1018 // returns the register read and any subregister identifying which part is
1019 // read.
1020 auto GetRegAndSubreg =
1021 [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1022 Register NewReg, OldReg;
1023 unsigned SubReg;
1024 if (Cpy.isCopy()) {
1025 OldReg = Cpy.getOperand(0).getReg();
1026 NewReg = Cpy.getOperand(1).getReg();
1027 SubReg = Cpy.getOperand(1).getSubReg();
1028 } else if (Cpy.isSubregToReg()) {
1029 OldReg = Cpy.getOperand(0).getReg();
1030 NewReg = Cpy.getOperand(2).getReg();
1031 SubReg = Cpy.getOperand(3).getImm();
1032 } else {
1033 auto CopyDetails = *TII.isCopyInstr(Cpy);
1034 const MachineOperand &Src = *CopyDetails.Source;
1035 const MachineOperand &Dest = *CopyDetails.Destination;
1036 OldReg = Dest.getReg();
1037 NewReg = Src.getReg();
1038 SubReg = Src.getSubReg();
1039 }
1040
1041 return {NewReg, SubReg};
1042 };
1043
1044 // First seek either the defining instruction, or a copy from a physreg.
1045 // During search, the current state is the current copy instruction, and which
1046 // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1047 // deal with those later.
1048 auto State = GetRegAndSubreg(MI);
1049 auto CurInst = MI.getIterator();
1050 SmallVector<unsigned, 4> SubregsSeen;
1051 while (true) {
1052 // If we've found a copy from a physreg, first portion of search is over.
1053 if (!State.first.isVirtual())
1054 break;
1055
1056 // Record any subregister qualifier.
1057 if (State.second)
1058 SubregsSeen.push_back(State.second);
1059
1060 assert(MRI.hasOneDef(State.first));
1061 MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1062 CurInst = Inst.getIterator();
1063
1064 // Any non-copy instruction is the defining instruction we're seeking.
1065 if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1066 break;
1067 State = GetRegAndSubreg(Inst);
1068 };
1069
1070 // Helper lambda to apply additional subregister substitutions to a known
1071 // instruction/operand pair. Adds new (fake) substitutions so that we can
1072 // record the subregister. FIXME: this isn't very space efficient if multiple
1073 // values are tracked back through the same copies; cache something later.
1074 auto ApplySubregisters =
1075 [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1076 for (unsigned Subreg : reverse(SubregsSeen)) {
1077 // Fetch a new instruction number, not attached to an actual instruction.
1078 unsigned NewInstrNumber = getNewDebugInstrNum();
1079 // Add a substitution from the "new" number to the known one, with a
1080 // qualifying subreg.
1081 makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1082 // Return the new number; to find the underlying value, consumers need to
1083 // deal with the qualifying subreg.
1084 P = {NewInstrNumber, 0};
1085 }
1086 return P;
1087 };
1088
1089 // If we managed to find the defining instruction after COPYs, return an
1090 // instruction / operand pair after adding subregister qualifiers.
1091 if (State.first.isVirtual()) {
1092 // Virtual register def -- we can just look up where this happens.
1093 MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
Jay Foad9d725662023-05-24 14:57:23 +01001094 for (auto &MO : Inst->all_defs()) {
1095 if (MO.getReg() != State.first)
Jeremy Morseb9133962021-06-02 15:14:37 +01001096 continue;
Jay Foad6501ea02023-02-03 09:42:25 +00001097 return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
Jeremy Morseb9133962021-06-02 15:14:37 +01001098 }
1099
1100 llvm_unreachable("Vreg def with no corresponding operand?");
1101 }
1102
1103 // Our search ended in a copy from a physreg: walk back up the function
1104 // looking for whatever defines the physreg.
1105 assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1106 State = GetRegAndSubreg(*CurInst);
1107 Register RegToSeek = State.first;
1108
1109 auto RMII = CurInst->getReverseIterator();
1110 auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1111 for (auto &ToExamine : PrevInstrs) {
Jay Foad9d725662023-05-24 14:57:23 +01001112 for (auto &MO : ToExamine.all_defs()) {
Jeremy Morseb9133962021-06-02 15:14:37 +01001113 // Test for operand that defines something aliasing RegToSeek.
Jay Foad9d725662023-05-24 14:57:23 +01001114 if (!TRI.regsOverlap(RegToSeek, MO.getReg()))
Jeremy Morseb9133962021-06-02 15:14:37 +01001115 continue;
1116
1117 return ApplySubregisters(
Jay Foad6501ea02023-02-03 09:42:25 +00001118 {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
Jeremy Morseb9133962021-06-02 15:14:37 +01001119 }
1120 }
1121
Jeremy Morse1f977452021-07-26 15:00:08 +01001122 MachineBasicBlock &InsertBB = *CurInst->getParent();
1123
Jeremy Morseb9133962021-06-02 15:14:37 +01001124 // We reached the start of the block before finding a defining instruction.
Jeremy Morsea5cf4652022-03-04 16:39:22 +00001125 // There are numerous scenarios where this can happen:
1126 // * Constant physical registers,
1127 // * Several intrinsics that allow LLVM-IR to read arbitary registers,
1128 // * Arguments in the entry block,
1129 // * Exception handling landing pads.
1130 // Validating all of them is too difficult, so just insert a DBG_PHI reading
1131 // the variable value at this position, rather than checking it makes sense.
Jeremy Morseb9133962021-06-02 15:14:37 +01001132
1133 // Create DBG_PHI for specified physreg.
Jeremy Morse1f977452021-07-26 15:00:08 +01001134 auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
Jeremy Morseb9133962021-06-02 15:14:37 +01001135 TII.get(TargetOpcode::DBG_PHI));
Jack Andersen67d96562021-10-07 16:02:30 +01001136 Builder.addReg(State.first);
Jeremy Morseb9133962021-06-02 15:14:37 +01001137 unsigned NewNum = getNewDebugInstrNum();
1138 Builder.addImm(NewNum);
1139 return ApplySubregisters({NewNum, 0u});
1140}
1141
1142void MachineFunction::finalizeDebugInstrRefs() {
1143 auto *TII = getSubtarget().getInstrInfo();
1144
Jeremy Morse66998b32021-11-24 10:20:03 +00001145 auto MakeUndefDbgValue = [&](MachineInstr &MI) {
Stephen Tozer307857a2022-09-15 11:26:57 +01001146 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
Jeremy Morseb9133962021-06-02 15:14:37 +01001147 MI.setDesc(RefII);
Stephen Tozer64c93c92023-01-03 18:13:31 +00001148 MI.setDebugValueUndef();
Jeremy Morseb9133962021-06-02 15:14:37 +01001149 };
1150
Jeremy Morsee11d27e2022-05-03 09:42:27 +01001151 DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
Jeremy Morseb9133962021-06-02 15:14:37 +01001152 for (auto &MBB : *this) {
1153 for (auto &MI : MBB) {
Stephen Tozer64c93c92023-01-03 18:13:31 +00001154 if (!MI.isDebugRef())
Jeremy Morseb9133962021-06-02 15:14:37 +01001155 continue;
1156
Stephen Tozer64c93c92023-01-03 18:13:31 +00001157 bool IsValidRef = true;
Jeremy Morseb9133962021-06-02 15:14:37 +01001158
Stephen Tozer64c93c92023-01-03 18:13:31 +00001159 for (MachineOperand &MO : MI.debug_operands()) {
1160 if (!MO.isReg())
1161 continue;
Jeremy Morseb9133962021-06-02 15:14:37 +01001162
Stephen Tozer64c93c92023-01-03 18:13:31 +00001163 Register Reg = MO.getReg();
Jeremy Morseb9133962021-06-02 15:14:37 +01001164
Stephen Tozer64c93c92023-01-03 18:13:31 +00001165 // Some vregs can be deleted as redundant in the meantime. Mark those
1166 // as DBG_VALUE $noreg. Additionally, some normal instructions are
1167 // quickly deleted, leaving dangling references to vregs with no def.
1168 if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1169 IsValidRef = false;
1170 break;
Jeremy Morseb9133962021-06-02 15:14:37 +01001171 }
Jeremy Morseb9133962021-06-02 15:14:37 +01001172
Stephen Tozer64c93c92023-01-03 18:13:31 +00001173 assert(Reg.isVirtual());
1174 MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1175
1176 // If we've found a copy-like instruction, follow it back to the
1177 // instruction that defines the source value, see salvageCopySSA docs
1178 // for why this is important.
1179 if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1180 auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1181 MO.ChangeToDbgInstrRef(Result.first, Result.second);
1182 } else {
1183 // Otherwise, identify the operand number that the VReg refers to.
1184 unsigned OperandIdx = 0;
1185 for (const auto &DefMO : DefMI.operands()) {
1186 if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1187 break;
1188 ++OperandIdx;
1189 }
1190 assert(OperandIdx < DefMI.getNumOperands());
1191
1192 // Morph this instr ref to point at the given instruction and operand.
1193 unsigned ID = DefMI.getDebugInstrNum();
1194 MO.ChangeToDbgInstrRef(ID, OperandIdx);
1195 }
Jeremy Morseb9133962021-06-02 15:14:37 +01001196 }
Stephen Tozer64c93c92023-01-03 18:13:31 +00001197
1198 if (!IsValidRef)
1199 MakeUndefDbgValue(MI);
Jeremy Morseb9133962021-06-02 15:14:37 +01001200 }
1201 }
1202}
1203
Jeremy Morsed0f58ba2023-01-20 14:14:39 +00001204bool MachineFunction::shouldUseDebugInstrRef() const {
Jeremy Morse97b88782021-08-25 14:56:05 +01001205 // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1206 // have optimized code inlined into this unoptimized code, however with
1207 // fewer and less aggressive optimizations happening, coverage and accuracy
1208 // should not suffer.
Arthur Eubanks254c2e52023-09-14 14:10:14 -07001209 if (getTarget().getOptLevel() == CodeGenOptLevel::None)
Jeremy Morse97b88782021-08-25 14:56:05 +01001210 return false;
1211
1212 // Don't use instr-ref if this function is marked optnone.
1213 if (F.hasFnAttribute(Attribute::OptimizeNone))
1214 return false;
1215
Jeremy Morse55507042022-01-12 12:35:36 +00001216 if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
Jeremy Morse97b88782021-08-25 14:56:05 +01001217 return true;
1218
1219 return false;
1220}
1221
Jeremy Morsed0f58ba2023-01-20 14:14:39 +00001222bool MachineFunction::useDebugInstrRef() const {
1223 return UseDebugInstrRef;
1224}
1225
1226void MachineFunction::setUseDebugInstrRef(bool Use) {
1227 UseDebugInstrRef = Use;
1228}
1229
Jeremy Morsea4f93742021-10-25 15:09:42 +01001230// Use one million as a high / reserved number.
1231const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1232
Matthias Braun1520f7a2016-12-01 19:32:15 +00001233/// \}
1234
Chris Lattner5b841ff2002-12-28 20:37:16 +00001235//===----------------------------------------------------------------------===//
Nate Begeman83e5f082006-04-22 18:53:45 +00001236// MachineJumpTableInfo implementation
1237//===----------------------------------------------------------------------===//
1238
Sanjay Patela3bab492015-06-13 15:32:45 +00001239/// Return the size of each entry in the jump table.
Micah Villmowfda694e2012-10-08 16:38:25 +00001240unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
Chris Lattner5b5cc062010-01-25 23:26:13 +00001241 // The size of a jump table entry is 4 bytes unless the entry is just the
1242 // address of a block, in which case it is the pointer size.
1243 switch (getEntryKind()) {
1244 case MachineJumpTableInfo::EK_BlockAddress:
Chandler Carruth58934882012-11-01 09:14:31 +00001245 return TD.getPointerSize();
Akira Hatanakafd156ff2012-02-03 04:33:00 +00001246 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
Arthur Eubanks695e0182023-08-31 10:13:20 -07001247 case MachineJumpTableInfo::EK_LabelDifference64:
Akira Hatanakafd156ff2012-02-03 04:33:00 +00001248 return 8;
Chris Lattner5b5cc062010-01-25 23:26:13 +00001249 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1250 case MachineJumpTableInfo::EK_LabelDifference32:
Chris Lattner0d82d762010-01-26 04:05:28 +00001251 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner5b5cc062010-01-25 23:26:13 +00001252 return 4;
Richard Osbornece2762c2010-03-11 14:58:16 +00001253 case MachineJumpTableInfo::EK_Inline:
1254 return 0;
Chris Lattner5b5cc062010-01-25 23:26:13 +00001255 }
Craig Toppere8a18f32012-02-06 08:17:43 +00001256 llvm_unreachable("Unknown jump table encoding!");
Chris Lattner5b5cc062010-01-25 23:26:13 +00001257}
1258
Sanjay Patela3bab492015-06-13 15:32:45 +00001259/// Return the alignment of each entry in the jump table.
Micah Villmowfda694e2012-10-08 16:38:25 +00001260unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
Chris Lattner5b5cc062010-01-25 23:26:13 +00001261 // The alignment of a jump table entry is the alignment of int32 unless the
1262 // entry is just the address of a block, in which case it is the pointer
1263 // alignment.
1264 switch (getEntryKind()) {
1265 case MachineJumpTableInfo::EK_BlockAddress:
Guillaume Chateletc5dbe672019-09-23 12:41:36 +00001266 return TD.getPointerABIAlignment(0).value();
Akira Hatanakafd156ff2012-02-03 04:33:00 +00001267 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
Arthur Eubanks695e0182023-08-31 10:13:20 -07001268 case MachineJumpTableInfo::EK_LabelDifference64:
Guillaume Chateletc5dbe672019-09-23 12:41:36 +00001269 return TD.getABIIntegerTypeAlignment(64).value();
Chris Lattner5b5cc062010-01-25 23:26:13 +00001270 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1271 case MachineJumpTableInfo::EK_LabelDifference32:
Chris Lattner0d82d762010-01-26 04:05:28 +00001272 case MachineJumpTableInfo::EK_Custom32:
Guillaume Chateletc5dbe672019-09-23 12:41:36 +00001273 return TD.getABIIntegerTypeAlignment(32).value();
Richard Osbornece2762c2010-03-11 14:58:16 +00001274 case MachineJumpTableInfo::EK_Inline:
1275 return 1;
Chris Lattner5b5cc062010-01-25 23:26:13 +00001276 }
Craig Toppere8a18f32012-02-06 08:17:43 +00001277 llvm_unreachable("Unknown jump table encoding!");
Chris Lattner5b5cc062010-01-25 23:26:13 +00001278}
1279
Sanjay Patela3bab492015-06-13 15:32:45 +00001280/// Create a new jump table entry in the jump table info.
Bob Wilsonab8df3d2010-03-18 18:42:41 +00001281unsigned MachineJumpTableInfo::createJumpTableIndex(
Chris Lattner0b91ab92006-10-28 18:17:09 +00001282 const std::vector<MachineBasicBlock*> &DestBBs) {
Chris Lattnercbe53df2006-10-28 18:11:20 +00001283 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
Nate Begeman83e5f082006-04-22 18:53:45 +00001284 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1285 return JumpTables.size()-1;
1286}
1287
Sanjay Patela3bab492015-06-13 15:32:45 +00001288/// If Old is the target of any jump tables, update the jump tables to branch
1289/// to New instead.
Chris Lattner80a68492010-01-26 05:58:28 +00001290bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1291 MachineBasicBlock *New) {
Dan Gohman557b3912009-04-15 01:18:49 +00001292 assert(Old != New && "Not making a change?");
1293 bool MadeChange = false;
Jim Grosbach5df06252009-11-14 20:09:13 +00001294 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1295 ReplaceMBBInJumpTable(i, Old, New);
1296 return MadeChange;
1297}
1298
Victor Huang347c4612020-11-16 10:33:06 -06001299/// If MBB is present in any jump tables, remove it.
1300bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1301 bool MadeChange = false;
1302 for (MachineJumpTableEntry &JTE : JumpTables) {
1303 auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1304 MadeChange |= (removeBeginItr != JTE.MBBs.end());
1305 JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1306 }
1307 return MadeChange;
1308}
1309
Sanjay Patela3bab492015-06-13 15:32:45 +00001310/// If Old is a target of the jump tables, update the jump table to branch to
1311/// New instead.
Chris Lattner80a68492010-01-26 05:58:28 +00001312bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1313 MachineBasicBlock *Old,
1314 MachineBasicBlock *New) {
Jim Grosbach5df06252009-11-14 20:09:13 +00001315 assert(Old != New && "Not making a change?");
1316 bool MadeChange = false;
1317 MachineJumpTableEntry &JTE = JumpTables[Idx];
Kazu Hirata74d9b882021-11-22 20:33:27 -08001318 for (MachineBasicBlock *&MBB : JTE.MBBs)
1319 if (MBB == Old) {
1320 MBB = New;
Jim Grosbach5df06252009-11-14 20:09:13 +00001321 MadeChange = true;
1322 }
Dan Gohman557b3912009-04-15 01:18:49 +00001323 return MadeChange;
1324}
Nate Begeman83e5f082006-04-22 18:53:45 +00001325
Chris Lattnerb1d55db2009-08-23 01:12:47 +00001326void MachineJumpTableInfo::print(raw_ostream &OS) const {
Dan Gohman89871b62009-10-31 20:19:03 +00001327 if (JumpTables.empty()) return;
1328
1329 OS << "Jump Tables:\n";
1330
Nate Begeman83e5f082006-04-22 18:53:45 +00001331 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
Evandro Menezes5a515cd2019-06-26 15:11:31 +00001332 OS << printJumpTableEntryReference(i) << ':';
Kazu Hirata74d9b882021-11-22 20:33:27 -08001333 for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
1334 OS << ' ' << printMBBReference(*MBB);
Evandro Menezes5a515cd2019-06-26 15:11:31 +00001335 if (i != e)
1336 OS << '\n';
Nate Begeman83e5f082006-04-22 18:53:45 +00001337 }
Dan Gohman89871b62009-10-31 20:19:03 +00001338
1339 OS << '\n';
Nate Begeman83e5f082006-04-22 18:53:45 +00001340}
1341
Aaron Ballman7fced3f2017-10-15 14:32:27 +00001342#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Keren33afa9a2016-01-29 20:50:44 +00001343LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
Manman Ren4f061be2012-09-06 19:06:06 +00001344#endif
Nate Begeman83e5f082006-04-22 18:53:45 +00001345
Francis Visoiu Mistrih45acd392017-12-13 10:30:59 +00001346Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1347 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1348}
1349
Nate Begeman83e5f082006-04-22 18:53:45 +00001350//===----------------------------------------------------------------------===//
Chris Lattnere1511612003-01-13 00:23:03 +00001351// MachineConstantPool implementation
1352//===----------------------------------------------------------------------===//
1353
Eugene Zelenko9375b782017-10-10 22:33:29 +00001354void MachineConstantPoolValue::anchor() {}
David Blaikiecd738cc2011-12-20 02:50:00 +00001355
QingShan Zhang778a9002021-01-05 03:22:45 +00001356unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1357 return DL.getTypeAllocSize(Ty);
1358}
1359
1360unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
Evan Cheng1c500432006-09-14 05:50:57 +00001361 if (isMachineConstantPoolEntry())
QingShan Zhang778a9002021-01-05 03:22:45 +00001362 return Val.MachineCPVal->getSizeInBytes(DL);
1363 return DL.getTypeAllocSize(Val.ConstVal->getType());
Evan Cheng1c500432006-09-14 05:50:57 +00001364}
1365
Rafael Espindola1a213e42015-11-17 00:51:23 +00001366bool MachineConstantPoolEntry::needsRelocation() const {
Chris Lattnera0453a92009-07-21 23:34:23 +00001367 if (isMachineConstantPoolEntry())
Rafael Espindola1a213e42015-11-17 00:51:23 +00001368 return true;
Leonard Chan1719ae62021-02-10 09:59:36 -08001369 return Val.ConstVal->needsDynamicRelocation();
Chris Lattnera0453a92009-07-21 23:34:23 +00001370}
1371
David Majnemerb0a4e782014-07-14 22:06:29 +00001372SectionKind
1373MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
Rafael Espindola1a213e42015-11-17 00:51:23 +00001374 if (needsRelocation())
1375 return SectionKind::getReadOnlyWithRel();
QingShan Zhang778a9002021-01-05 03:22:45 +00001376 switch (getSizeInBytes(*DL)) {
Rafael Espindola1a213e42015-11-17 00:51:23 +00001377 case 4:
1378 return SectionKind::getMergeableConst4();
1379 case 8:
1380 return SectionKind::getMergeableConst8();
1381 case 16:
1382 return SectionKind::getMergeableConst16();
David Majnemer125c7bf2016-02-22 22:23:11 +00001383 case 32:
1384 return SectionKind::getMergeableConst32();
David Majnemerb0a4e782014-07-14 22:06:29 +00001385 default:
Rafael Espindola1a213e42015-11-17 00:51:23 +00001386 return SectionKind::getReadOnly();
David Majnemerb0a4e782014-07-14 22:06:29 +00001387 }
David Majnemerb0a4e782014-07-14 22:06:29 +00001388}
1389
Evan Chengbb4b58c2006-09-12 21:00:35 +00001390MachineConstantPool::~MachineConstantPool() {
James Molloy5dbdef82016-09-26 07:26:24 +00001391 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1392 // so keep track of which we've deleted to avoid double deletions.
1393 DenseSet<MachineConstantPoolValue*> Deleted;
Kazu Hirata655998b2021-12-04 08:48:04 -08001394 for (const MachineConstantPoolEntry &C : Constants)
1395 if (C.isMachineConstantPoolEntry()) {
1396 Deleted.insert(C.Val.MachineCPVal);
1397 delete C.Val.MachineCPVal;
James Molloy5dbdef82016-09-26 07:26:24 +00001398 }
Kazu Hirata44969dc2021-02-15 14:46:10 -08001399 for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1400 if (Deleted.count(CPV) == 0)
1401 delete CPV;
James Molloy5dbdef82016-09-26 07:26:24 +00001402 }
Evan Chengbb4b58c2006-09-12 21:00:35 +00001403}
1404
Sanjay Patela3bab492015-06-13 15:32:45 +00001405/// Test whether the given two constants can be allocated the same constant pool
Simon Pilgrim96e646d2023-06-13 10:15:02 +01001406/// entry referenced by \param A.
Dan Gohman90cad462010-04-15 01:51:59 +00001407static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
Mehdi Aminic0a24f62015-07-07 18:20:57 +00001408 const DataLayout &DL) {
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001409 // Handle the trivial case quickly.
1410 if (A == B) return true;
1411
1412 // If they have the same type but weren't the same constant, quickly
1413 // reject them.
1414 if (A->getType() == B->getType()) return false;
1415
Chris Lattner5c0ff072012-01-27 01:46:00 +00001416 // We can't handle structs or arrays.
1417 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1418 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1419 return false;
NAKAMURA Takumie82ebbb2014-06-25 12:40:56 +00001420
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001421 // For now, only support constants with the same size.
Mehdi Aminic0a24f62015-07-07 18:20:57 +00001422 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1423 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001424 return false;
1425
Simon Pilgrim96e646d2023-06-13 10:15:02 +01001426 bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
1427
Chris Lattner5c0ff072012-01-27 01:46:00 +00001428 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001429
Chris Lattner5c0ff072012-01-27 01:46:00 +00001430 // Try constant folding a bitcast of both instructions to an integer. If we
1431 // get two identical ConstantInt's, then we are good to share them. We use
1432 // the constant folding APIs to do this so that we get the benefit of
Micah Villmowfda694e2012-10-08 16:38:25 +00001433 // DataLayout.
Chris Lattner5c0ff072012-01-27 01:46:00 +00001434 if (isa<PointerType>(A->getType()))
Manuel Jacob56d03132016-01-21 06:31:08 +00001435 A = ConstantFoldCastOperand(Instruction::PtrToInt,
1436 const_cast<Constant *>(A), IntTy, DL);
Chris Lattner5c0ff072012-01-27 01:46:00 +00001437 else if (A->getType() != IntTy)
Manuel Jacob56d03132016-01-21 06:31:08 +00001438 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1439 IntTy, DL);
Chris Lattner5c0ff072012-01-27 01:46:00 +00001440 if (isa<PointerType>(B->getType()))
Manuel Jacob56d03132016-01-21 06:31:08 +00001441 B = ConstantFoldCastOperand(Instruction::PtrToInt,
1442 const_cast<Constant *>(B), IntTy, DL);
Chris Lattner5c0ff072012-01-27 01:46:00 +00001443 else if (B->getType() != IntTy)
Manuel Jacob56d03132016-01-21 06:31:08 +00001444 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1445 IntTy, DL);
Chad Rosierbe02a0a2012-06-19 23:37:57 +00001446
Simon Pilgrim96e646d2023-06-13 10:15:02 +01001447 if (A != B)
1448 return false;
1449
1450 // Constants only safely match if A doesn't contain undef/poison.
1451 // As we'll be reusing A, it doesn't matter if B contain undef/poison.
1452 // TODO: Handle cases where A and B have the same undef/poison elements.
1453 // TODO: Merge A and B with mismatching undef/poison elements.
1454 return !ContainsUndefOrPoisonA;
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001455}
1456
Sanjay Patela3bab492015-06-13 15:32:45 +00001457/// Create a new entry in the constant pool or return an existing one.
1458/// User must specify the log2 of the minimum required alignment for the object.
NAKAMURA Takumie82ebbb2014-06-25 12:40:56 +00001459unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
Craig Topper3b2c9952020-05-12 09:43:24 -07001460 Align Alignment) {
Chris Lattneree31d0d2006-02-09 04:46:04 +00001461 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001462
Chris Lattneree31d0d2006-02-09 04:46:04 +00001463 // Check to see if we already have this constant.
1464 //
1465 // FIXME, this could be made much more efficient for large constant pools.
Chris Lattneree31d0d2006-02-09 04:46:04 +00001466 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001467 if (!Constants[i].isMachineConstantPoolEntry() &&
Mehdi Aminic0a24f62015-07-07 18:20:57 +00001468 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
Craig Topper3b2c9952020-05-12 09:43:24 -07001469 if (Constants[i].getAlign() < Alignment)
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001470 Constants[i].Alignment = Alignment;
Chris Lattneree31d0d2006-02-09 04:46:04 +00001471 return i;
Dan Gohman8d4ffb32009-10-28 01:12:16 +00001472 }
Chad Rosierbe02a0a2012-06-19 23:37:57 +00001473
Evan Cheng24d890f2009-03-13 07:51:59 +00001474 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
Chris Lattneree31d0d2006-02-09 04:46:04 +00001475 return Constants.size()-1;
1476}
1477
Evan Chengbb4b58c2006-09-12 21:00:35 +00001478unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
Craig Topper3b2c9952020-05-12 09:43:24 -07001479 Align Alignment) {
Evan Chengbb4b58c2006-09-12 21:00:35 +00001480 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
Chad Rosierbe02a0a2012-06-19 23:37:57 +00001481
Evan Chengbb4b58c2006-09-12 21:00:35 +00001482 // Check to see if we already have this constant.
1483 //
1484 // FIXME, this could be made much more efficient for large constant pools.
Evan Chengbb4b58c2006-09-12 21:00:35 +00001485 int Idx = V->getExistingMachineCPValue(this, Alignment);
Cameron Zwarich9d2cc5d2011-02-22 08:54:30 +00001486 if (Idx != -1) {
1487 MachineCPVsSharingEntries.insert(V);
Evan Chengbb4b58c2006-09-12 21:00:35 +00001488 return (unsigned)Idx;
Cameron Zwarich9d2cc5d2011-02-22 08:54:30 +00001489 }
Evan Cheng24d890f2009-03-13 07:51:59 +00001490
1491 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
Evan Chengbb4b58c2006-09-12 21:00:35 +00001492 return Constants.size()-1;
1493}
1494
Chris Lattnerfd02f772008-08-23 22:53:13 +00001495void MachineConstantPool::print(raw_ostream &OS) const {
Dan Gohman89871b62009-10-31 20:19:03 +00001496 if (Constants.empty()) return;
1497
1498 OS << "Constant Pool:\n";
Evan Cheng10570502006-01-31 22:23:14 +00001499 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Dan Gohman89871b62009-10-31 20:19:03 +00001500 OS << " cp#" << i << ": ";
Evan Chengbb4b58c2006-09-12 21:00:35 +00001501 if (Constants[i].isMachineConstantPoolEntry())
1502 Constants[i].Val.MachineCPVal->print(OS);
1503 else
Chandler Carruthe6948282014-01-09 02:29:41 +00001504 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
Craig Topper3b2c9952020-05-12 09:43:24 -07001505 OS << ", align=" << Constants[i].getAlign().value();
Evan Cheng10570502006-01-31 22:23:14 +00001506 OS << "\n";
1507 }
Chris Lattnere1511612003-01-13 00:23:03 +00001508}
1509
Han Shenc5e85272023-06-28 22:18:53 -07001510//===----------------------------------------------------------------------===//
1511// Template specialization for MachineFunction implementation of
1512// ProfileSummaryInfo::getEntryCount().
1513//===----------------------------------------------------------------------===//
1514template <>
1515std::optional<Function::ProfileCount>
1516ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
1517 const llvm::MachineFunction *F) const {
1518 return F->getFunction().getEntryCount();
1519}
1520
Aaron Ballman7fced3f2017-10-15 14:32:27 +00001521#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Keren33afa9a2016-01-29 20:50:44 +00001522LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
Manman Ren4f061be2012-09-06 19:06:06 +00001523#endif