1*0b57cec5SDimitry Andric //===- MachineFunction.cpp ------------------------------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // Collect native machine code information for a function.  This allows
10*0b57cec5SDimitry Andric // target-specific information about the generated code to be stored with each
11*0b57cec5SDimitry Andric // function.
12*0b57cec5SDimitry Andric //
13*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14*0b57cec5SDimitry Andric 
15*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
23*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
24*0b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
25*0b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
26*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
27*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
28*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
30*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
31*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
32*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
33*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
34*0b57cec5SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
35*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
365ffd83dbSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
37*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
38*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
39*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
40*0b57cec5SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
41*0b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
42*0b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
44*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
46*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
47*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
48*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
49*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
50*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
51*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
54*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
55*0b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
56*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
57*0b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
58*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
59*0b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
60*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
61*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/DOTGraphTraits.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
66*0b57cec5SDimitry Andric #include "llvm/Support/GraphWriter.h"
67*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
68*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
69*0b57cec5SDimitry Andric #include <algorithm>
70*0b57cec5SDimitry Andric #include <cassert>
71*0b57cec5SDimitry Andric #include <cstddef>
72*0b57cec5SDimitry Andric #include <cstdint>
73*0b57cec5SDimitry Andric #include <iterator>
74*0b57cec5SDimitry Andric #include <string>
755ffd83dbSDimitry Andric #include <type_traits>
76*0b57cec5SDimitry Andric #include <utility>
77*0b57cec5SDimitry Andric #include <vector>
78*0b57cec5SDimitry Andric 
7904eeddc0SDimitry Andric #include "LiveDebugValues/LiveDebugValues.h"
8004eeddc0SDimitry Andric 
81*0b57cec5SDimitry Andric using namespace llvm;
82*0b57cec5SDimitry Andric 
83*0b57cec5SDimitry Andric #define DEBUG_TYPE "codegen"
84*0b57cec5SDimitry Andric 
858bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllFunctions(
868bcb0991SDimitry Andric     "align-all-functions",
878bcb0991SDimitry Andric     cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
888bcb0991SDimitry Andric              "means align on 16B boundaries)."),
89*0b57cec5SDimitry Andric     cl::init(0), cl::Hidden);
90*0b57cec5SDimitry Andric 
91*0b57cec5SDimitry Andric static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
92*0b57cec5SDimitry Andric   using P = MachineFunctionProperties::Property;
93*0b57cec5SDimitry Andric 
940eae32dcSDimitry Andric   // clang-format off
95*0b57cec5SDimitry Andric   switch(Prop) {
96*0b57cec5SDimitry Andric   case P::FailedISel: return "FailedISel";
97*0b57cec5SDimitry Andric   case P::IsSSA: return "IsSSA";
98*0b57cec5SDimitry Andric   case P::Legalized: return "Legalized";
99*0b57cec5SDimitry Andric   case P::NoPHIs: return "NoPHIs";
100*0b57cec5SDimitry Andric   case P::NoVRegs: return "NoVRegs";
101*0b57cec5SDimitry Andric   case P::RegBankSelected: return "RegBankSelected";
102*0b57cec5SDimitry Andric   case P::Selected: return "Selected";
103*0b57cec5SDimitry Andric   case P::TracksLiveness: return "TracksLiveness";
1045ffd83dbSDimitry Andric   case P::TiedOpsRewritten: return "TiedOpsRewritten";
105349cc55cSDimitry Andric   case P::FailsVerification: return "FailsVerification";
1060eae32dcSDimitry Andric   case P::TracksDebugUserValues: return "TracksDebugUserValues";
107*0b57cec5SDimitry Andric   }
1080eae32dcSDimitry Andric   // clang-format on
109*0b57cec5SDimitry Andric   llvm_unreachable("Invalid machine function property");
110*0b57cec5SDimitry Andric }
111*0b57cec5SDimitry Andric 
112*0b57cec5SDimitry Andric // Pin the vtable to this file.
113*0b57cec5SDimitry Andric void MachineFunction::Delegate::anchor() {}
114*0b57cec5SDimitry Andric 
115*0b57cec5SDimitry Andric void MachineFunctionProperties::print(raw_ostream &OS) const {
116*0b57cec5SDimitry Andric   const char *Separator = "";
117*0b57cec5SDimitry Andric   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
118*0b57cec5SDimitry Andric     if (!Properties[I])
119*0b57cec5SDimitry Andric       continue;
120*0b57cec5SDimitry Andric     OS << Separator << getPropertyName(static_cast<Property>(I));
121*0b57cec5SDimitry Andric     Separator = ", ";
122*0b57cec5SDimitry Andric   }
123*0b57cec5SDimitry Andric }
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
126*0b57cec5SDimitry Andric // MachineFunction implementation
127*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric // Out-of-line virtual method.
130*0b57cec5SDimitry Andric MachineFunctionInfo::~MachineFunctionInfo() = default;
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
1330eae32dcSDimitry Andric   MBB->getParent()->deleteMachineBasicBlock(MBB);
134*0b57cec5SDimitry Andric }
135*0b57cec5SDimitry Andric 
136*0b57cec5SDimitry Andric static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
137*0b57cec5SDimitry Andric                                            const Function &F) {
138349cc55cSDimitry Andric   if (auto MA = F.getFnStackAlign())
139349cc55cSDimitry Andric     return MA->value();
1405ffd83dbSDimitry Andric   return STI->getFrameLowering()->getStackAlign().value();
141*0b57cec5SDimitry Andric }
142*0b57cec5SDimitry Andric 
1435ffd83dbSDimitry Andric MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
144*0b57cec5SDimitry Andric                                  const TargetSubtargetInfo &STI,
145*0b57cec5SDimitry Andric                                  unsigned FunctionNum, MachineModuleInfo &mmi)
146*0b57cec5SDimitry Andric     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
147*0b57cec5SDimitry Andric   FunctionNumber = FunctionNum;
148*0b57cec5SDimitry Andric   init();
149*0b57cec5SDimitry Andric }
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric void MachineFunction::handleInsertion(MachineInstr &MI) {
152*0b57cec5SDimitry Andric   if (TheDelegate)
153*0b57cec5SDimitry Andric     TheDelegate->MF_HandleInsertion(MI);
154*0b57cec5SDimitry Andric }
155*0b57cec5SDimitry Andric 
156*0b57cec5SDimitry Andric void MachineFunction::handleRemoval(MachineInstr &MI) {
157*0b57cec5SDimitry Andric   if (TheDelegate)
158*0b57cec5SDimitry Andric     TheDelegate->MF_HandleRemoval(MI);
159*0b57cec5SDimitry Andric }
160*0b57cec5SDimitry Andric 
161*0b57cec5SDimitry Andric void MachineFunction::init() {
162*0b57cec5SDimitry Andric   // Assume the function starts in SSA form with correct liveness.
163*0b57cec5SDimitry Andric   Properties.set(MachineFunctionProperties::Property::IsSSA);
164*0b57cec5SDimitry Andric   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
165*0b57cec5SDimitry Andric   if (STI->getRegisterInfo())
166*0b57cec5SDimitry Andric     RegInfo = new (Allocator) MachineRegisterInfo(this);
167*0b57cec5SDimitry Andric   else
168*0b57cec5SDimitry Andric     RegInfo = nullptr;
169*0b57cec5SDimitry Andric 
170*0b57cec5SDimitry Andric   MFInfo = nullptr;
171*0b57cec5SDimitry Andric   // We can realign the stack if the target supports it and the user hasn't
172*0b57cec5SDimitry Andric   // explicitly asked us not to.
173*0b57cec5SDimitry Andric   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
174*0b57cec5SDimitry Andric                       !F.hasFnAttribute("no-realign-stack");
175*0b57cec5SDimitry Andric   FrameInfo = new (Allocator) MachineFrameInfo(
176*0b57cec5SDimitry Andric       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
177*0b57cec5SDimitry Andric       /*ForcedRealign=*/CanRealignSP &&
178*0b57cec5SDimitry Andric           F.hasFnAttribute(Attribute::StackAlignment));
179*0b57cec5SDimitry Andric 
180*0b57cec5SDimitry Andric   if (F.hasFnAttribute(Attribute::StackAlignment))
1815ffd83dbSDimitry Andric     FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
184*0b57cec5SDimitry Andric   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
185*0b57cec5SDimitry Andric 
186*0b57cec5SDimitry Andric   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
187*0b57cec5SDimitry Andric   // FIXME: Use Function::hasOptSize().
188*0b57cec5SDimitry Andric   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
189*0b57cec5SDimitry Andric     Alignment = std::max(Alignment,
190*0b57cec5SDimitry Andric                          STI->getTargetLowering()->getPrefFunctionAlignment());
191*0b57cec5SDimitry Andric 
192*0b57cec5SDimitry Andric   if (AlignAllFunctions)
1938bcb0991SDimitry Andric     Alignment = Align(1ULL << AlignAllFunctions);
194*0b57cec5SDimitry Andric 
195*0b57cec5SDimitry Andric   JumpTableInfo = nullptr;
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric   if (isFuncletEHPersonality(classifyEHPersonality(
198*0b57cec5SDimitry Andric           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
199*0b57cec5SDimitry Andric     WinEHInfo = new (Allocator) WinEHFuncInfo();
200*0b57cec5SDimitry Andric   }
201*0b57cec5SDimitry Andric 
202*0b57cec5SDimitry Andric   if (isScopedEHPersonality(classifyEHPersonality(
203*0b57cec5SDimitry Andric           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
204*0b57cec5SDimitry Andric     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
205*0b57cec5SDimitry Andric   }
206*0b57cec5SDimitry Andric 
207*0b57cec5SDimitry Andric   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
208*0b57cec5SDimitry Andric          "Can't create a MachineFunction using a Module with a "
209*0b57cec5SDimitry Andric          "Target-incompatible DataLayout attached\n");
210*0b57cec5SDimitry Andric 
211*0b57cec5SDimitry Andric   PSVManager =
2128bcb0991SDimitry Andric     std::make_unique<PseudoSourceValueManager>(*(getSubtarget().
213*0b57cec5SDimitry Andric                                                   getInstrInfo()));
214*0b57cec5SDimitry Andric }
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric MachineFunction::~MachineFunction() {
217*0b57cec5SDimitry Andric   clear();
218*0b57cec5SDimitry Andric }
219*0b57cec5SDimitry Andric 
220*0b57cec5SDimitry Andric void MachineFunction::clear() {
221*0b57cec5SDimitry Andric   Properties.reset();
222*0b57cec5SDimitry Andric   // Don't call destructors on MachineInstr and MachineOperand. All of their
223*0b57cec5SDimitry Andric   // memory comes from the BumpPtrAllocator which is about to be purged.
224*0b57cec5SDimitry Andric   //
225*0b57cec5SDimitry Andric   // Do call MachineBasicBlock destructors, it contains std::vectors.
226*0b57cec5SDimitry Andric   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
227*0b57cec5SDimitry Andric     I->Insts.clearAndLeakNodesUnsafely();
228*0b57cec5SDimitry Andric   MBBNumbering.clear();
229*0b57cec5SDimitry Andric 
230*0b57cec5SDimitry Andric   InstructionRecycler.clear(Allocator);
231*0b57cec5SDimitry Andric   OperandRecycler.clear(Allocator);
232*0b57cec5SDimitry Andric   BasicBlockRecycler.clear(Allocator);
233*0b57cec5SDimitry Andric   CodeViewAnnotations.clear();
234*0b57cec5SDimitry Andric   VariableDbgInfos.clear();
235*0b57cec5SDimitry Andric   if (RegInfo) {
236*0b57cec5SDimitry Andric     RegInfo->~MachineRegisterInfo();
237*0b57cec5SDimitry Andric     Allocator.Deallocate(RegInfo);
238*0b57cec5SDimitry Andric   }
239*0b57cec5SDimitry Andric   if (MFInfo) {
240*0b57cec5SDimitry Andric     MFInfo->~MachineFunctionInfo();
241*0b57cec5SDimitry Andric     Allocator.Deallocate(MFInfo);
242*0b57cec5SDimitry Andric   }
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric   FrameInfo->~MachineFrameInfo();
245*0b57cec5SDimitry Andric   Allocator.Deallocate(FrameInfo);
246*0b57cec5SDimitry Andric 
247*0b57cec5SDimitry Andric   ConstantPool->~MachineConstantPool();
248*0b57cec5SDimitry Andric   Allocator.Deallocate(ConstantPool);
249*0b57cec5SDimitry Andric 
250*0b57cec5SDimitry Andric   if (JumpTableInfo) {
251*0b57cec5SDimitry Andric     JumpTableInfo->~MachineJumpTableInfo();
252*0b57cec5SDimitry Andric     Allocator.Deallocate(JumpTableInfo);
253*0b57cec5SDimitry Andric   }
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric   if (WinEHInfo) {
256*0b57cec5SDimitry Andric     WinEHInfo->~WinEHFuncInfo();
257*0b57cec5SDimitry Andric     Allocator.Deallocate(WinEHInfo);
258*0b57cec5SDimitry Andric   }
259*0b57cec5SDimitry Andric 
260*0b57cec5SDimitry Andric   if (WasmEHInfo) {
261*0b57cec5SDimitry Andric     WasmEHInfo->~WasmEHFuncInfo();
262*0b57cec5SDimitry Andric     Allocator.Deallocate(WasmEHInfo);
263*0b57cec5SDimitry Andric   }
264*0b57cec5SDimitry Andric }
265*0b57cec5SDimitry Andric 
266*0b57cec5SDimitry Andric const DataLayout &MachineFunction::getDataLayout() const {
267*0b57cec5SDimitry Andric   return F.getParent()->getDataLayout();
268*0b57cec5SDimitry Andric }
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric /// Get the JumpTableInfo for this function.
271*0b57cec5SDimitry Andric /// If it does not already exist, allocate one.
272*0b57cec5SDimitry Andric MachineJumpTableInfo *MachineFunction::
273*0b57cec5SDimitry Andric getOrCreateJumpTableInfo(unsigned EntryKind) {
274*0b57cec5SDimitry Andric   if (JumpTableInfo) return JumpTableInfo;
275*0b57cec5SDimitry Andric 
276*0b57cec5SDimitry Andric   JumpTableInfo = new (Allocator)
277*0b57cec5SDimitry Andric     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
278*0b57cec5SDimitry Andric   return JumpTableInfo;
279*0b57cec5SDimitry Andric }
280*0b57cec5SDimitry Andric 
281480093f4SDimitry Andric DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
282e8d8bef9SDimitry Andric   return F.getDenormalMode(FPType);
283480093f4SDimitry Andric }
284480093f4SDimitry Andric 
285*0b57cec5SDimitry Andric /// Should we be emitting segmented stack stuff for the function
286*0b57cec5SDimitry Andric bool MachineFunction::shouldSplitStack() const {
287*0b57cec5SDimitry Andric   return getFunction().hasFnAttribute("split-stack");
288*0b57cec5SDimitry Andric }
289*0b57cec5SDimitry Andric 
290*0b57cec5SDimitry Andric LLVM_NODISCARD unsigned
291*0b57cec5SDimitry Andric MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
292*0b57cec5SDimitry Andric   FrameInstructions.push_back(Inst);
293*0b57cec5SDimitry Andric   return FrameInstructions.size() - 1;
294*0b57cec5SDimitry Andric }
295*0b57cec5SDimitry Andric 
296*0b57cec5SDimitry Andric /// This discards all of the MachineBasicBlock numbers and recomputes them.
297*0b57cec5SDimitry Andric /// This guarantees that the MBB numbers are sequential, dense, and match the
298*0b57cec5SDimitry Andric /// ordering of the blocks within the function.  If a specific MachineBasicBlock
299*0b57cec5SDimitry Andric /// is specified, only that block and those after it are renumbered.
300*0b57cec5SDimitry Andric void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
301*0b57cec5SDimitry Andric   if (empty()) { MBBNumbering.clear(); return; }
302*0b57cec5SDimitry Andric   MachineFunction::iterator MBBI, E = end();
303*0b57cec5SDimitry Andric   if (MBB == nullptr)
304*0b57cec5SDimitry Andric     MBBI = begin();
305*0b57cec5SDimitry Andric   else
306*0b57cec5SDimitry Andric     MBBI = MBB->getIterator();
307*0b57cec5SDimitry Andric 
308*0b57cec5SDimitry Andric   // Figure out the block number this should have.
309*0b57cec5SDimitry Andric   unsigned BlockNo = 0;
310*0b57cec5SDimitry Andric   if (MBBI != begin())
311*0b57cec5SDimitry Andric     BlockNo = std::prev(MBBI)->getNumber() + 1;
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric   for (; MBBI != E; ++MBBI, ++BlockNo) {
314*0b57cec5SDimitry Andric     if (MBBI->getNumber() != (int)BlockNo) {
315*0b57cec5SDimitry Andric       // Remove use of the old number.
316*0b57cec5SDimitry Andric       if (MBBI->getNumber() != -1) {
317*0b57cec5SDimitry Andric         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
318*0b57cec5SDimitry Andric                "MBB number mismatch!");
319*0b57cec5SDimitry Andric         MBBNumbering[MBBI->getNumber()] = nullptr;
320*0b57cec5SDimitry Andric       }
321*0b57cec5SDimitry Andric 
322*0b57cec5SDimitry Andric       // If BlockNo is already taken, set that block's number to -1.
323*0b57cec5SDimitry Andric       if (MBBNumbering[BlockNo])
324*0b57cec5SDimitry Andric         MBBNumbering[BlockNo]->setNumber(-1);
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric       MBBNumbering[BlockNo] = &*MBBI;
327*0b57cec5SDimitry Andric       MBBI->setNumber(BlockNo);
328*0b57cec5SDimitry Andric     }
329*0b57cec5SDimitry Andric   }
330*0b57cec5SDimitry Andric 
331*0b57cec5SDimitry Andric   // Okay, all the blocks are renumbered.  If we have compactified the block
332*0b57cec5SDimitry Andric   // numbering, shrink MBBNumbering now.
333*0b57cec5SDimitry Andric   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
334*0b57cec5SDimitry Andric   MBBNumbering.resize(BlockNo);
335*0b57cec5SDimitry Andric }
336*0b57cec5SDimitry Andric 
3375ffd83dbSDimitry Andric /// This method iterates over the basic blocks and assigns their IsBeginSection
3385ffd83dbSDimitry Andric /// and IsEndSection fields. This must be called after MBB layout is finalized
3395ffd83dbSDimitry Andric /// and the SectionID's are assigned to MBBs.
3405ffd83dbSDimitry Andric void MachineFunction::assignBeginEndSections() {
3415ffd83dbSDimitry Andric   front().setIsBeginSection();
3425ffd83dbSDimitry Andric   auto CurrentSectionID = front().getSectionID();
3435ffd83dbSDimitry Andric   for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
3445ffd83dbSDimitry Andric     if (MBBI->getSectionID() == CurrentSectionID)
3455ffd83dbSDimitry Andric       continue;
3465ffd83dbSDimitry Andric     MBBI->setIsBeginSection();
3475ffd83dbSDimitry Andric     std::prev(MBBI)->setIsEndSection();
3485ffd83dbSDimitry Andric     CurrentSectionID = MBBI->getSectionID();
3495ffd83dbSDimitry Andric   }
3505ffd83dbSDimitry Andric   back().setIsEndSection();
3515ffd83dbSDimitry Andric }
3525ffd83dbSDimitry Andric 
353*0b57cec5SDimitry Andric /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
354*0b57cec5SDimitry Andric MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
3550eae32dcSDimitry Andric                                                   DebugLoc DL,
356e8d8bef9SDimitry Andric                                                   bool NoImplicit) {
357*0b57cec5SDimitry Andric   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
3580eae32dcSDimitry Andric       MachineInstr(*this, MCID, std::move(DL), NoImplicit);
359*0b57cec5SDimitry Andric }
360*0b57cec5SDimitry Andric 
361*0b57cec5SDimitry Andric /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
362*0b57cec5SDimitry Andric /// identical in all ways except the instruction has no parent, prev, or next.
363*0b57cec5SDimitry Andric MachineInstr *
364*0b57cec5SDimitry Andric MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
365*0b57cec5SDimitry Andric   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
366*0b57cec5SDimitry Andric              MachineInstr(*this, *Orig);
367*0b57cec5SDimitry Andric }
368*0b57cec5SDimitry Andric 
3690eae32dcSDimitry Andric MachineInstr &MachineFunction::cloneMachineInstrBundle(
3700eae32dcSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
3710eae32dcSDimitry Andric     const MachineInstr &Orig) {
372*0b57cec5SDimitry Andric   MachineInstr *FirstClone = nullptr;
373*0b57cec5SDimitry Andric   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
374*0b57cec5SDimitry Andric   while (true) {
375*0b57cec5SDimitry Andric     MachineInstr *Cloned = CloneMachineInstr(&*I);
376*0b57cec5SDimitry Andric     MBB.insert(InsertBefore, Cloned);
377*0b57cec5SDimitry Andric     if (FirstClone == nullptr) {
378*0b57cec5SDimitry Andric       FirstClone = Cloned;
379*0b57cec5SDimitry Andric     } else {
380*0b57cec5SDimitry Andric       Cloned->bundleWithPred();
381*0b57cec5SDimitry Andric     }
382*0b57cec5SDimitry Andric 
383*0b57cec5SDimitry Andric     if (!I->isBundledWithSucc())
384*0b57cec5SDimitry Andric       break;
385*0b57cec5SDimitry Andric     ++I;
386*0b57cec5SDimitry Andric   }
3875ffd83dbSDimitry Andric   // Copy over call site info to the cloned instruction if needed. If Orig is in
3885ffd83dbSDimitry Andric   // a bundle, copyCallSiteInfo takes care of finding the call instruction in
3895ffd83dbSDimitry Andric   // the bundle.
3905ffd83dbSDimitry Andric   if (Orig.shouldUpdateCallSiteInfo())
3915ffd83dbSDimitry Andric     copyCallSiteInfo(&Orig, FirstClone);
392*0b57cec5SDimitry Andric   return *FirstClone;
393*0b57cec5SDimitry Andric }
394*0b57cec5SDimitry Andric 
395*0b57cec5SDimitry Andric /// Delete the given MachineInstr.
396*0b57cec5SDimitry Andric ///
397*0b57cec5SDimitry Andric /// This function also serves as the MachineInstr destructor - the real
398*0b57cec5SDimitry Andric /// ~MachineInstr() destructor must be empty.
3990eae32dcSDimitry Andric void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
400*0b57cec5SDimitry Andric   // Verify that a call site info is at valid state. This assertion should
401*0b57cec5SDimitry Andric   // be triggered during the implementation of support for the
402*0b57cec5SDimitry Andric   // call site info of a new architecture. If the assertion is triggered,
403*0b57cec5SDimitry Andric   // back trace will tell where to insert a call to updateCallSiteInfo().
4045ffd83dbSDimitry Andric   assert((!MI->isCandidateForCallSiteEntry() ||
405*0b57cec5SDimitry Andric           CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
406*0b57cec5SDimitry Andric          "Call site info was not updated!");
407*0b57cec5SDimitry Andric   // Strip it for parts. The operand array and the MI object itself are
408*0b57cec5SDimitry Andric   // independently recyclable.
409*0b57cec5SDimitry Andric   if (MI->Operands)
410*0b57cec5SDimitry Andric     deallocateOperandArray(MI->CapOperands, MI->Operands);
411*0b57cec5SDimitry Andric   // Don't call ~MachineInstr() which must be trivial anyway because
412*0b57cec5SDimitry Andric   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
413*0b57cec5SDimitry Andric   // destructors.
414*0b57cec5SDimitry Andric   InstructionRecycler.Deallocate(Allocator, MI);
415*0b57cec5SDimitry Andric }
416*0b57cec5SDimitry Andric 
417*0b57cec5SDimitry Andric /// Allocate a new MachineBasicBlock. Use this instead of
418*0b57cec5SDimitry Andric /// `new MachineBasicBlock'.
419*0b57cec5SDimitry Andric MachineBasicBlock *
420*0b57cec5SDimitry Andric MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
421*0b57cec5SDimitry Andric   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
422*0b57cec5SDimitry Andric              MachineBasicBlock(*this, bb);
423*0b57cec5SDimitry Andric }
424*0b57cec5SDimitry Andric 
425*0b57cec5SDimitry Andric /// Delete the given MachineBasicBlock.
4260eae32dcSDimitry Andric void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
427*0b57cec5SDimitry Andric   assert(MBB->getParent() == this && "MBB parent mismatch!");
428e8d8bef9SDimitry Andric   // Clean up any references to MBB in jump tables before deleting it.
429e8d8bef9SDimitry Andric   if (JumpTableInfo)
430e8d8bef9SDimitry Andric     JumpTableInfo->RemoveMBBFromJumpTables(MBB);
431*0b57cec5SDimitry Andric   MBB->~MachineBasicBlock();
432*0b57cec5SDimitry Andric   BasicBlockRecycler.Deallocate(Allocator, MBB);
433*0b57cec5SDimitry Andric }
434*0b57cec5SDimitry Andric 
435*0b57cec5SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
436*0b57cec5SDimitry Andric     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
4375ffd83dbSDimitry Andric     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
438*0b57cec5SDimitry Andric     SyncScope::ID SSID, AtomicOrdering Ordering,
439*0b57cec5SDimitry Andric     AtomicOrdering FailureOrdering) {
440*0b57cec5SDimitry Andric   return new (Allocator)
441*0b57cec5SDimitry Andric       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
442*0b57cec5SDimitry Andric                         SSID, Ordering, FailureOrdering);
443*0b57cec5SDimitry Andric }
444*0b57cec5SDimitry Andric 
445e8d8bef9SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
446fe6060f1SDimitry Andric     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
447fe6060f1SDimitry Andric     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
448fe6060f1SDimitry Andric     SyncScope::ID SSID, AtomicOrdering Ordering,
449fe6060f1SDimitry Andric     AtomicOrdering FailureOrdering) {
450fe6060f1SDimitry Andric   return new (Allocator)
451fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
452fe6060f1SDimitry Andric                         Ordering, FailureOrdering);
453fe6060f1SDimitry Andric }
454fe6060f1SDimitry Andric 
455fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
456fe6060f1SDimitry Andric     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
457fe6060f1SDimitry Andric   return new (Allocator)
458fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
459fe6060f1SDimitry Andric                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
460fe6060f1SDimitry Andric                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
461fe6060f1SDimitry Andric }
462fe6060f1SDimitry Andric 
463fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
464fe6060f1SDimitry Andric     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
465fe6060f1SDimitry Andric   return new (Allocator)
466fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
467fe6060f1SDimitry Andric                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
468fe6060f1SDimitry Andric                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
469e8d8bef9SDimitry Andric }
470e8d8bef9SDimitry Andric 
471*0b57cec5SDimitry Andric MachineMemOperand *
472*0b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
473fe6060f1SDimitry Andric                                       int64_t Offset, LLT Ty) {
474*0b57cec5SDimitry Andric   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
475*0b57cec5SDimitry Andric 
476*0b57cec5SDimitry Andric   // If there is no pointer value, the offset isn't tracked so we need to adjust
477*0b57cec5SDimitry Andric   // the base alignment.
4785ffd83dbSDimitry Andric   Align Alignment = PtrInfo.V.isNull()
4795ffd83dbSDimitry Andric                         ? commonAlignment(MMO->getBaseAlign(), Offset)
4805ffd83dbSDimitry Andric                         : MMO->getBaseAlign();
481*0b57cec5SDimitry Andric 
482e8d8bef9SDimitry Andric   // Do not preserve ranges, since we don't necessarily know what the high bits
483e8d8bef9SDimitry Andric   // are anymore.
484fe6060f1SDimitry Andric   return new (Allocator) MachineMemOperand(
485fe6060f1SDimitry Andric       PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
486fe6060f1SDimitry Andric       MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
487fe6060f1SDimitry Andric       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
488*0b57cec5SDimitry Andric }
489*0b57cec5SDimitry Andric 
490*0b57cec5SDimitry Andric MachineMemOperand *
491*0b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
492*0b57cec5SDimitry Andric                                       const AAMDNodes &AAInfo) {
493*0b57cec5SDimitry Andric   MachinePointerInfo MPI = MMO->getValue() ?
494*0b57cec5SDimitry Andric              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
495*0b57cec5SDimitry Andric              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
496*0b57cec5SDimitry Andric 
4975ffd83dbSDimitry Andric   return new (Allocator) MachineMemOperand(
4985ffd83dbSDimitry Andric       MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
499fe6060f1SDimitry Andric       MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
5005ffd83dbSDimitry Andric       MMO->getFailureOrdering());
501*0b57cec5SDimitry Andric }
502*0b57cec5SDimitry Andric 
503*0b57cec5SDimitry Andric MachineMemOperand *
504*0b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
505*0b57cec5SDimitry Andric                                       MachineMemOperand::Flags Flags) {
506*0b57cec5SDimitry Andric   return new (Allocator) MachineMemOperand(
5075ffd83dbSDimitry Andric       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
508*0b57cec5SDimitry Andric       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
509fe6060f1SDimitry Andric       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
510*0b57cec5SDimitry Andric }
511*0b57cec5SDimitry Andric 
512480093f4SDimitry Andric MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
513c14a5a88SDimitry Andric     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
514c14a5a88SDimitry Andric     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
515c14a5a88SDimitry Andric   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
516c14a5a88SDimitry Andric                                          PostInstrSymbol, HeapAllocMarker);
517*0b57cec5SDimitry Andric }
518*0b57cec5SDimitry Andric 
519*0b57cec5SDimitry Andric const char *MachineFunction::createExternalSymbolName(StringRef Name) {
520*0b57cec5SDimitry Andric   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
521*0b57cec5SDimitry Andric   llvm::copy(Name, Dest);
522*0b57cec5SDimitry Andric   Dest[Name.size()] = 0;
523*0b57cec5SDimitry Andric   return Dest;
524*0b57cec5SDimitry Andric }
525*0b57cec5SDimitry Andric 
526*0b57cec5SDimitry Andric uint32_t *MachineFunction::allocateRegMask() {
527*0b57cec5SDimitry Andric   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
528*0b57cec5SDimitry Andric   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
529*0b57cec5SDimitry Andric   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
530*0b57cec5SDimitry Andric   memset(Mask, 0, Size * sizeof(Mask[0]));
531*0b57cec5SDimitry Andric   return Mask;
532*0b57cec5SDimitry Andric }
533*0b57cec5SDimitry Andric 
534480093f4SDimitry Andric ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
535480093f4SDimitry Andric   int* AllocMask = Allocator.Allocate<int>(Mask.size());
536480093f4SDimitry Andric   copy(Mask, AllocMask);
537480093f4SDimitry Andric   return {AllocMask, Mask.size()};
538480093f4SDimitry Andric }
539480093f4SDimitry Andric 
540*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
541*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineFunction::dump() const {
542*0b57cec5SDimitry Andric   print(dbgs());
543*0b57cec5SDimitry Andric }
544*0b57cec5SDimitry Andric #endif
545*0b57cec5SDimitry Andric 
546*0b57cec5SDimitry Andric StringRef MachineFunction::getName() const {
547*0b57cec5SDimitry Andric   return getFunction().getName();
548*0b57cec5SDimitry Andric }
549*0b57cec5SDimitry Andric 
550*0b57cec5SDimitry Andric void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
551*0b57cec5SDimitry Andric   OS << "# Machine code for function " << getName() << ": ";
552*0b57cec5SDimitry Andric   getProperties().print(OS);
553*0b57cec5SDimitry Andric   OS << '\n';
554*0b57cec5SDimitry Andric 
555*0b57cec5SDimitry Andric   // Print Frame Information
556*0b57cec5SDimitry Andric   FrameInfo->print(*this, OS);
557*0b57cec5SDimitry Andric 
558*0b57cec5SDimitry Andric   // Print JumpTable Information
559*0b57cec5SDimitry Andric   if (JumpTableInfo)
560*0b57cec5SDimitry Andric     JumpTableInfo->print(OS);
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric   // Print Constant Pool
563*0b57cec5SDimitry Andric   ConstantPool->print(OS);
564*0b57cec5SDimitry Andric 
565*0b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
566*0b57cec5SDimitry Andric 
567*0b57cec5SDimitry Andric   if (RegInfo && !RegInfo->livein_empty()) {
568*0b57cec5SDimitry Andric     OS << "Function Live Ins: ";
569*0b57cec5SDimitry Andric     for (MachineRegisterInfo::livein_iterator
570*0b57cec5SDimitry Andric          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
571*0b57cec5SDimitry Andric       OS << printReg(I->first, TRI);
572*0b57cec5SDimitry Andric       if (I->second)
573*0b57cec5SDimitry Andric         OS << " in " << printReg(I->second, TRI);
574*0b57cec5SDimitry Andric       if (std::next(I) != E)
575*0b57cec5SDimitry Andric         OS << ", ";
576*0b57cec5SDimitry Andric     }
577*0b57cec5SDimitry Andric     OS << '\n';
578*0b57cec5SDimitry Andric   }
579*0b57cec5SDimitry Andric 
580*0b57cec5SDimitry Andric   ModuleSlotTracker MST(getFunction().getParent());
581*0b57cec5SDimitry Andric   MST.incorporateFunction(getFunction());
582*0b57cec5SDimitry Andric   for (const auto &BB : *this) {
583*0b57cec5SDimitry Andric     OS << '\n';
584*0b57cec5SDimitry Andric     // If we print the whole function, print it at its most verbose level.
585*0b57cec5SDimitry Andric     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
586*0b57cec5SDimitry Andric   }
587*0b57cec5SDimitry Andric 
588*0b57cec5SDimitry Andric   OS << "\n# End machine code for function " << getName() << ".\n\n";
589*0b57cec5SDimitry Andric }
590*0b57cec5SDimitry Andric 
591480093f4SDimitry Andric /// True if this function needs frame moves for debug or exceptions.
592480093f4SDimitry Andric bool MachineFunction::needsFrameMoves() const {
593480093f4SDimitry Andric   return getMMI().hasDebugInfo() ||
594480093f4SDimitry Andric          getTarget().Options.ForceDwarfFrameSection ||
595480093f4SDimitry Andric          F.needsUnwindTableEntry();
596480093f4SDimitry Andric }
597480093f4SDimitry Andric 
598*0b57cec5SDimitry Andric namespace llvm {
599*0b57cec5SDimitry Andric 
600*0b57cec5SDimitry Andric   template<>
601*0b57cec5SDimitry Andric   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
602*0b57cec5SDimitry Andric     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
603*0b57cec5SDimitry Andric 
604*0b57cec5SDimitry Andric     static std::string getGraphName(const MachineFunction *F) {
605*0b57cec5SDimitry Andric       return ("CFG for '" + F->getName() + "' function").str();
606*0b57cec5SDimitry Andric     }
607*0b57cec5SDimitry Andric 
608*0b57cec5SDimitry Andric     std::string getNodeLabel(const MachineBasicBlock *Node,
609*0b57cec5SDimitry Andric                              const MachineFunction *Graph) {
610*0b57cec5SDimitry Andric       std::string OutStr;
611*0b57cec5SDimitry Andric       {
612*0b57cec5SDimitry Andric         raw_string_ostream OSS(OutStr);
613*0b57cec5SDimitry Andric 
614*0b57cec5SDimitry Andric         if (isSimple()) {
615*0b57cec5SDimitry Andric           OSS << printMBBReference(*Node);
616*0b57cec5SDimitry Andric           if (const BasicBlock *BB = Node->getBasicBlock())
617*0b57cec5SDimitry Andric             OSS << ": " << BB->getName();
618*0b57cec5SDimitry Andric         } else
619*0b57cec5SDimitry Andric           Node->print(OSS);
620*0b57cec5SDimitry Andric       }
621*0b57cec5SDimitry Andric 
622*0b57cec5SDimitry Andric       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
623*0b57cec5SDimitry Andric 
624*0b57cec5SDimitry Andric       // Process string output to make it nicer...
625*0b57cec5SDimitry Andric       for (unsigned i = 0; i != OutStr.length(); ++i)
626*0b57cec5SDimitry Andric         if (OutStr[i] == '\n') {                            // Left justify
627*0b57cec5SDimitry Andric           OutStr[i] = '\\';
628*0b57cec5SDimitry Andric           OutStr.insert(OutStr.begin()+i+1, 'l');
629*0b57cec5SDimitry Andric         }
630*0b57cec5SDimitry Andric       return OutStr;
631*0b57cec5SDimitry Andric     }
632*0b57cec5SDimitry Andric   };
633*0b57cec5SDimitry Andric 
634*0b57cec5SDimitry Andric } // end namespace llvm
635*0b57cec5SDimitry Andric 
636*0b57cec5SDimitry Andric void MachineFunction::viewCFG() const
637*0b57cec5SDimitry Andric {
638*0b57cec5SDimitry Andric #ifndef NDEBUG
639*0b57cec5SDimitry Andric   ViewGraph(this, "mf" + getName());
640*0b57cec5SDimitry Andric #else
641*0b57cec5SDimitry Andric   errs() << "MachineFunction::viewCFG is only available in debug builds on "
642*0b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
643*0b57cec5SDimitry Andric #endif // NDEBUG
644*0b57cec5SDimitry Andric }
645*0b57cec5SDimitry Andric 
646*0b57cec5SDimitry Andric void MachineFunction::viewCFGOnly() const
647*0b57cec5SDimitry Andric {
648*0b57cec5SDimitry Andric #ifndef NDEBUG
649*0b57cec5SDimitry Andric   ViewGraph(this, "mf" + getName(), true);
650*0b57cec5SDimitry Andric #else
651*0b57cec5SDimitry Andric   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
652*0b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
653*0b57cec5SDimitry Andric #endif // NDEBUG
654*0b57cec5SDimitry Andric }
655*0b57cec5SDimitry Andric 
656*0b57cec5SDimitry Andric /// Add the specified physical register as a live-in value and
657*0b57cec5SDimitry Andric /// create a corresponding virtual register for it.
6585ffd83dbSDimitry Andric Register MachineFunction::addLiveIn(MCRegister PReg,
659*0b57cec5SDimitry Andric                                     const TargetRegisterClass *RC) {
660*0b57cec5SDimitry Andric   MachineRegisterInfo &MRI = getRegInfo();
6615ffd83dbSDimitry Andric   Register VReg = MRI.getLiveInVirtReg(PReg);
662*0b57cec5SDimitry Andric   if (VReg) {
663*0b57cec5SDimitry Andric     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
664*0b57cec5SDimitry Andric     (void)VRegRC;
665*0b57cec5SDimitry Andric     // A physical register can be added several times.
666*0b57cec5SDimitry Andric     // Between two calls, the register class of the related virtual register
667*0b57cec5SDimitry Andric     // may have been constrained to match some operation constraints.
668*0b57cec5SDimitry Andric     // In that case, check that the current register class includes the
669*0b57cec5SDimitry Andric     // physical register and is a sub class of the specified RC.
670*0b57cec5SDimitry Andric     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
671*0b57cec5SDimitry Andric                              RC->hasSubClassEq(VRegRC))) &&
672*0b57cec5SDimitry Andric             "Register class mismatch!");
673*0b57cec5SDimitry Andric     return VReg;
674*0b57cec5SDimitry Andric   }
675*0b57cec5SDimitry Andric   VReg = MRI.createVirtualRegister(RC);
676*0b57cec5SDimitry Andric   MRI.addLiveIn(PReg, VReg);
677*0b57cec5SDimitry Andric   return VReg;
678*0b57cec5SDimitry Andric }
679*0b57cec5SDimitry Andric 
680*0b57cec5SDimitry Andric /// Return the MCSymbol for the specified non-empty jump table.
681*0b57cec5SDimitry Andric /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
682*0b57cec5SDimitry Andric /// normal 'L' label is returned.
683*0b57cec5SDimitry Andric MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
684*0b57cec5SDimitry Andric                                         bool isLinkerPrivate) const {
685*0b57cec5SDimitry Andric   const DataLayout &DL = getDataLayout();
686*0b57cec5SDimitry Andric   assert(JumpTableInfo && "No jump tables");
687*0b57cec5SDimitry Andric   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
688*0b57cec5SDimitry Andric 
689*0b57cec5SDimitry Andric   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
690*0b57cec5SDimitry Andric                                      : DL.getPrivateGlobalPrefix();
691*0b57cec5SDimitry Andric   SmallString<60> Name;
692*0b57cec5SDimitry Andric   raw_svector_ostream(Name)
693*0b57cec5SDimitry Andric     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
694*0b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol(Name);
695*0b57cec5SDimitry Andric }
696*0b57cec5SDimitry Andric 
697*0b57cec5SDimitry Andric /// Return a function-local symbol to represent the PIC base.
698*0b57cec5SDimitry Andric MCSymbol *MachineFunction::getPICBaseSymbol() const {
699*0b57cec5SDimitry Andric   const DataLayout &DL = getDataLayout();
700*0b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
701*0b57cec5SDimitry Andric                                Twine(getFunctionNumber()) + "$pb");
702*0b57cec5SDimitry Andric }
703*0b57cec5SDimitry Andric 
704*0b57cec5SDimitry Andric /// \name Exception Handling
705*0b57cec5SDimitry Andric /// \{
706*0b57cec5SDimitry Andric 
707*0b57cec5SDimitry Andric LandingPadInfo &
708*0b57cec5SDimitry Andric MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
709*0b57cec5SDimitry Andric   unsigned N = LandingPads.size();
710*0b57cec5SDimitry Andric   for (unsigned i = 0; i < N; ++i) {
711*0b57cec5SDimitry Andric     LandingPadInfo &LP = LandingPads[i];
712*0b57cec5SDimitry Andric     if (LP.LandingPadBlock == LandingPad)
713*0b57cec5SDimitry Andric       return LP;
714*0b57cec5SDimitry Andric   }
715*0b57cec5SDimitry Andric 
716*0b57cec5SDimitry Andric   LandingPads.push_back(LandingPadInfo(LandingPad));
717*0b57cec5SDimitry Andric   return LandingPads[N];
718*0b57cec5SDimitry Andric }
719*0b57cec5SDimitry Andric 
720*0b57cec5SDimitry Andric void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
721*0b57cec5SDimitry Andric                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
722*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
723*0b57cec5SDimitry Andric   LP.BeginLabels.push_back(BeginLabel);
724*0b57cec5SDimitry Andric   LP.EndLabels.push_back(EndLabel);
725*0b57cec5SDimitry Andric }
726*0b57cec5SDimitry Andric 
727*0b57cec5SDimitry Andric MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
728*0b57cec5SDimitry Andric   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
729*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
730*0b57cec5SDimitry Andric   LP.LandingPadLabel = LandingPadLabel;
731*0b57cec5SDimitry Andric 
732*0b57cec5SDimitry Andric   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
733*0b57cec5SDimitry Andric   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
734*0b57cec5SDimitry Andric     if (const auto *PF =
735*0b57cec5SDimitry Andric             dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
736*0b57cec5SDimitry Andric       getMMI().addPersonality(PF);
737*0b57cec5SDimitry Andric 
738*0b57cec5SDimitry Andric     if (LPI->isCleanup())
739*0b57cec5SDimitry Andric       addCleanup(LandingPad);
740*0b57cec5SDimitry Andric 
741*0b57cec5SDimitry Andric     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
742*0b57cec5SDimitry Andric     //        correct, but we need to do it this way because of how the DWARF EH
743*0b57cec5SDimitry Andric     //        emitter processes the clauses.
744*0b57cec5SDimitry Andric     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
745*0b57cec5SDimitry Andric       Value *Val = LPI->getClause(I - 1);
746*0b57cec5SDimitry Andric       if (LPI->isCatch(I - 1)) {
747*0b57cec5SDimitry Andric         addCatchTypeInfo(LandingPad,
748*0b57cec5SDimitry Andric                          dyn_cast<GlobalValue>(Val->stripPointerCasts()));
749*0b57cec5SDimitry Andric       } else {
750*0b57cec5SDimitry Andric         // Add filters in a list.
751*0b57cec5SDimitry Andric         auto *CVal = cast<Constant>(Val);
752*0b57cec5SDimitry Andric         SmallVector<const GlobalValue *, 4> FilterList;
753349cc55cSDimitry Andric         for (const Use &U : CVal->operands())
754349cc55cSDimitry Andric           FilterList.push_back(cast<GlobalValue>(U->stripPointerCasts()));
755*0b57cec5SDimitry Andric 
756*0b57cec5SDimitry Andric         addFilterTypeInfo(LandingPad, FilterList);
757*0b57cec5SDimitry Andric       }
758*0b57cec5SDimitry Andric     }
759*0b57cec5SDimitry Andric 
760*0b57cec5SDimitry Andric   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
761*0b57cec5SDimitry Andric     for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
762*0b57cec5SDimitry Andric       Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
763*0b57cec5SDimitry Andric       addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
764*0b57cec5SDimitry Andric     }
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   } else {
767*0b57cec5SDimitry Andric     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
768*0b57cec5SDimitry Andric   }
769*0b57cec5SDimitry Andric 
770*0b57cec5SDimitry Andric   return LandingPadLabel;
771*0b57cec5SDimitry Andric }
772*0b57cec5SDimitry Andric 
773*0b57cec5SDimitry Andric void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
774*0b57cec5SDimitry Andric                                        ArrayRef<const GlobalValue *> TyInfo) {
775*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
7760eae32dcSDimitry Andric   for (const GlobalValue *GV : llvm::reverse(TyInfo))
7770eae32dcSDimitry Andric     LP.TypeIds.push_back(getTypeIDFor(GV));
778*0b57cec5SDimitry Andric }
779*0b57cec5SDimitry Andric 
780*0b57cec5SDimitry Andric void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
781*0b57cec5SDimitry Andric                                         ArrayRef<const GlobalValue *> TyInfo) {
782*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
783*0b57cec5SDimitry Andric   std::vector<unsigned> IdsInFilter(TyInfo.size());
784*0b57cec5SDimitry Andric   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
785*0b57cec5SDimitry Andric     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
786*0b57cec5SDimitry Andric   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
787*0b57cec5SDimitry Andric }
788*0b57cec5SDimitry Andric 
789*0b57cec5SDimitry Andric void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
790*0b57cec5SDimitry Andric                                       bool TidyIfNoBeginLabels) {
791*0b57cec5SDimitry Andric   for (unsigned i = 0; i != LandingPads.size(); ) {
792*0b57cec5SDimitry Andric     LandingPadInfo &LandingPad = LandingPads[i];
793*0b57cec5SDimitry Andric     if (LandingPad.LandingPadLabel &&
794*0b57cec5SDimitry Andric         !LandingPad.LandingPadLabel->isDefined() &&
795*0b57cec5SDimitry Andric         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
796*0b57cec5SDimitry Andric       LandingPad.LandingPadLabel = nullptr;
797*0b57cec5SDimitry Andric 
798*0b57cec5SDimitry Andric     // Special case: we *should* emit LPs with null LP MBB. This indicates
799*0b57cec5SDimitry Andric     // "nounwind" case.
800*0b57cec5SDimitry Andric     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
801*0b57cec5SDimitry Andric       LandingPads.erase(LandingPads.begin() + i);
802*0b57cec5SDimitry Andric       continue;
803*0b57cec5SDimitry Andric     }
804*0b57cec5SDimitry Andric 
805*0b57cec5SDimitry Andric     if (TidyIfNoBeginLabels) {
806*0b57cec5SDimitry Andric       for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
807*0b57cec5SDimitry Andric         MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
808*0b57cec5SDimitry Andric         MCSymbol *EndLabel = LandingPad.EndLabels[j];
809*0b57cec5SDimitry Andric         if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
810*0b57cec5SDimitry Andric             (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
811*0b57cec5SDimitry Andric           continue;
812*0b57cec5SDimitry Andric 
813*0b57cec5SDimitry Andric         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
814*0b57cec5SDimitry Andric         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
815*0b57cec5SDimitry Andric         --j;
816*0b57cec5SDimitry Andric         --e;
817*0b57cec5SDimitry Andric       }
818*0b57cec5SDimitry Andric 
819*0b57cec5SDimitry Andric       // Remove landing pads with no try-ranges.
820*0b57cec5SDimitry Andric       if (LandingPads[i].BeginLabels.empty()) {
821*0b57cec5SDimitry Andric         LandingPads.erase(LandingPads.begin() + i);
822*0b57cec5SDimitry Andric         continue;
823*0b57cec5SDimitry Andric       }
824*0b57cec5SDimitry Andric     }
825*0b57cec5SDimitry Andric 
826*0b57cec5SDimitry Andric     // If there is no landing pad, ensure that the list of typeids is empty.
827*0b57cec5SDimitry Andric     // If the only typeid is a cleanup, this is the same as having no typeids.
828*0b57cec5SDimitry Andric     if (!LandingPad.LandingPadBlock ||
829*0b57cec5SDimitry Andric         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
830*0b57cec5SDimitry Andric       LandingPad.TypeIds.clear();
831*0b57cec5SDimitry Andric     ++i;
832*0b57cec5SDimitry Andric   }
833*0b57cec5SDimitry Andric }
834*0b57cec5SDimitry Andric 
835*0b57cec5SDimitry Andric void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
836*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
837*0b57cec5SDimitry Andric   LP.TypeIds.push_back(0);
838*0b57cec5SDimitry Andric }
839*0b57cec5SDimitry Andric 
840*0b57cec5SDimitry Andric void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
841*0b57cec5SDimitry Andric                                          const Function *Filter,
842*0b57cec5SDimitry Andric                                          const BlockAddress *RecoverBA) {
843*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
844*0b57cec5SDimitry Andric   SEHHandler Handler;
845*0b57cec5SDimitry Andric   Handler.FilterOrFinally = Filter;
846*0b57cec5SDimitry Andric   Handler.RecoverBA = RecoverBA;
847*0b57cec5SDimitry Andric   LP.SEHHandlers.push_back(Handler);
848*0b57cec5SDimitry Andric }
849*0b57cec5SDimitry Andric 
850*0b57cec5SDimitry Andric void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
851*0b57cec5SDimitry Andric                                            const Function *Cleanup) {
852*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
853*0b57cec5SDimitry Andric   SEHHandler Handler;
854*0b57cec5SDimitry Andric   Handler.FilterOrFinally = Cleanup;
855*0b57cec5SDimitry Andric   Handler.RecoverBA = nullptr;
856*0b57cec5SDimitry Andric   LP.SEHHandlers.push_back(Handler);
857*0b57cec5SDimitry Andric }
858*0b57cec5SDimitry Andric 
859*0b57cec5SDimitry Andric void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
860*0b57cec5SDimitry Andric                                             ArrayRef<unsigned> Sites) {
861*0b57cec5SDimitry Andric   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
862*0b57cec5SDimitry Andric }
863*0b57cec5SDimitry Andric 
864*0b57cec5SDimitry Andric unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
865*0b57cec5SDimitry Andric   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
866*0b57cec5SDimitry Andric     if (TypeInfos[i] == TI) return i + 1;
867*0b57cec5SDimitry Andric 
868*0b57cec5SDimitry Andric   TypeInfos.push_back(TI);
869*0b57cec5SDimitry Andric   return TypeInfos.size();
870*0b57cec5SDimitry Andric }
871*0b57cec5SDimitry Andric 
872*0b57cec5SDimitry Andric int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
873*0b57cec5SDimitry Andric   // If the new filter coincides with the tail of an existing filter, then
874*0b57cec5SDimitry Andric   // re-use the existing filter.  Folding filters more than this requires
875*0b57cec5SDimitry Andric   // re-ordering filters and/or their elements - probably not worth it.
876fe6060f1SDimitry Andric   for (unsigned i : FilterEnds) {
877fe6060f1SDimitry Andric     unsigned j = TyIds.size();
878*0b57cec5SDimitry Andric 
879*0b57cec5SDimitry Andric     while (i && j)
880*0b57cec5SDimitry Andric       if (FilterIds[--i] != TyIds[--j])
881*0b57cec5SDimitry Andric         goto try_next;
882*0b57cec5SDimitry Andric 
883*0b57cec5SDimitry Andric     if (!j)
884*0b57cec5SDimitry Andric       // The new filter coincides with range [i, end) of the existing filter.
885*0b57cec5SDimitry Andric       return -(1 + i);
886*0b57cec5SDimitry Andric 
887*0b57cec5SDimitry Andric try_next:;
888*0b57cec5SDimitry Andric   }
889*0b57cec5SDimitry Andric 
890*0b57cec5SDimitry Andric   // Add the new filter.
891*0b57cec5SDimitry Andric   int FilterID = -(1 + FilterIds.size());
892*0b57cec5SDimitry Andric   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
893e8d8bef9SDimitry Andric   llvm::append_range(FilterIds, TyIds);
894*0b57cec5SDimitry Andric   FilterEnds.push_back(FilterIds.size());
895*0b57cec5SDimitry Andric   FilterIds.push_back(0); // terminator
896*0b57cec5SDimitry Andric   return FilterID;
897*0b57cec5SDimitry Andric }
898*0b57cec5SDimitry Andric 
899480093f4SDimitry Andric MachineFunction::CallSiteInfoMap::iterator
900480093f4SDimitry Andric MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
9015ffd83dbSDimitry Andric   assert(MI->isCandidateForCallSiteEntry() &&
9025ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates");
903*0b57cec5SDimitry Andric 
9045ffd83dbSDimitry Andric   if (!Target.Options.EmitCallSiteInfo)
905480093f4SDimitry Andric     return CallSitesInfo.end();
906480093f4SDimitry Andric   return CallSitesInfo.find(MI);
907*0b57cec5SDimitry Andric }
908*0b57cec5SDimitry Andric 
9095ffd83dbSDimitry Andric /// Return the call machine instruction or find a call within bundle.
9105ffd83dbSDimitry Andric static const MachineInstr *getCallInstr(const MachineInstr *MI) {
9115ffd83dbSDimitry Andric   if (!MI->isBundle())
9125ffd83dbSDimitry Andric     return MI;
913*0b57cec5SDimitry Andric 
9145ffd83dbSDimitry Andric   for (auto &BMI : make_range(getBundleStart(MI->getIterator()),
9155ffd83dbSDimitry Andric                               getBundleEnd(MI->getIterator())))
9165ffd83dbSDimitry Andric     if (BMI.isCandidateForCallSiteEntry())
9175ffd83dbSDimitry Andric       return &BMI;
9188bcb0991SDimitry Andric 
9195ffd83dbSDimitry Andric   llvm_unreachable("Unexpected bundle without a call site candidate");
9208bcb0991SDimitry Andric }
9218bcb0991SDimitry Andric 
9228bcb0991SDimitry Andric void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
9235ffd83dbSDimitry Andric   assert(MI->shouldUpdateCallSiteInfo() &&
9245ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9255ffd83dbSDimitry Andric          "candidates inside bundles");
9265ffd83dbSDimitry Andric 
9275ffd83dbSDimitry Andric   const MachineInstr *CallMI = getCallInstr(MI);
9285ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
9298bcb0991SDimitry Andric   if (CSIt == CallSitesInfo.end())
9308bcb0991SDimitry Andric     return;
9318bcb0991SDimitry Andric   CallSitesInfo.erase(CSIt);
9328bcb0991SDimitry Andric }
9338bcb0991SDimitry Andric 
9348bcb0991SDimitry Andric void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
9358bcb0991SDimitry Andric                                        const MachineInstr *New) {
9365ffd83dbSDimitry Andric   assert(Old->shouldUpdateCallSiteInfo() &&
9375ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9385ffd83dbSDimitry Andric          "candidates inside bundles");
9398bcb0991SDimitry Andric 
9405ffd83dbSDimitry Andric   if (!New->isCandidateForCallSiteEntry())
9415ffd83dbSDimitry Andric     return eraseCallSiteInfo(Old);
9425ffd83dbSDimitry Andric 
9435ffd83dbSDimitry Andric   const MachineInstr *OldCallMI = getCallInstr(Old);
9445ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9458bcb0991SDimitry Andric   if (CSIt == CallSitesInfo.end())
9468bcb0991SDimitry Andric     return;
9478bcb0991SDimitry Andric 
9488bcb0991SDimitry Andric   CallSiteInfo CSInfo = CSIt->second;
949*0b57cec5SDimitry Andric   CallSitesInfo[New] = CSInfo;
950*0b57cec5SDimitry Andric }
951*0b57cec5SDimitry Andric 
9525ffd83dbSDimitry Andric void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
9535ffd83dbSDimitry Andric                                        const MachineInstr *New) {
9545ffd83dbSDimitry Andric   assert(Old->shouldUpdateCallSiteInfo() &&
9555ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9565ffd83dbSDimitry Andric          "candidates inside bundles");
9575ffd83dbSDimitry Andric 
9585ffd83dbSDimitry Andric   if (!New->isCandidateForCallSiteEntry())
9595ffd83dbSDimitry Andric     return eraseCallSiteInfo(Old);
9605ffd83dbSDimitry Andric 
9615ffd83dbSDimitry Andric   const MachineInstr *OldCallMI = getCallInstr(Old);
9625ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9635ffd83dbSDimitry Andric   if (CSIt == CallSitesInfo.end())
9645ffd83dbSDimitry Andric     return;
9655ffd83dbSDimitry Andric 
9665ffd83dbSDimitry Andric   CallSiteInfo CSInfo = std::move(CSIt->second);
9675ffd83dbSDimitry Andric   CallSitesInfo.erase(CSIt);
9685ffd83dbSDimitry Andric   CallSitesInfo[New] = CSInfo;
9695ffd83dbSDimitry Andric }
9705ffd83dbSDimitry Andric 
971e8d8bef9SDimitry Andric void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
972e8d8bef9SDimitry Andric   DebugInstrNumberingCount = Num;
973e8d8bef9SDimitry Andric }
974e8d8bef9SDimitry Andric 
975e8d8bef9SDimitry Andric void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
976fe6060f1SDimitry Andric                                                  DebugInstrOperandPair B,
977fe6060f1SDimitry Andric                                                  unsigned Subreg) {
978fe6060f1SDimitry Andric   // Catch any accidental self-loops.
979fe6060f1SDimitry Andric   assert(A.first != B.first);
980349cc55cSDimitry Andric   // Don't allow any substitutions _from_ the memory operand number.
981349cc55cSDimitry Andric   assert(A.second != DebugOperandMemNumber);
982349cc55cSDimitry Andric 
983fe6060f1SDimitry Andric   DebugValueSubstitutions.push_back({A, B, Subreg});
984e8d8bef9SDimitry Andric }
985e8d8bef9SDimitry Andric 
986e8d8bef9SDimitry Andric void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
987e8d8bef9SDimitry Andric                                                    MachineInstr &New,
988e8d8bef9SDimitry Andric                                                    unsigned MaxOperand) {
989e8d8bef9SDimitry Andric   // If the Old instruction wasn't tracked at all, there is no work to do.
990e8d8bef9SDimitry Andric   unsigned OldInstrNum = Old.peekDebugInstrNum();
991e8d8bef9SDimitry Andric   if (!OldInstrNum)
992e8d8bef9SDimitry Andric     return;
993e8d8bef9SDimitry Andric 
994e8d8bef9SDimitry Andric   // Iterate over all operands looking for defs to create substitutions for.
995e8d8bef9SDimitry Andric   // Avoid creating new instr numbers unless we create a new substitution.
996e8d8bef9SDimitry Andric   // While this has no functional effect, it risks confusing someone reading
997e8d8bef9SDimitry Andric   // MIR output.
998e8d8bef9SDimitry Andric   // Examine all the operands, or the first N specified by the caller.
999e8d8bef9SDimitry Andric   MaxOperand = std::min(MaxOperand, Old.getNumOperands());
1000fe6060f1SDimitry Andric   for (unsigned int I = 0; I < MaxOperand; ++I) {
1001e8d8bef9SDimitry Andric     const auto &OldMO = Old.getOperand(I);
1002e8d8bef9SDimitry Andric     auto &NewMO = New.getOperand(I);
1003e8d8bef9SDimitry Andric     (void)NewMO;
1004e8d8bef9SDimitry Andric 
1005e8d8bef9SDimitry Andric     if (!OldMO.isReg() || !OldMO.isDef())
1006e8d8bef9SDimitry Andric       continue;
1007e8d8bef9SDimitry Andric     assert(NewMO.isDef());
1008e8d8bef9SDimitry Andric 
1009e8d8bef9SDimitry Andric     unsigned NewInstrNum = New.getDebugInstrNum();
1010e8d8bef9SDimitry Andric     makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
1011e8d8bef9SDimitry Andric                                std::make_pair(NewInstrNum, I));
1012e8d8bef9SDimitry Andric   }
1013e8d8bef9SDimitry Andric }
1014e8d8bef9SDimitry Andric 
1015fe6060f1SDimitry Andric auto MachineFunction::salvageCopySSA(MachineInstr &MI)
1016fe6060f1SDimitry Andric     -> DebugInstrOperandPair {
1017fe6060f1SDimitry Andric   MachineRegisterInfo &MRI = getRegInfo();
1018fe6060f1SDimitry Andric   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1019fe6060f1SDimitry Andric   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1020fe6060f1SDimitry Andric 
1021fe6060f1SDimitry Andric   // Chase the value read by a copy-like instruction back to the instruction
1022fe6060f1SDimitry Andric   // that ultimately _defines_ that value. This may pass:
1023fe6060f1SDimitry Andric   //  * Through multiple intermediate copies, including subregister moves /
1024fe6060f1SDimitry Andric   //    copies,
1025fe6060f1SDimitry Andric   //  * Copies from physical registers that must then be traced back to the
1026fe6060f1SDimitry Andric   //    defining instruction,
1027fe6060f1SDimitry Andric   //  * Or, physical registers may be live-in to (only) the entry block, which
1028fe6060f1SDimitry Andric   //    requires a DBG_PHI to be created.
1029fe6060f1SDimitry Andric   // We can pursue this problem in that order: trace back through copies,
1030fe6060f1SDimitry Andric   // optionally through a physical register, to a defining instruction. We
1031fe6060f1SDimitry Andric   // should never move from physreg to vreg. As we're still in SSA form, no need
1032fe6060f1SDimitry Andric   // to worry about partial definitions of registers.
1033fe6060f1SDimitry Andric 
1034fe6060f1SDimitry Andric   // Helper lambda to interpret a copy-like instruction. Takes instruction,
1035fe6060f1SDimitry Andric   // returns the register read and any subregister identifying which part is
1036fe6060f1SDimitry Andric   // read.
1037fe6060f1SDimitry Andric   auto GetRegAndSubreg =
1038fe6060f1SDimitry Andric       [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1039fe6060f1SDimitry Andric     Register NewReg, OldReg;
1040fe6060f1SDimitry Andric     unsigned SubReg;
1041fe6060f1SDimitry Andric     if (Cpy.isCopy()) {
1042fe6060f1SDimitry Andric       OldReg = Cpy.getOperand(0).getReg();
1043fe6060f1SDimitry Andric       NewReg = Cpy.getOperand(1).getReg();
1044fe6060f1SDimitry Andric       SubReg = Cpy.getOperand(1).getSubReg();
1045fe6060f1SDimitry Andric     } else if (Cpy.isSubregToReg()) {
1046fe6060f1SDimitry Andric       OldReg = Cpy.getOperand(0).getReg();
1047fe6060f1SDimitry Andric       NewReg = Cpy.getOperand(2).getReg();
1048fe6060f1SDimitry Andric       SubReg = Cpy.getOperand(3).getImm();
1049fe6060f1SDimitry Andric     } else {
1050fe6060f1SDimitry Andric       auto CopyDetails = *TII.isCopyInstr(Cpy);
1051fe6060f1SDimitry Andric       const MachineOperand &Src = *CopyDetails.Source;
1052fe6060f1SDimitry Andric       const MachineOperand &Dest = *CopyDetails.Destination;
1053fe6060f1SDimitry Andric       OldReg = Dest.getReg();
1054fe6060f1SDimitry Andric       NewReg = Src.getReg();
1055fe6060f1SDimitry Andric       SubReg = Src.getSubReg();
1056fe6060f1SDimitry Andric     }
1057fe6060f1SDimitry Andric 
1058fe6060f1SDimitry Andric     return {NewReg, SubReg};
1059fe6060f1SDimitry Andric   };
1060fe6060f1SDimitry Andric 
1061fe6060f1SDimitry Andric   // First seek either the defining instruction, or a copy from a physreg.
1062fe6060f1SDimitry Andric   // During search, the current state is the current copy instruction, and which
1063fe6060f1SDimitry Andric   // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1064fe6060f1SDimitry Andric   // deal with those later.
1065fe6060f1SDimitry Andric   auto State = GetRegAndSubreg(MI);
1066fe6060f1SDimitry Andric   auto CurInst = MI.getIterator();
1067fe6060f1SDimitry Andric   SmallVector<unsigned, 4> SubregsSeen;
1068fe6060f1SDimitry Andric   while (true) {
1069fe6060f1SDimitry Andric     // If we've found a copy from a physreg, first portion of search is over.
1070fe6060f1SDimitry Andric     if (!State.first.isVirtual())
1071fe6060f1SDimitry Andric       break;
1072fe6060f1SDimitry Andric 
1073fe6060f1SDimitry Andric     // Record any subregister qualifier.
1074fe6060f1SDimitry Andric     if (State.second)
1075fe6060f1SDimitry Andric       SubregsSeen.push_back(State.second);
1076fe6060f1SDimitry Andric 
1077fe6060f1SDimitry Andric     assert(MRI.hasOneDef(State.first));
1078fe6060f1SDimitry Andric     MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1079fe6060f1SDimitry Andric     CurInst = Inst.getIterator();
1080fe6060f1SDimitry Andric 
1081fe6060f1SDimitry Andric     // Any non-copy instruction is the defining instruction we're seeking.
1082fe6060f1SDimitry Andric     if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1083fe6060f1SDimitry Andric       break;
1084fe6060f1SDimitry Andric     State = GetRegAndSubreg(Inst);
1085fe6060f1SDimitry Andric   };
1086fe6060f1SDimitry Andric 
1087fe6060f1SDimitry Andric   // Helper lambda to apply additional subregister substitutions to a known
1088fe6060f1SDimitry Andric   // instruction/operand pair. Adds new (fake) substitutions so that we can
1089fe6060f1SDimitry Andric   // record the subregister. FIXME: this isn't very space efficient if multiple
1090fe6060f1SDimitry Andric   // values are tracked back through the same copies; cache something later.
1091fe6060f1SDimitry Andric   auto ApplySubregisters =
1092fe6060f1SDimitry Andric       [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1093fe6060f1SDimitry Andric     for (unsigned Subreg : reverse(SubregsSeen)) {
1094fe6060f1SDimitry Andric       // Fetch a new instruction number, not attached to an actual instruction.
1095fe6060f1SDimitry Andric       unsigned NewInstrNumber = getNewDebugInstrNum();
1096fe6060f1SDimitry Andric       // Add a substitution from the "new" number to the known one, with a
1097fe6060f1SDimitry Andric       // qualifying subreg.
1098fe6060f1SDimitry Andric       makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1099fe6060f1SDimitry Andric       // Return the new number; to find the underlying value, consumers need to
1100fe6060f1SDimitry Andric       // deal with the qualifying subreg.
1101fe6060f1SDimitry Andric       P = {NewInstrNumber, 0};
1102fe6060f1SDimitry Andric     }
1103fe6060f1SDimitry Andric     return P;
1104fe6060f1SDimitry Andric   };
1105fe6060f1SDimitry Andric 
1106fe6060f1SDimitry Andric   // If we managed to find the defining instruction after COPYs, return an
1107fe6060f1SDimitry Andric   // instruction / operand pair after adding subregister qualifiers.
1108fe6060f1SDimitry Andric   if (State.first.isVirtual()) {
1109fe6060f1SDimitry Andric     // Virtual register def -- we can just look up where this happens.
1110fe6060f1SDimitry Andric     MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1111fe6060f1SDimitry Andric     for (auto &MO : Inst->operands()) {
1112fe6060f1SDimitry Andric       if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first)
1113fe6060f1SDimitry Andric         continue;
1114fe6060f1SDimitry Andric       return ApplySubregisters(
1115fe6060f1SDimitry Andric           {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)});
1116fe6060f1SDimitry Andric     }
1117fe6060f1SDimitry Andric 
1118fe6060f1SDimitry Andric     llvm_unreachable("Vreg def with no corresponding operand?");
1119fe6060f1SDimitry Andric   }
1120fe6060f1SDimitry Andric 
1121fe6060f1SDimitry Andric   // Our search ended in a copy from a physreg: walk back up the function
1122fe6060f1SDimitry Andric   // looking for whatever defines the physreg.
1123fe6060f1SDimitry Andric   assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1124fe6060f1SDimitry Andric   State = GetRegAndSubreg(*CurInst);
1125fe6060f1SDimitry Andric   Register RegToSeek = State.first;
1126fe6060f1SDimitry Andric 
1127fe6060f1SDimitry Andric   auto RMII = CurInst->getReverseIterator();
1128fe6060f1SDimitry Andric   auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1129fe6060f1SDimitry Andric   for (auto &ToExamine : PrevInstrs) {
1130fe6060f1SDimitry Andric     for (auto &MO : ToExamine.operands()) {
1131fe6060f1SDimitry Andric       // Test for operand that defines something aliasing RegToSeek.
1132fe6060f1SDimitry Andric       if (!MO.isReg() || !MO.isDef() ||
1133fe6060f1SDimitry Andric           !TRI.regsOverlap(RegToSeek, MO.getReg()))
1134fe6060f1SDimitry Andric         continue;
1135fe6060f1SDimitry Andric 
1136fe6060f1SDimitry Andric       return ApplySubregisters(
1137fe6060f1SDimitry Andric           {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)});
1138fe6060f1SDimitry Andric     }
1139fe6060f1SDimitry Andric   }
1140fe6060f1SDimitry Andric 
1141fe6060f1SDimitry Andric   MachineBasicBlock &InsertBB = *CurInst->getParent();
1142fe6060f1SDimitry Andric 
1143fe6060f1SDimitry Andric   // We reached the start of the block before finding a defining instruction.
1144fe6060f1SDimitry Andric   // It could be from a constant register, otherwise it must be an argument.
1145fe6060f1SDimitry Andric   if (TRI.isConstantPhysReg(State.first)) {
1146fe6060f1SDimitry Andric     // We can produce a DBG_PHI that identifies the constant physreg. Doesn't
1147fe6060f1SDimitry Andric     // matter where we put it, as it's constant valued.
1148fe6060f1SDimitry Andric     assert(CurInst->isCopy());
1149fe6060f1SDimitry Andric   } else if (State.first == TRI.getFrameRegister(*this)) {
1150fe6060f1SDimitry Andric     // LLVM IR is allowed to read the framepointer by calling a
1151fe6060f1SDimitry Andric     // llvm.frameaddress.* intrinsic. We can support this by emitting a
1152fe6060f1SDimitry Andric     // DBG_PHI $fp. This isn't ideal, because it extends the behaviours /
1153fe6060f1SDimitry Andric     // position that DBG_PHIs appear at, limiting what can be done later.
1154fe6060f1SDimitry Andric     // TODO: see if there's a better way of expressing these variable
1155fe6060f1SDimitry Andric     // locations.
1156fe6060f1SDimitry Andric     ;
1157fe6060f1SDimitry Andric   } else {
1158349cc55cSDimitry Andric     // Assert that this is the entry block, or an EH pad. If it isn't, then
1159349cc55cSDimitry Andric     // there is some code construct we don't recognise that deals with physregs
1160349cc55cSDimitry Andric     // across blocks.
1161fe6060f1SDimitry Andric     assert(!State.first.isVirtual());
1162349cc55cSDimitry Andric     assert(&*InsertBB.getParent()->begin() == &InsertBB || InsertBB.isEHPad());
1163fe6060f1SDimitry Andric   }
1164fe6060f1SDimitry Andric 
1165fe6060f1SDimitry Andric   // Create DBG_PHI for specified physreg.
1166fe6060f1SDimitry Andric   auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1167fe6060f1SDimitry Andric                          TII.get(TargetOpcode::DBG_PHI));
1168349cc55cSDimitry Andric   Builder.addReg(State.first);
1169fe6060f1SDimitry Andric   unsigned NewNum = getNewDebugInstrNum();
1170fe6060f1SDimitry Andric   Builder.addImm(NewNum);
1171fe6060f1SDimitry Andric   return ApplySubregisters({NewNum, 0u});
1172fe6060f1SDimitry Andric }
1173fe6060f1SDimitry Andric 
1174fe6060f1SDimitry Andric void MachineFunction::finalizeDebugInstrRefs() {
1175fe6060f1SDimitry Andric   auto *TII = getSubtarget().getInstrInfo();
1176fe6060f1SDimitry Andric 
11774824e7fdSDimitry Andric   auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1178fe6060f1SDimitry Andric     const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE);
1179fe6060f1SDimitry Andric     MI.setDesc(RefII);
11804824e7fdSDimitry Andric     MI.getOperand(0).setReg(0);
1181fe6060f1SDimitry Andric     MI.getOperand(1).ChangeToRegister(0, false);
1182fe6060f1SDimitry Andric   };
1183fe6060f1SDimitry Andric 
1184349cc55cSDimitry Andric   if (!useDebugInstrRef())
1185fe6060f1SDimitry Andric     return;
1186fe6060f1SDimitry Andric 
1187fe6060f1SDimitry Andric   for (auto &MBB : *this) {
1188fe6060f1SDimitry Andric     for (auto &MI : MBB) {
1189fe6060f1SDimitry Andric       if (!MI.isDebugRef() || !MI.getOperand(0).isReg())
1190fe6060f1SDimitry Andric         continue;
1191fe6060f1SDimitry Andric 
1192fe6060f1SDimitry Andric       Register Reg = MI.getOperand(0).getReg();
1193fe6060f1SDimitry Andric 
1194fe6060f1SDimitry Andric       // Some vregs can be deleted as redundant in the meantime. Mark those
11954824e7fdSDimitry Andric       // as DBG_VALUE $noreg. Additionally, some normal instructions are
11964824e7fdSDimitry Andric       // quickly deleted, leaving dangling references to vregs with no def.
11974824e7fdSDimitry Andric       if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
11984824e7fdSDimitry Andric         MakeUndefDbgValue(MI);
1199fe6060f1SDimitry Andric         continue;
1200fe6060f1SDimitry Andric       }
1201fe6060f1SDimitry Andric 
1202fe6060f1SDimitry Andric       assert(Reg.isVirtual());
1203fe6060f1SDimitry Andric       MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1204fe6060f1SDimitry Andric 
1205fe6060f1SDimitry Andric       // If we've found a copy-like instruction, follow it back to the
1206fe6060f1SDimitry Andric       // instruction that defines the source value, see salvageCopySSA docs
1207fe6060f1SDimitry Andric       // for why this is important.
1208fe6060f1SDimitry Andric       if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1209fe6060f1SDimitry Andric         auto Result = salvageCopySSA(DefMI);
1210fe6060f1SDimitry Andric         MI.getOperand(0).ChangeToImmediate(Result.first);
1211fe6060f1SDimitry Andric         MI.getOperand(1).setImm(Result.second);
1212fe6060f1SDimitry Andric       } else {
1213fe6060f1SDimitry Andric         // Otherwise, identify the operand number that the VReg refers to.
1214fe6060f1SDimitry Andric         unsigned OperandIdx = 0;
1215fe6060f1SDimitry Andric         for (const auto &MO : DefMI.operands()) {
1216fe6060f1SDimitry Andric           if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
1217fe6060f1SDimitry Andric             break;
1218fe6060f1SDimitry Andric           ++OperandIdx;
1219fe6060f1SDimitry Andric         }
1220fe6060f1SDimitry Andric         assert(OperandIdx < DefMI.getNumOperands());
1221fe6060f1SDimitry Andric 
1222fe6060f1SDimitry Andric         // Morph this instr ref to point at the given instruction and operand.
1223fe6060f1SDimitry Andric         unsigned ID = DefMI.getDebugInstrNum();
1224fe6060f1SDimitry Andric         MI.getOperand(0).ChangeToImmediate(ID);
1225fe6060f1SDimitry Andric         MI.getOperand(1).setImm(OperandIdx);
1226fe6060f1SDimitry Andric       }
1227fe6060f1SDimitry Andric     }
1228fe6060f1SDimitry Andric   }
1229fe6060f1SDimitry Andric }
1230fe6060f1SDimitry Andric 
1231349cc55cSDimitry Andric bool MachineFunction::useDebugInstrRef() const {
1232349cc55cSDimitry Andric   // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1233349cc55cSDimitry Andric   // have optimized code inlined into this unoptimized code, however with
1234349cc55cSDimitry Andric   // fewer and less aggressive optimizations happening, coverage and accuracy
1235349cc55cSDimitry Andric   // should not suffer.
1236349cc55cSDimitry Andric   if (getTarget().getOptLevel() == CodeGenOpt::None)
1237349cc55cSDimitry Andric     return false;
1238349cc55cSDimitry Andric 
1239349cc55cSDimitry Andric   // Don't use instr-ref if this function is marked optnone.
1240349cc55cSDimitry Andric   if (F.hasFnAttribute(Attribute::OptimizeNone))
1241349cc55cSDimitry Andric     return false;
1242349cc55cSDimitry Andric 
124304eeddc0SDimitry Andric   if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1244349cc55cSDimitry Andric     return true;
1245349cc55cSDimitry Andric 
1246349cc55cSDimitry Andric   return false;
1247349cc55cSDimitry Andric }
1248349cc55cSDimitry Andric 
1249349cc55cSDimitry Andric // Use one million as a high / reserved number.
1250349cc55cSDimitry Andric const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1251349cc55cSDimitry Andric 
1252*0b57cec5SDimitry Andric /// \}
1253*0b57cec5SDimitry Andric 
1254*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1255*0b57cec5SDimitry Andric //  MachineJumpTableInfo implementation
1256*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1257*0b57cec5SDimitry Andric 
1258*0b57cec5SDimitry Andric /// Return the size of each entry in the jump table.
1259*0b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
1260*0b57cec5SDimitry Andric   // The size of a jump table entry is 4 bytes unless the entry is just the
1261*0b57cec5SDimitry Andric   // address of a block, in which case it is the pointer size.
1262*0b57cec5SDimitry Andric   switch (getEntryKind()) {
1263*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_BlockAddress:
1264*0b57cec5SDimitry Andric     return TD.getPointerSize();
1265*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1266*0b57cec5SDimitry Andric     return 8;
1267*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1268*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_LabelDifference32:
1269*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Custom32:
1270*0b57cec5SDimitry Andric     return 4;
1271*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Inline:
1272*0b57cec5SDimitry Andric     return 0;
1273*0b57cec5SDimitry Andric   }
1274*0b57cec5SDimitry Andric   llvm_unreachable("Unknown jump table encoding!");
1275*0b57cec5SDimitry Andric }
1276*0b57cec5SDimitry Andric 
1277*0b57cec5SDimitry Andric /// Return the alignment of each entry in the jump table.
1278*0b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1279*0b57cec5SDimitry Andric   // The alignment of a jump table entry is the alignment of int32 unless the
1280*0b57cec5SDimitry Andric   // entry is just the address of a block, in which case it is the pointer
1281*0b57cec5SDimitry Andric   // alignment.
1282*0b57cec5SDimitry Andric   switch (getEntryKind()) {
1283*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_BlockAddress:
12848bcb0991SDimitry Andric     return TD.getPointerABIAlignment(0).value();
1285*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
12868bcb0991SDimitry Andric     return TD.getABIIntegerTypeAlignment(64).value();
1287*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1288*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_LabelDifference32:
1289*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Custom32:
12908bcb0991SDimitry Andric     return TD.getABIIntegerTypeAlignment(32).value();
1291*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Inline:
1292*0b57cec5SDimitry Andric     return 1;
1293*0b57cec5SDimitry Andric   }
1294*0b57cec5SDimitry Andric   llvm_unreachable("Unknown jump table encoding!");
1295*0b57cec5SDimitry Andric }
1296*0b57cec5SDimitry Andric 
1297*0b57cec5SDimitry Andric /// Create a new jump table entry in the jump table info.
1298*0b57cec5SDimitry Andric unsigned MachineJumpTableInfo::createJumpTableIndex(
1299*0b57cec5SDimitry Andric                                const std::vector<MachineBasicBlock*> &DestBBs) {
1300*0b57cec5SDimitry Andric   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1301*0b57cec5SDimitry Andric   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1302*0b57cec5SDimitry Andric   return JumpTables.size()-1;
1303*0b57cec5SDimitry Andric }
1304*0b57cec5SDimitry Andric 
1305*0b57cec5SDimitry Andric /// If Old is the target of any jump tables, update the jump tables to branch
1306*0b57cec5SDimitry Andric /// to New instead.
1307*0b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1308*0b57cec5SDimitry Andric                                                   MachineBasicBlock *New) {
1309*0b57cec5SDimitry Andric   assert(Old != New && "Not making a change?");
1310*0b57cec5SDimitry Andric   bool MadeChange = false;
1311*0b57cec5SDimitry Andric   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1312*0b57cec5SDimitry Andric     ReplaceMBBInJumpTable(i, Old, New);
1313*0b57cec5SDimitry Andric   return MadeChange;
1314*0b57cec5SDimitry Andric }
1315*0b57cec5SDimitry Andric 
1316e8d8bef9SDimitry Andric /// If MBB is present in any jump tables, remove it.
1317e8d8bef9SDimitry Andric bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1318e8d8bef9SDimitry Andric   bool MadeChange = false;
1319e8d8bef9SDimitry Andric   for (MachineJumpTableEntry &JTE : JumpTables) {
1320e8d8bef9SDimitry Andric     auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1321e8d8bef9SDimitry Andric     MadeChange |= (removeBeginItr != JTE.MBBs.end());
1322e8d8bef9SDimitry Andric     JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1323e8d8bef9SDimitry Andric   }
1324e8d8bef9SDimitry Andric   return MadeChange;
1325e8d8bef9SDimitry Andric }
1326e8d8bef9SDimitry Andric 
1327*0b57cec5SDimitry Andric /// If Old is a target of the jump tables, update the jump table to branch to
1328*0b57cec5SDimitry Andric /// New instead.
1329*0b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1330*0b57cec5SDimitry Andric                                                  MachineBasicBlock *Old,
1331*0b57cec5SDimitry Andric                                                  MachineBasicBlock *New) {
1332*0b57cec5SDimitry Andric   assert(Old != New && "Not making a change?");
1333*0b57cec5SDimitry Andric   bool MadeChange = false;
1334*0b57cec5SDimitry Andric   MachineJumpTableEntry &JTE = JumpTables[Idx];
13354824e7fdSDimitry Andric   for (MachineBasicBlock *&MBB : JTE.MBBs)
13364824e7fdSDimitry Andric     if (MBB == Old) {
13374824e7fdSDimitry Andric       MBB = New;
1338*0b57cec5SDimitry Andric       MadeChange = true;
1339*0b57cec5SDimitry Andric     }
1340*0b57cec5SDimitry Andric   return MadeChange;
1341*0b57cec5SDimitry Andric }
1342*0b57cec5SDimitry Andric 
1343*0b57cec5SDimitry Andric void MachineJumpTableInfo::print(raw_ostream &OS) const {
1344*0b57cec5SDimitry Andric   if (JumpTables.empty()) return;
1345*0b57cec5SDimitry Andric 
1346*0b57cec5SDimitry Andric   OS << "Jump Tables:\n";
1347*0b57cec5SDimitry Andric 
1348*0b57cec5SDimitry Andric   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1349*0b57cec5SDimitry Andric     OS << printJumpTableEntryReference(i) << ':';
13504824e7fdSDimitry Andric     for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
13514824e7fdSDimitry Andric       OS << ' ' << printMBBReference(*MBB);
1352*0b57cec5SDimitry Andric     if (i != e)
1353*0b57cec5SDimitry Andric       OS << '\n';
1354*0b57cec5SDimitry Andric   }
1355*0b57cec5SDimitry Andric 
1356*0b57cec5SDimitry Andric   OS << '\n';
1357*0b57cec5SDimitry Andric }
1358*0b57cec5SDimitry Andric 
1359*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1360*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1361*0b57cec5SDimitry Andric #endif
1362*0b57cec5SDimitry Andric 
1363*0b57cec5SDimitry Andric Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1364*0b57cec5SDimitry Andric   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1365*0b57cec5SDimitry Andric }
1366*0b57cec5SDimitry Andric 
1367*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1368*0b57cec5SDimitry Andric //  MachineConstantPool implementation
1369*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1370*0b57cec5SDimitry Andric 
1371*0b57cec5SDimitry Andric void MachineConstantPoolValue::anchor() {}
1372*0b57cec5SDimitry Andric 
1373e8d8bef9SDimitry Andric unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1374e8d8bef9SDimitry Andric   return DL.getTypeAllocSize(Ty);
1375e8d8bef9SDimitry Andric }
1376e8d8bef9SDimitry Andric 
1377e8d8bef9SDimitry Andric unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1378*0b57cec5SDimitry Andric   if (isMachineConstantPoolEntry())
1379e8d8bef9SDimitry Andric     return Val.MachineCPVal->getSizeInBytes(DL);
1380e8d8bef9SDimitry Andric   return DL.getTypeAllocSize(Val.ConstVal->getType());
1381*0b57cec5SDimitry Andric }
1382*0b57cec5SDimitry Andric 
1383*0b57cec5SDimitry Andric bool MachineConstantPoolEntry::needsRelocation() const {
1384*0b57cec5SDimitry Andric   if (isMachineConstantPoolEntry())
1385*0b57cec5SDimitry Andric     return true;
1386fe6060f1SDimitry Andric   return Val.ConstVal->needsDynamicRelocation();
1387*0b57cec5SDimitry Andric }
1388*0b57cec5SDimitry Andric 
1389*0b57cec5SDimitry Andric SectionKind
1390*0b57cec5SDimitry Andric MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1391*0b57cec5SDimitry Andric   if (needsRelocation())
1392*0b57cec5SDimitry Andric     return SectionKind::getReadOnlyWithRel();
1393e8d8bef9SDimitry Andric   switch (getSizeInBytes(*DL)) {
1394*0b57cec5SDimitry Andric   case 4:
1395*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst4();
1396*0b57cec5SDimitry Andric   case 8:
1397*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst8();
1398*0b57cec5SDimitry Andric   case 16:
1399*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst16();
1400*0b57cec5SDimitry Andric   case 32:
1401*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst32();
1402*0b57cec5SDimitry Andric   default:
1403*0b57cec5SDimitry Andric     return SectionKind::getReadOnly();
1404*0b57cec5SDimitry Andric   }
1405*0b57cec5SDimitry Andric }
1406*0b57cec5SDimitry Andric 
1407*0b57cec5SDimitry Andric MachineConstantPool::~MachineConstantPool() {
1408*0b57cec5SDimitry Andric   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1409*0b57cec5SDimitry Andric   // so keep track of which we've deleted to avoid double deletions.
1410*0b57cec5SDimitry Andric   DenseSet<MachineConstantPoolValue*> Deleted;
14110eae32dcSDimitry Andric   for (const MachineConstantPoolEntry &C : Constants)
14120eae32dcSDimitry Andric     if (C.isMachineConstantPoolEntry()) {
14130eae32dcSDimitry Andric       Deleted.insert(C.Val.MachineCPVal);
14140eae32dcSDimitry Andric       delete C.Val.MachineCPVal;
1415*0b57cec5SDimitry Andric     }
1416fe6060f1SDimitry Andric   for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1417fe6060f1SDimitry Andric     if (Deleted.count(CPV) == 0)
1418fe6060f1SDimitry Andric       delete CPV;
1419*0b57cec5SDimitry Andric   }
1420*0b57cec5SDimitry Andric }
1421*0b57cec5SDimitry Andric 
1422*0b57cec5SDimitry Andric /// Test whether the given two constants can be allocated the same constant pool
1423*0b57cec5SDimitry Andric /// entry.
1424*0b57cec5SDimitry Andric static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1425*0b57cec5SDimitry Andric                                       const DataLayout &DL) {
1426*0b57cec5SDimitry Andric   // Handle the trivial case quickly.
1427*0b57cec5SDimitry Andric   if (A == B) return true;
1428*0b57cec5SDimitry Andric 
1429*0b57cec5SDimitry Andric   // If they have the same type but weren't the same constant, quickly
1430*0b57cec5SDimitry Andric   // reject them.
1431*0b57cec5SDimitry Andric   if (A->getType() == B->getType()) return false;
1432*0b57cec5SDimitry Andric 
1433*0b57cec5SDimitry Andric   // We can't handle structs or arrays.
1434*0b57cec5SDimitry Andric   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1435*0b57cec5SDimitry Andric       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1436*0b57cec5SDimitry Andric     return false;
1437*0b57cec5SDimitry Andric 
1438*0b57cec5SDimitry Andric   // For now, only support constants with the same size.
1439*0b57cec5SDimitry Andric   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1440*0b57cec5SDimitry Andric   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1441*0b57cec5SDimitry Andric     return false;
1442*0b57cec5SDimitry Andric 
1443*0b57cec5SDimitry Andric   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1444*0b57cec5SDimitry Andric 
1445*0b57cec5SDimitry Andric   // Try constant folding a bitcast of both instructions to an integer.  If we
1446*0b57cec5SDimitry Andric   // get two identical ConstantInt's, then we are good to share them.  We use
1447*0b57cec5SDimitry Andric   // the constant folding APIs to do this so that we get the benefit of
1448*0b57cec5SDimitry Andric   // DataLayout.
1449*0b57cec5SDimitry Andric   if (isa<PointerType>(A->getType()))
1450*0b57cec5SDimitry Andric     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1451*0b57cec5SDimitry Andric                                 const_cast<Constant *>(A), IntTy, DL);
1452*0b57cec5SDimitry Andric   else if (A->getType() != IntTy)
1453*0b57cec5SDimitry Andric     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1454*0b57cec5SDimitry Andric                                 IntTy, DL);
1455*0b57cec5SDimitry Andric   if (isa<PointerType>(B->getType()))
1456*0b57cec5SDimitry Andric     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1457*0b57cec5SDimitry Andric                                 const_cast<Constant *>(B), IntTy, DL);
1458*0b57cec5SDimitry Andric   else if (B->getType() != IntTy)
1459*0b57cec5SDimitry Andric     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1460*0b57cec5SDimitry Andric                                 IntTy, DL);
1461*0b57cec5SDimitry Andric 
1462*0b57cec5SDimitry Andric   return A == B;
1463*0b57cec5SDimitry Andric }
1464*0b57cec5SDimitry Andric 
1465*0b57cec5SDimitry Andric /// Create a new entry in the constant pool or return an existing one.
1466*0b57cec5SDimitry Andric /// User must specify the log2 of the minimum required alignment for the object.
1467*0b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
14685ffd83dbSDimitry Andric                                                    Align Alignment) {
1469*0b57cec5SDimitry Andric   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1470*0b57cec5SDimitry Andric 
1471*0b57cec5SDimitry Andric   // Check to see if we already have this constant.
1472*0b57cec5SDimitry Andric   //
1473*0b57cec5SDimitry Andric   // FIXME, this could be made much more efficient for large constant pools.
1474*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1475*0b57cec5SDimitry Andric     if (!Constants[i].isMachineConstantPoolEntry() &&
1476*0b57cec5SDimitry Andric         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
14775ffd83dbSDimitry Andric       if (Constants[i].getAlign() < Alignment)
1478*0b57cec5SDimitry Andric         Constants[i].Alignment = Alignment;
1479*0b57cec5SDimitry Andric       return i;
1480*0b57cec5SDimitry Andric     }
1481*0b57cec5SDimitry Andric 
1482*0b57cec5SDimitry Andric   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1483*0b57cec5SDimitry Andric   return Constants.size()-1;
1484*0b57cec5SDimitry Andric }
1485*0b57cec5SDimitry Andric 
1486*0b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
14875ffd83dbSDimitry Andric                                                    Align Alignment) {
1488*0b57cec5SDimitry Andric   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1489*0b57cec5SDimitry Andric 
1490*0b57cec5SDimitry Andric   // Check to see if we already have this constant.
1491*0b57cec5SDimitry Andric   //
1492*0b57cec5SDimitry Andric   // FIXME, this could be made much more efficient for large constant pools.
1493*0b57cec5SDimitry Andric   int Idx = V->getExistingMachineCPValue(this, Alignment);
1494*0b57cec5SDimitry Andric   if (Idx != -1) {
1495*0b57cec5SDimitry Andric     MachineCPVsSharingEntries.insert(V);
1496*0b57cec5SDimitry Andric     return (unsigned)Idx;
1497*0b57cec5SDimitry Andric   }
1498*0b57cec5SDimitry Andric 
1499*0b57cec5SDimitry Andric   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1500*0b57cec5SDimitry Andric   return Constants.size()-1;
1501*0b57cec5SDimitry Andric }
1502*0b57cec5SDimitry Andric 
1503*0b57cec5SDimitry Andric void MachineConstantPool::print(raw_ostream &OS) const {
1504*0b57cec5SDimitry Andric   if (Constants.empty()) return;
1505*0b57cec5SDimitry Andric 
1506*0b57cec5SDimitry Andric   OS << "Constant Pool:\n";
1507*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1508*0b57cec5SDimitry Andric     OS << "  cp#" << i << ": ";
1509*0b57cec5SDimitry Andric     if (Constants[i].isMachineConstantPoolEntry())
1510*0b57cec5SDimitry Andric       Constants[i].Val.MachineCPVal->print(OS);
1511*0b57cec5SDimitry Andric     else
1512*0b57cec5SDimitry Andric       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
15135ffd83dbSDimitry Andric     OS << ", align=" << Constants[i].getAlign().value();
1514*0b57cec5SDimitry Andric     OS << "\n";
1515*0b57cec5SDimitry Andric   }
1516*0b57cec5SDimitry Andric }
1517*0b57cec5SDimitry Andric 
1518*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1519*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1520*0b57cec5SDimitry Andric #endif
1521