10b57cec5SDimitry Andric //===- MachineFunction.cpp ------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Collect native machine code information for a function.  This allows
100b57cec5SDimitry Andric // target-specific information about the generated code to be stored with each
110b57cec5SDimitry Andric // function.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
160b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
25*fe013be4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
365ffd83dbSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
420b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
430b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
440b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
450b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
460b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
470b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
48*fe013be4SDimitry Andric #include "llvm/IR/EHPersonalities.h"
490b57cec5SDimitry Andric #include "llvm/IR/Function.h"
500b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
510b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
520b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
530b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
540b57cec5SDimitry Andric #include "llvm/IR/Module.h"
550b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
560b57cec5SDimitry Andric #include "llvm/IR/Value.h"
570b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
580b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
590b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
600b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
610b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
620b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
630b57cec5SDimitry Andric #include "llvm/Support/DOTGraphTraits.h"
640b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
650b57cec5SDimitry Andric #include "llvm/Support/GraphWriter.h"
660b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
670b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
680b57cec5SDimitry Andric #include <algorithm>
690b57cec5SDimitry Andric #include <cassert>
700b57cec5SDimitry Andric #include <cstddef>
710b57cec5SDimitry Andric #include <cstdint>
720b57cec5SDimitry Andric #include <iterator>
730b57cec5SDimitry Andric #include <string>
745ffd83dbSDimitry Andric #include <type_traits>
750b57cec5SDimitry Andric #include <utility>
760b57cec5SDimitry Andric #include <vector>
770b57cec5SDimitry Andric 
7804eeddc0SDimitry Andric #include "LiveDebugValues/LiveDebugValues.h"
7904eeddc0SDimitry Andric 
800b57cec5SDimitry Andric using namespace llvm;
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric #define DEBUG_TYPE "codegen"
830b57cec5SDimitry Andric 
848bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllFunctions(
858bcb0991SDimitry Andric     "align-all-functions",
868bcb0991SDimitry Andric     cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
878bcb0991SDimitry Andric              "means align on 16B boundaries)."),
880b57cec5SDimitry Andric     cl::init(0), cl::Hidden);
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
910b57cec5SDimitry Andric   using P = MachineFunctionProperties::Property;
920b57cec5SDimitry Andric 
930eae32dcSDimitry Andric   // clang-format off
940b57cec5SDimitry Andric   switch(Prop) {
950b57cec5SDimitry Andric   case P::FailedISel: return "FailedISel";
960b57cec5SDimitry Andric   case P::IsSSA: return "IsSSA";
970b57cec5SDimitry Andric   case P::Legalized: return "Legalized";
980b57cec5SDimitry Andric   case P::NoPHIs: return "NoPHIs";
990b57cec5SDimitry Andric   case P::NoVRegs: return "NoVRegs";
1000b57cec5SDimitry Andric   case P::RegBankSelected: return "RegBankSelected";
1010b57cec5SDimitry Andric   case P::Selected: return "Selected";
1020b57cec5SDimitry Andric   case P::TracksLiveness: return "TracksLiveness";
1035ffd83dbSDimitry Andric   case P::TiedOpsRewritten: return "TiedOpsRewritten";
104349cc55cSDimitry Andric   case P::FailsVerification: return "FailsVerification";
1050eae32dcSDimitry Andric   case P::TracksDebugUserValues: return "TracksDebugUserValues";
1060b57cec5SDimitry Andric   }
1070eae32dcSDimitry Andric   // clang-format on
1080b57cec5SDimitry Andric   llvm_unreachable("Invalid machine function property");
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric 
11181ad6265SDimitry Andric void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
11281ad6265SDimitry Andric   if (!F.hasFnAttribute(Attribute::SafeStack))
11381ad6265SDimitry Andric     return;
11481ad6265SDimitry Andric 
11581ad6265SDimitry Andric   auto *Existing =
11681ad6265SDimitry Andric       dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
11781ad6265SDimitry Andric 
11881ad6265SDimitry Andric   if (!Existing || Existing->getNumOperands() != 2)
11981ad6265SDimitry Andric     return;
12081ad6265SDimitry Andric 
12181ad6265SDimitry Andric   auto *MetadataName = "unsafe-stack-size";
12281ad6265SDimitry Andric   if (auto &N = Existing->getOperand(0)) {
123*fe013be4SDimitry Andric     if (N.equalsStr(MetadataName)) {
12481ad6265SDimitry Andric       if (auto &Op = Existing->getOperand(1)) {
12581ad6265SDimitry Andric         auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
12681ad6265SDimitry Andric         FrameInfo.setUnsafeStackSize(Val);
12781ad6265SDimitry Andric       }
12881ad6265SDimitry Andric     }
12981ad6265SDimitry Andric   }
13081ad6265SDimitry Andric }
13181ad6265SDimitry Andric 
1320b57cec5SDimitry Andric // Pin the vtable to this file.
1330b57cec5SDimitry Andric void MachineFunction::Delegate::anchor() {}
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric void MachineFunctionProperties::print(raw_ostream &OS) const {
1360b57cec5SDimitry Andric   const char *Separator = "";
1370b57cec5SDimitry Andric   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
1380b57cec5SDimitry Andric     if (!Properties[I])
1390b57cec5SDimitry Andric       continue;
1400b57cec5SDimitry Andric     OS << Separator << getPropertyName(static_cast<Property>(I));
1410b57cec5SDimitry Andric     Separator = ", ";
1420b57cec5SDimitry Andric   }
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1460b57cec5SDimitry Andric // MachineFunction implementation
1470b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric // Out-of-line virtual method.
1500b57cec5SDimitry Andric MachineFunctionInfo::~MachineFunctionInfo() = default;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
1530eae32dcSDimitry Andric   MBB->getParent()->deleteMachineBasicBlock(MBB);
1540b57cec5SDimitry Andric }
1550b57cec5SDimitry Andric 
15681ad6265SDimitry Andric static inline Align getFnStackAlignment(const TargetSubtargetInfo *STI,
1570b57cec5SDimitry Andric                                            const Function &F) {
158349cc55cSDimitry Andric   if (auto MA = F.getFnStackAlign())
15981ad6265SDimitry Andric     return *MA;
16081ad6265SDimitry Andric   return STI->getFrameLowering()->getStackAlign();
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
1635ffd83dbSDimitry Andric MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
1640b57cec5SDimitry Andric                                  const TargetSubtargetInfo &STI,
1650b57cec5SDimitry Andric                                  unsigned FunctionNum, MachineModuleInfo &mmi)
1660b57cec5SDimitry Andric     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
1670b57cec5SDimitry Andric   FunctionNumber = FunctionNum;
1680b57cec5SDimitry Andric   init();
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric void MachineFunction::handleInsertion(MachineInstr &MI) {
1720b57cec5SDimitry Andric   if (TheDelegate)
1730b57cec5SDimitry Andric     TheDelegate->MF_HandleInsertion(MI);
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric void MachineFunction::handleRemoval(MachineInstr &MI) {
1770b57cec5SDimitry Andric   if (TheDelegate)
1780b57cec5SDimitry Andric     TheDelegate->MF_HandleRemoval(MI);
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric void MachineFunction::init() {
1820b57cec5SDimitry Andric   // Assume the function starts in SSA form with correct liveness.
1830b57cec5SDimitry Andric   Properties.set(MachineFunctionProperties::Property::IsSSA);
1840b57cec5SDimitry Andric   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
1850b57cec5SDimitry Andric   if (STI->getRegisterInfo())
1860b57cec5SDimitry Andric     RegInfo = new (Allocator) MachineRegisterInfo(this);
1870b57cec5SDimitry Andric   else
1880b57cec5SDimitry Andric     RegInfo = nullptr;
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   MFInfo = nullptr;
191bdd1243dSDimitry Andric 
1920b57cec5SDimitry Andric   // We can realign the stack if the target supports it and the user hasn't
1930b57cec5SDimitry Andric   // explicitly asked us not to.
1940b57cec5SDimitry Andric   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
1950b57cec5SDimitry Andric                       !F.hasFnAttribute("no-realign-stack");
1960b57cec5SDimitry Andric   FrameInfo = new (Allocator) MachineFrameInfo(
1970b57cec5SDimitry Andric       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
1980b57cec5SDimitry Andric       /*ForcedRealign=*/CanRealignSP &&
1990b57cec5SDimitry Andric           F.hasFnAttribute(Attribute::StackAlignment));
2000b57cec5SDimitry Andric 
20181ad6265SDimitry Andric   setUnsafeStackSize(F, *FrameInfo);
20281ad6265SDimitry Andric 
2030b57cec5SDimitry Andric   if (F.hasFnAttribute(Attribute::StackAlignment))
2045ffd83dbSDimitry Andric     FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
2070b57cec5SDimitry Andric   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
2100b57cec5SDimitry Andric   // FIXME: Use Function::hasOptSize().
2110b57cec5SDimitry Andric   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
2120b57cec5SDimitry Andric     Alignment = std::max(Alignment,
2130b57cec5SDimitry Andric                          STI->getTargetLowering()->getPrefFunctionAlignment());
2140b57cec5SDimitry Andric 
215*fe013be4SDimitry Andric   // -fsanitize=function and -fsanitize=kcfi instrument indirect function calls
216*fe013be4SDimitry Andric   // to load a type hash before the function label. Ensure functions are aligned
217*fe013be4SDimitry Andric   // by a least 4 to avoid unaligned access, which is especially important for
218*fe013be4SDimitry Andric   // -mno-unaligned-access.
219*fe013be4SDimitry Andric   if (F.hasMetadata(LLVMContext::MD_func_sanitize) ||
220*fe013be4SDimitry Andric       F.getMetadata(LLVMContext::MD_kcfi_type))
221*fe013be4SDimitry Andric     Alignment = std::max(Alignment, Align(4));
222*fe013be4SDimitry Andric 
2230b57cec5SDimitry Andric   if (AlignAllFunctions)
2248bcb0991SDimitry Andric     Alignment = Align(1ULL << AlignAllFunctions);
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   JumpTableInfo = nullptr;
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   if (isFuncletEHPersonality(classifyEHPersonality(
2290b57cec5SDimitry Andric           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
2300b57cec5SDimitry Andric     WinEHInfo = new (Allocator) WinEHFuncInfo();
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   if (isScopedEHPersonality(classifyEHPersonality(
2340b57cec5SDimitry Andric           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
2350b57cec5SDimitry Andric     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
2390b57cec5SDimitry Andric          "Can't create a MachineFunction using a Module with a "
2400b57cec5SDimitry Andric          "Target-incompatible DataLayout attached\n");
2410b57cec5SDimitry Andric 
24281ad6265SDimitry Andric   PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric 
245bdd1243dSDimitry Andric void MachineFunction::initTargetMachineFunctionInfo(
246bdd1243dSDimitry Andric     const TargetSubtargetInfo &STI) {
247bdd1243dSDimitry Andric   assert(!MFInfo && "MachineFunctionInfo already set");
248bdd1243dSDimitry Andric   MFInfo = Target.createMachineFunctionInfo(Allocator, F, &STI);
249bdd1243dSDimitry Andric }
250bdd1243dSDimitry Andric 
2510b57cec5SDimitry Andric MachineFunction::~MachineFunction() {
2520b57cec5SDimitry Andric   clear();
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric void MachineFunction::clear() {
2560b57cec5SDimitry Andric   Properties.reset();
2570b57cec5SDimitry Andric   // Don't call destructors on MachineInstr and MachineOperand. All of their
2580b57cec5SDimitry Andric   // memory comes from the BumpPtrAllocator which is about to be purged.
2590b57cec5SDimitry Andric   //
2600b57cec5SDimitry Andric   // Do call MachineBasicBlock destructors, it contains std::vectors.
2610b57cec5SDimitry Andric   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
2620b57cec5SDimitry Andric     I->Insts.clearAndLeakNodesUnsafely();
2630b57cec5SDimitry Andric   MBBNumbering.clear();
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   InstructionRecycler.clear(Allocator);
2660b57cec5SDimitry Andric   OperandRecycler.clear(Allocator);
2670b57cec5SDimitry Andric   BasicBlockRecycler.clear(Allocator);
2680b57cec5SDimitry Andric   CodeViewAnnotations.clear();
2690b57cec5SDimitry Andric   VariableDbgInfos.clear();
2700b57cec5SDimitry Andric   if (RegInfo) {
2710b57cec5SDimitry Andric     RegInfo->~MachineRegisterInfo();
2720b57cec5SDimitry Andric     Allocator.Deallocate(RegInfo);
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric   if (MFInfo) {
2750b57cec5SDimitry Andric     MFInfo->~MachineFunctionInfo();
2760b57cec5SDimitry Andric     Allocator.Deallocate(MFInfo);
2770b57cec5SDimitry Andric   }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   FrameInfo->~MachineFrameInfo();
2800b57cec5SDimitry Andric   Allocator.Deallocate(FrameInfo);
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   ConstantPool->~MachineConstantPool();
2830b57cec5SDimitry Andric   Allocator.Deallocate(ConstantPool);
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   if (JumpTableInfo) {
2860b57cec5SDimitry Andric     JumpTableInfo->~MachineJumpTableInfo();
2870b57cec5SDimitry Andric     Allocator.Deallocate(JumpTableInfo);
2880b57cec5SDimitry Andric   }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   if (WinEHInfo) {
2910b57cec5SDimitry Andric     WinEHInfo->~WinEHFuncInfo();
2920b57cec5SDimitry Andric     Allocator.Deallocate(WinEHInfo);
2930b57cec5SDimitry Andric   }
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   if (WasmEHInfo) {
2960b57cec5SDimitry Andric     WasmEHInfo->~WasmEHFuncInfo();
2970b57cec5SDimitry Andric     Allocator.Deallocate(WasmEHInfo);
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric const DataLayout &MachineFunction::getDataLayout() const {
3020b57cec5SDimitry Andric   return F.getParent()->getDataLayout();
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric /// Get the JumpTableInfo for this function.
3060b57cec5SDimitry Andric /// If it does not already exist, allocate one.
3070b57cec5SDimitry Andric MachineJumpTableInfo *MachineFunction::
3080b57cec5SDimitry Andric getOrCreateJumpTableInfo(unsigned EntryKind) {
3090b57cec5SDimitry Andric   if (JumpTableInfo) return JumpTableInfo;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   JumpTableInfo = new (Allocator)
3120b57cec5SDimitry Andric     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
3130b57cec5SDimitry Andric   return JumpTableInfo;
3140b57cec5SDimitry Andric }
3150b57cec5SDimitry Andric 
316480093f4SDimitry Andric DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
317e8d8bef9SDimitry Andric   return F.getDenormalMode(FPType);
318480093f4SDimitry Andric }
319480093f4SDimitry Andric 
3200b57cec5SDimitry Andric /// Should we be emitting segmented stack stuff for the function
3210b57cec5SDimitry Andric bool MachineFunction::shouldSplitStack() const {
3220b57cec5SDimitry Andric   return getFunction().hasFnAttribute("split-stack");
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
325bdd1243dSDimitry Andric [[nodiscard]] unsigned
3260b57cec5SDimitry Andric MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
3270b57cec5SDimitry Andric   FrameInstructions.push_back(Inst);
3280b57cec5SDimitry Andric   return FrameInstructions.size() - 1;
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric /// This discards all of the MachineBasicBlock numbers and recomputes them.
3320b57cec5SDimitry Andric /// This guarantees that the MBB numbers are sequential, dense, and match the
3330b57cec5SDimitry Andric /// ordering of the blocks within the function.  If a specific MachineBasicBlock
3340b57cec5SDimitry Andric /// is specified, only that block and those after it are renumbered.
3350b57cec5SDimitry Andric void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
3360b57cec5SDimitry Andric   if (empty()) { MBBNumbering.clear(); return; }
3370b57cec5SDimitry Andric   MachineFunction::iterator MBBI, E = end();
3380b57cec5SDimitry Andric   if (MBB == nullptr)
3390b57cec5SDimitry Andric     MBBI = begin();
3400b57cec5SDimitry Andric   else
3410b57cec5SDimitry Andric     MBBI = MBB->getIterator();
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   // Figure out the block number this should have.
3440b57cec5SDimitry Andric   unsigned BlockNo = 0;
3450b57cec5SDimitry Andric   if (MBBI != begin())
3460b57cec5SDimitry Andric     BlockNo = std::prev(MBBI)->getNumber() + 1;
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   for (; MBBI != E; ++MBBI, ++BlockNo) {
3490b57cec5SDimitry Andric     if (MBBI->getNumber() != (int)BlockNo) {
3500b57cec5SDimitry Andric       // Remove use of the old number.
3510b57cec5SDimitry Andric       if (MBBI->getNumber() != -1) {
3520b57cec5SDimitry Andric         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
3530b57cec5SDimitry Andric                "MBB number mismatch!");
3540b57cec5SDimitry Andric         MBBNumbering[MBBI->getNumber()] = nullptr;
3550b57cec5SDimitry Andric       }
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric       // If BlockNo is already taken, set that block's number to -1.
3580b57cec5SDimitry Andric       if (MBBNumbering[BlockNo])
3590b57cec5SDimitry Andric         MBBNumbering[BlockNo]->setNumber(-1);
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric       MBBNumbering[BlockNo] = &*MBBI;
3620b57cec5SDimitry Andric       MBBI->setNumber(BlockNo);
3630b57cec5SDimitry Andric     }
3640b57cec5SDimitry Andric   }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   // Okay, all the blocks are renumbered.  If we have compactified the block
3670b57cec5SDimitry Andric   // numbering, shrink MBBNumbering now.
3680b57cec5SDimitry Andric   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
3690b57cec5SDimitry Andric   MBBNumbering.resize(BlockNo);
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
3725ffd83dbSDimitry Andric /// This method iterates over the basic blocks and assigns their IsBeginSection
3735ffd83dbSDimitry Andric /// and IsEndSection fields. This must be called after MBB layout is finalized
3745ffd83dbSDimitry Andric /// and the SectionID's are assigned to MBBs.
3755ffd83dbSDimitry Andric void MachineFunction::assignBeginEndSections() {
3765ffd83dbSDimitry Andric   front().setIsBeginSection();
3775ffd83dbSDimitry Andric   auto CurrentSectionID = front().getSectionID();
3785ffd83dbSDimitry Andric   for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
3795ffd83dbSDimitry Andric     if (MBBI->getSectionID() == CurrentSectionID)
3805ffd83dbSDimitry Andric       continue;
3815ffd83dbSDimitry Andric     MBBI->setIsBeginSection();
3825ffd83dbSDimitry Andric     std::prev(MBBI)->setIsEndSection();
3835ffd83dbSDimitry Andric     CurrentSectionID = MBBI->getSectionID();
3845ffd83dbSDimitry Andric   }
3855ffd83dbSDimitry Andric   back().setIsEndSection();
3865ffd83dbSDimitry Andric }
3875ffd83dbSDimitry Andric 
3880b57cec5SDimitry Andric /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
3890b57cec5SDimitry Andric MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
3900eae32dcSDimitry Andric                                                   DebugLoc DL,
391e8d8bef9SDimitry Andric                                                   bool NoImplicit) {
3920b57cec5SDimitry Andric   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
3930eae32dcSDimitry Andric       MachineInstr(*this, MCID, std::move(DL), NoImplicit);
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
3970b57cec5SDimitry Andric /// identical in all ways except the instruction has no parent, prev, or next.
3980b57cec5SDimitry Andric MachineInstr *
3990b57cec5SDimitry Andric MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
4000b57cec5SDimitry Andric   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
4010b57cec5SDimitry Andric              MachineInstr(*this, *Orig);
4020b57cec5SDimitry Andric }
4030b57cec5SDimitry Andric 
4040eae32dcSDimitry Andric MachineInstr &MachineFunction::cloneMachineInstrBundle(
4050eae32dcSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
4060eae32dcSDimitry Andric     const MachineInstr &Orig) {
4070b57cec5SDimitry Andric   MachineInstr *FirstClone = nullptr;
4080b57cec5SDimitry Andric   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
4090b57cec5SDimitry Andric   while (true) {
4100b57cec5SDimitry Andric     MachineInstr *Cloned = CloneMachineInstr(&*I);
4110b57cec5SDimitry Andric     MBB.insert(InsertBefore, Cloned);
4120b57cec5SDimitry Andric     if (FirstClone == nullptr) {
4130b57cec5SDimitry Andric       FirstClone = Cloned;
4140b57cec5SDimitry Andric     } else {
4150b57cec5SDimitry Andric       Cloned->bundleWithPred();
4160b57cec5SDimitry Andric     }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric     if (!I->isBundledWithSucc())
4190b57cec5SDimitry Andric       break;
4200b57cec5SDimitry Andric     ++I;
4210b57cec5SDimitry Andric   }
4225ffd83dbSDimitry Andric   // Copy over call site info to the cloned instruction if needed. If Orig is in
4235ffd83dbSDimitry Andric   // a bundle, copyCallSiteInfo takes care of finding the call instruction in
4245ffd83dbSDimitry Andric   // the bundle.
4255ffd83dbSDimitry Andric   if (Orig.shouldUpdateCallSiteInfo())
4265ffd83dbSDimitry Andric     copyCallSiteInfo(&Orig, FirstClone);
4270b57cec5SDimitry Andric   return *FirstClone;
4280b57cec5SDimitry Andric }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric /// Delete the given MachineInstr.
4310b57cec5SDimitry Andric ///
4320b57cec5SDimitry Andric /// This function also serves as the MachineInstr destructor - the real
4330b57cec5SDimitry Andric /// ~MachineInstr() destructor must be empty.
4340eae32dcSDimitry Andric void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
4350b57cec5SDimitry Andric   // Verify that a call site info is at valid state. This assertion should
4360b57cec5SDimitry Andric   // be triggered during the implementation of support for the
4370b57cec5SDimitry Andric   // call site info of a new architecture. If the assertion is triggered,
4380b57cec5SDimitry Andric   // back trace will tell where to insert a call to updateCallSiteInfo().
439*fe013be4SDimitry Andric   assert((!MI->isCandidateForCallSiteEntry() || !CallSitesInfo.contains(MI)) &&
4400b57cec5SDimitry Andric          "Call site info was not updated!");
4410b57cec5SDimitry Andric   // Strip it for parts. The operand array and the MI object itself are
4420b57cec5SDimitry Andric   // independently recyclable.
4430b57cec5SDimitry Andric   if (MI->Operands)
4440b57cec5SDimitry Andric     deallocateOperandArray(MI->CapOperands, MI->Operands);
4450b57cec5SDimitry Andric   // Don't call ~MachineInstr() which must be trivial anyway because
4460b57cec5SDimitry Andric   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
4470b57cec5SDimitry Andric   // destructors.
4480b57cec5SDimitry Andric   InstructionRecycler.Deallocate(Allocator, MI);
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric /// Allocate a new MachineBasicBlock. Use this instead of
4520b57cec5SDimitry Andric /// `new MachineBasicBlock'.
4530b57cec5SDimitry Andric MachineBasicBlock *
4540b57cec5SDimitry Andric MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
455bdd1243dSDimitry Andric   MachineBasicBlock *MBB =
456bdd1243dSDimitry Andric       new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
4570b57cec5SDimitry Andric           MachineBasicBlock(*this, bb);
458bdd1243dSDimitry Andric   // Set BBID for `-basic-block=sections=labels` and
459bdd1243dSDimitry Andric   // `-basic-block-sections=list` to allow robust mapping of profiles to basic
460bdd1243dSDimitry Andric   // blocks.
461bdd1243dSDimitry Andric   if (Target.getBBSectionsType() == BasicBlockSection::Labels ||
462bdd1243dSDimitry Andric       Target.getBBSectionsType() == BasicBlockSection::List)
463bdd1243dSDimitry Andric     MBB->setBBID(NextBBID++);
464bdd1243dSDimitry Andric   return MBB;
4650b57cec5SDimitry Andric }
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric /// Delete the given MachineBasicBlock.
4680eae32dcSDimitry Andric void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
4690b57cec5SDimitry Andric   assert(MBB->getParent() == this && "MBB parent mismatch!");
470e8d8bef9SDimitry Andric   // Clean up any references to MBB in jump tables before deleting it.
471e8d8bef9SDimitry Andric   if (JumpTableInfo)
472e8d8bef9SDimitry Andric     JumpTableInfo->RemoveMBBFromJumpTables(MBB);
4730b57cec5SDimitry Andric   MBB->~MachineBasicBlock();
4740b57cec5SDimitry Andric   BasicBlockRecycler.Deallocate(Allocator, MBB);
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
4780b57cec5SDimitry Andric     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
4795ffd83dbSDimitry Andric     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
4800b57cec5SDimitry Andric     SyncScope::ID SSID, AtomicOrdering Ordering,
4810b57cec5SDimitry Andric     AtomicOrdering FailureOrdering) {
4820b57cec5SDimitry Andric   return new (Allocator)
4830b57cec5SDimitry Andric       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
4840b57cec5SDimitry Andric                         SSID, Ordering, FailureOrdering);
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
487e8d8bef9SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
488fe6060f1SDimitry Andric     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
489fe6060f1SDimitry Andric     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
490fe6060f1SDimitry Andric     SyncScope::ID SSID, AtomicOrdering Ordering,
491fe6060f1SDimitry Andric     AtomicOrdering FailureOrdering) {
492fe6060f1SDimitry Andric   return new (Allocator)
493fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
494fe6060f1SDimitry Andric                         Ordering, FailureOrdering);
495fe6060f1SDimitry Andric }
496fe6060f1SDimitry Andric 
497fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
498fe6060f1SDimitry Andric     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
499fe6060f1SDimitry Andric   return new (Allocator)
500fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
501fe6060f1SDimitry Andric                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
502fe6060f1SDimitry Andric                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
503fe6060f1SDimitry Andric }
504fe6060f1SDimitry Andric 
505fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
506fe6060f1SDimitry Andric     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
507fe6060f1SDimitry Andric   return new (Allocator)
508fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
509fe6060f1SDimitry Andric                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
510fe6060f1SDimitry Andric                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
511e8d8bef9SDimitry Andric }
512e8d8bef9SDimitry Andric 
5130b57cec5SDimitry Andric MachineMemOperand *
5140b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
515fe6060f1SDimitry Andric                                       int64_t Offset, LLT Ty) {
5160b57cec5SDimitry Andric   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // If there is no pointer value, the offset isn't tracked so we need to adjust
5190b57cec5SDimitry Andric   // the base alignment.
5205ffd83dbSDimitry Andric   Align Alignment = PtrInfo.V.isNull()
5215ffd83dbSDimitry Andric                         ? commonAlignment(MMO->getBaseAlign(), Offset)
5225ffd83dbSDimitry Andric                         : MMO->getBaseAlign();
5230b57cec5SDimitry Andric 
524e8d8bef9SDimitry Andric   // Do not preserve ranges, since we don't necessarily know what the high bits
525e8d8bef9SDimitry Andric   // are anymore.
526fe6060f1SDimitry Andric   return new (Allocator) MachineMemOperand(
527fe6060f1SDimitry Andric       PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
528fe6060f1SDimitry Andric       MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
529fe6060f1SDimitry Andric       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
5300b57cec5SDimitry Andric }
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric MachineMemOperand *
5330b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
5340b57cec5SDimitry Andric                                       const AAMDNodes &AAInfo) {
5350b57cec5SDimitry Andric   MachinePointerInfo MPI = MMO->getValue() ?
5360b57cec5SDimitry Andric              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
5370b57cec5SDimitry Andric              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
5380b57cec5SDimitry Andric 
5395ffd83dbSDimitry Andric   return new (Allocator) MachineMemOperand(
5405ffd83dbSDimitry Andric       MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
541fe6060f1SDimitry Andric       MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
5425ffd83dbSDimitry Andric       MMO->getFailureOrdering());
5430b57cec5SDimitry Andric }
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric MachineMemOperand *
5460b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
5470b57cec5SDimitry Andric                                       MachineMemOperand::Flags Flags) {
5480b57cec5SDimitry Andric   return new (Allocator) MachineMemOperand(
5495ffd83dbSDimitry Andric       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
5500b57cec5SDimitry Andric       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
551fe6060f1SDimitry Andric       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric 
554480093f4SDimitry Andric MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
555c14a5a88SDimitry Andric     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
556bdd1243dSDimitry Andric     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
557bdd1243dSDimitry Andric     uint32_t CFIType) {
558c14a5a88SDimitry Andric   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
559bdd1243dSDimitry Andric                                          PostInstrSymbol, HeapAllocMarker,
560bdd1243dSDimitry Andric                                          PCSections, CFIType);
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric const char *MachineFunction::createExternalSymbolName(StringRef Name) {
5640b57cec5SDimitry Andric   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
5650b57cec5SDimitry Andric   llvm::copy(Name, Dest);
5660b57cec5SDimitry Andric   Dest[Name.size()] = 0;
5670b57cec5SDimitry Andric   return Dest;
5680b57cec5SDimitry Andric }
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric uint32_t *MachineFunction::allocateRegMask() {
5710b57cec5SDimitry Andric   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
5720b57cec5SDimitry Andric   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
5730b57cec5SDimitry Andric   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
5740b57cec5SDimitry Andric   memset(Mask, 0, Size * sizeof(Mask[0]));
5750b57cec5SDimitry Andric   return Mask;
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric 
578480093f4SDimitry Andric ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
579480093f4SDimitry Andric   int* AllocMask = Allocator.Allocate<int>(Mask.size());
580480093f4SDimitry Andric   copy(Mask, AllocMask);
581480093f4SDimitry Andric   return {AllocMask, Mask.size()};
582480093f4SDimitry Andric }
583480093f4SDimitry Andric 
5840b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5850b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineFunction::dump() const {
5860b57cec5SDimitry Andric   print(dbgs());
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric #endif
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric StringRef MachineFunction::getName() const {
5910b57cec5SDimitry Andric   return getFunction().getName();
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
5950b57cec5SDimitry Andric   OS << "# Machine code for function " << getName() << ": ";
5960b57cec5SDimitry Andric   getProperties().print(OS);
5970b57cec5SDimitry Andric   OS << '\n';
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   // Print Frame Information
6000b57cec5SDimitry Andric   FrameInfo->print(*this, OS);
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   // Print JumpTable Information
6030b57cec5SDimitry Andric   if (JumpTableInfo)
6040b57cec5SDimitry Andric     JumpTableInfo->print(OS);
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   // Print Constant Pool
6070b57cec5SDimitry Andric   ConstantPool->print(OS);
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   if (RegInfo && !RegInfo->livein_empty()) {
6120b57cec5SDimitry Andric     OS << "Function Live Ins: ";
6130b57cec5SDimitry Andric     for (MachineRegisterInfo::livein_iterator
6140b57cec5SDimitry Andric          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
6150b57cec5SDimitry Andric       OS << printReg(I->first, TRI);
6160b57cec5SDimitry Andric       if (I->second)
6170b57cec5SDimitry Andric         OS << " in " << printReg(I->second, TRI);
6180b57cec5SDimitry Andric       if (std::next(I) != E)
6190b57cec5SDimitry Andric         OS << ", ";
6200b57cec5SDimitry Andric     }
6210b57cec5SDimitry Andric     OS << '\n';
6220b57cec5SDimitry Andric   }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   ModuleSlotTracker MST(getFunction().getParent());
6250b57cec5SDimitry Andric   MST.incorporateFunction(getFunction());
6260b57cec5SDimitry Andric   for (const auto &BB : *this) {
6270b57cec5SDimitry Andric     OS << '\n';
6280b57cec5SDimitry Andric     // If we print the whole function, print it at its most verbose level.
6290b57cec5SDimitry Andric     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
6300b57cec5SDimitry Andric   }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   OS << "\n# End machine code for function " << getName() << ".\n\n";
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric 
635480093f4SDimitry Andric /// True if this function needs frame moves for debug or exceptions.
636480093f4SDimitry Andric bool MachineFunction::needsFrameMoves() const {
637480093f4SDimitry Andric   return getMMI().hasDebugInfo() ||
638480093f4SDimitry Andric          getTarget().Options.ForceDwarfFrameSection ||
639480093f4SDimitry Andric          F.needsUnwindTableEntry();
640480093f4SDimitry Andric }
641480093f4SDimitry Andric 
6420b57cec5SDimitry Andric namespace llvm {
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   template<>
6450b57cec5SDimitry Andric   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
6460b57cec5SDimitry Andric     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric     static std::string getGraphName(const MachineFunction *F) {
6490b57cec5SDimitry Andric       return ("CFG for '" + F->getName() + "' function").str();
6500b57cec5SDimitry Andric     }
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric     std::string getNodeLabel(const MachineBasicBlock *Node,
6530b57cec5SDimitry Andric                              const MachineFunction *Graph) {
6540b57cec5SDimitry Andric       std::string OutStr;
6550b57cec5SDimitry Andric       {
6560b57cec5SDimitry Andric         raw_string_ostream OSS(OutStr);
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric         if (isSimple()) {
6590b57cec5SDimitry Andric           OSS << printMBBReference(*Node);
6600b57cec5SDimitry Andric           if (const BasicBlock *BB = Node->getBasicBlock())
6610b57cec5SDimitry Andric             OSS << ": " << BB->getName();
6620b57cec5SDimitry Andric         } else
6630b57cec5SDimitry Andric           Node->print(OSS);
6640b57cec5SDimitry Andric       }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric       // Process string output to make it nicer...
6690b57cec5SDimitry Andric       for (unsigned i = 0; i != OutStr.length(); ++i)
6700b57cec5SDimitry Andric         if (OutStr[i] == '\n') {                            // Left justify
6710b57cec5SDimitry Andric           OutStr[i] = '\\';
6720b57cec5SDimitry Andric           OutStr.insert(OutStr.begin()+i+1, 'l');
6730b57cec5SDimitry Andric         }
6740b57cec5SDimitry Andric       return OutStr;
6750b57cec5SDimitry Andric     }
6760b57cec5SDimitry Andric   };
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric } // end namespace llvm
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric void MachineFunction::viewCFG() const
6810b57cec5SDimitry Andric {
6820b57cec5SDimitry Andric #ifndef NDEBUG
6830b57cec5SDimitry Andric   ViewGraph(this, "mf" + getName());
6840b57cec5SDimitry Andric #else
6850b57cec5SDimitry Andric   errs() << "MachineFunction::viewCFG is only available in debug builds on "
6860b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
6870b57cec5SDimitry Andric #endif // NDEBUG
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric void MachineFunction::viewCFGOnly() const
6910b57cec5SDimitry Andric {
6920b57cec5SDimitry Andric #ifndef NDEBUG
6930b57cec5SDimitry Andric   ViewGraph(this, "mf" + getName(), true);
6940b57cec5SDimitry Andric #else
6950b57cec5SDimitry Andric   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
6960b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
6970b57cec5SDimitry Andric #endif // NDEBUG
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric /// Add the specified physical register as a live-in value and
7010b57cec5SDimitry Andric /// create a corresponding virtual register for it.
7025ffd83dbSDimitry Andric Register MachineFunction::addLiveIn(MCRegister PReg,
7030b57cec5SDimitry Andric                                     const TargetRegisterClass *RC) {
7040b57cec5SDimitry Andric   MachineRegisterInfo &MRI = getRegInfo();
7055ffd83dbSDimitry Andric   Register VReg = MRI.getLiveInVirtReg(PReg);
7060b57cec5SDimitry Andric   if (VReg) {
7070b57cec5SDimitry Andric     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
7080b57cec5SDimitry Andric     (void)VRegRC;
7090b57cec5SDimitry Andric     // A physical register can be added several times.
7100b57cec5SDimitry Andric     // Between two calls, the register class of the related virtual register
7110b57cec5SDimitry Andric     // may have been constrained to match some operation constraints.
7120b57cec5SDimitry Andric     // In that case, check that the current register class includes the
7130b57cec5SDimitry Andric     // physical register and is a sub class of the specified RC.
7140b57cec5SDimitry Andric     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
7150b57cec5SDimitry Andric                              RC->hasSubClassEq(VRegRC))) &&
7160b57cec5SDimitry Andric             "Register class mismatch!");
7170b57cec5SDimitry Andric     return VReg;
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric   VReg = MRI.createVirtualRegister(RC);
7200b57cec5SDimitry Andric   MRI.addLiveIn(PReg, VReg);
7210b57cec5SDimitry Andric   return VReg;
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric /// Return the MCSymbol for the specified non-empty jump table.
7250b57cec5SDimitry Andric /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
7260b57cec5SDimitry Andric /// normal 'L' label is returned.
7270b57cec5SDimitry Andric MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
7280b57cec5SDimitry Andric                                         bool isLinkerPrivate) const {
7290b57cec5SDimitry Andric   const DataLayout &DL = getDataLayout();
7300b57cec5SDimitry Andric   assert(JumpTableInfo && "No jump tables");
7310b57cec5SDimitry Andric   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
7340b57cec5SDimitry Andric                                      : DL.getPrivateGlobalPrefix();
7350b57cec5SDimitry Andric   SmallString<60> Name;
7360b57cec5SDimitry Andric   raw_svector_ostream(Name)
7370b57cec5SDimitry Andric     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
7380b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol(Name);
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric /// Return a function-local symbol to represent the PIC base.
7420b57cec5SDimitry Andric MCSymbol *MachineFunction::getPICBaseSymbol() const {
7430b57cec5SDimitry Andric   const DataLayout &DL = getDataLayout();
7440b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
7450b57cec5SDimitry Andric                                Twine(getFunctionNumber()) + "$pb");
7460b57cec5SDimitry Andric }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric /// \name Exception Handling
7490b57cec5SDimitry Andric /// \{
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric LandingPadInfo &
7520b57cec5SDimitry Andric MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
7530b57cec5SDimitry Andric   unsigned N = LandingPads.size();
7540b57cec5SDimitry Andric   for (unsigned i = 0; i < N; ++i) {
7550b57cec5SDimitry Andric     LandingPadInfo &LP = LandingPads[i];
7560b57cec5SDimitry Andric     if (LP.LandingPadBlock == LandingPad)
7570b57cec5SDimitry Andric       return LP;
7580b57cec5SDimitry Andric   }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   LandingPads.push_back(LandingPadInfo(LandingPad));
7610b57cec5SDimitry Andric   return LandingPads[N];
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
7650b57cec5SDimitry Andric                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
7660b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
7670b57cec5SDimitry Andric   LP.BeginLabels.push_back(BeginLabel);
7680b57cec5SDimitry Andric   LP.EndLabels.push_back(EndLabel);
7690b57cec5SDimitry Andric }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
7720b57cec5SDimitry Andric   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
7730b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
7740b57cec5SDimitry Andric   LP.LandingPadLabel = LandingPadLabel;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
7770b57cec5SDimitry Andric   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
778bdd1243dSDimitry Andric     // If there's no typeid list specified, then "cleanup" is implicit.
779bdd1243dSDimitry Andric     // Otherwise, id 0 is reserved for the cleanup action.
780bdd1243dSDimitry Andric     if (LPI->isCleanup() && LPI->getNumClauses() != 0)
781bdd1243dSDimitry Andric       LP.TypeIds.push_back(0);
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
7840b57cec5SDimitry Andric     //        correct, but we need to do it this way because of how the DWARF EH
7850b57cec5SDimitry Andric     //        emitter processes the clauses.
7860b57cec5SDimitry Andric     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
7870b57cec5SDimitry Andric       Value *Val = LPI->getClause(I - 1);
7880b57cec5SDimitry Andric       if (LPI->isCatch(I - 1)) {
789bdd1243dSDimitry Andric         LP.TypeIds.push_back(
790bdd1243dSDimitry Andric             getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
7910b57cec5SDimitry Andric       } else {
7920b57cec5SDimitry Andric         // Add filters in a list.
7930b57cec5SDimitry Andric         auto *CVal = cast<Constant>(Val);
794bdd1243dSDimitry Andric         SmallVector<unsigned, 4> FilterList;
795349cc55cSDimitry Andric         for (const Use &U : CVal->operands())
796bdd1243dSDimitry Andric           FilterList.push_back(
797bdd1243dSDimitry Andric               getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
7980b57cec5SDimitry Andric 
799bdd1243dSDimitry Andric         LP.TypeIds.push_back(getFilterIDFor(FilterList));
8000b57cec5SDimitry Andric       }
8010b57cec5SDimitry Andric     }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
804bdd1243dSDimitry Andric     for (unsigned I = CPI->arg_size(); I != 0; --I) {
805bdd1243dSDimitry Andric       auto *TypeInfo =
806bdd1243dSDimitry Andric           dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
807bdd1243dSDimitry Andric       LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
8080b57cec5SDimitry Andric     }
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   } else {
8110b57cec5SDimitry Andric     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
8120b57cec5SDimitry Andric   }
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   return LandingPadLabel;
8150b57cec5SDimitry Andric }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
8180b57cec5SDimitry Andric                                             ArrayRef<unsigned> Sites) {
8190b57cec5SDimitry Andric   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
8230b57cec5SDimitry Andric   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
8240b57cec5SDimitry Andric     if (TypeInfos[i] == TI) return i + 1;
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   TypeInfos.push_back(TI);
8270b57cec5SDimitry Andric   return TypeInfos.size();
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
830bdd1243dSDimitry Andric int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
8310b57cec5SDimitry Andric   // If the new filter coincides with the tail of an existing filter, then
8320b57cec5SDimitry Andric   // re-use the existing filter.  Folding filters more than this requires
8330b57cec5SDimitry Andric   // re-ordering filters and/or their elements - probably not worth it.
834fe6060f1SDimitry Andric   for (unsigned i : FilterEnds) {
835fe6060f1SDimitry Andric     unsigned j = TyIds.size();
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric     while (i && j)
8380b57cec5SDimitry Andric       if (FilterIds[--i] != TyIds[--j])
8390b57cec5SDimitry Andric         goto try_next;
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     if (!j)
8420b57cec5SDimitry Andric       // The new filter coincides with range [i, end) of the existing filter.
8430b57cec5SDimitry Andric       return -(1 + i);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric try_next:;
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // Add the new filter.
8490b57cec5SDimitry Andric   int FilterID = -(1 + FilterIds.size());
8500b57cec5SDimitry Andric   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
851e8d8bef9SDimitry Andric   llvm::append_range(FilterIds, TyIds);
8520b57cec5SDimitry Andric   FilterEnds.push_back(FilterIds.size());
8530b57cec5SDimitry Andric   FilterIds.push_back(0); // terminator
8540b57cec5SDimitry Andric   return FilterID;
8550b57cec5SDimitry Andric }
8560b57cec5SDimitry Andric 
857480093f4SDimitry Andric MachineFunction::CallSiteInfoMap::iterator
858480093f4SDimitry Andric MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
8595ffd83dbSDimitry Andric   assert(MI->isCandidateForCallSiteEntry() &&
8605ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates");
8610b57cec5SDimitry Andric 
8625ffd83dbSDimitry Andric   if (!Target.Options.EmitCallSiteInfo)
863480093f4SDimitry Andric     return CallSitesInfo.end();
864480093f4SDimitry Andric   return CallSitesInfo.find(MI);
8650b57cec5SDimitry Andric }
8660b57cec5SDimitry Andric 
8675ffd83dbSDimitry Andric /// Return the call machine instruction or find a call within bundle.
8685ffd83dbSDimitry Andric static const MachineInstr *getCallInstr(const MachineInstr *MI) {
8695ffd83dbSDimitry Andric   if (!MI->isBundle())
8705ffd83dbSDimitry Andric     return MI;
8710b57cec5SDimitry Andric 
872fcaf7f86SDimitry Andric   for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
8735ffd83dbSDimitry Andric                                     getBundleEnd(MI->getIterator())))
8745ffd83dbSDimitry Andric     if (BMI.isCandidateForCallSiteEntry())
8755ffd83dbSDimitry Andric       return &BMI;
8768bcb0991SDimitry Andric 
8775ffd83dbSDimitry Andric   llvm_unreachable("Unexpected bundle without a call site candidate");
8788bcb0991SDimitry Andric }
8798bcb0991SDimitry Andric 
8808bcb0991SDimitry Andric void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
8815ffd83dbSDimitry Andric   assert(MI->shouldUpdateCallSiteInfo() &&
8825ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
8835ffd83dbSDimitry Andric          "candidates inside bundles");
8845ffd83dbSDimitry Andric 
8855ffd83dbSDimitry Andric   const MachineInstr *CallMI = getCallInstr(MI);
8865ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
8878bcb0991SDimitry Andric   if (CSIt == CallSitesInfo.end())
8888bcb0991SDimitry Andric     return;
8898bcb0991SDimitry Andric   CallSitesInfo.erase(CSIt);
8908bcb0991SDimitry Andric }
8918bcb0991SDimitry Andric 
8928bcb0991SDimitry Andric void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
8938bcb0991SDimitry Andric                                        const MachineInstr *New) {
8945ffd83dbSDimitry Andric   assert(Old->shouldUpdateCallSiteInfo() &&
8955ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
8965ffd83dbSDimitry Andric          "candidates inside bundles");
8978bcb0991SDimitry Andric 
8985ffd83dbSDimitry Andric   if (!New->isCandidateForCallSiteEntry())
8995ffd83dbSDimitry Andric     return eraseCallSiteInfo(Old);
9005ffd83dbSDimitry Andric 
9015ffd83dbSDimitry Andric   const MachineInstr *OldCallMI = getCallInstr(Old);
9025ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9038bcb0991SDimitry Andric   if (CSIt == CallSitesInfo.end())
9048bcb0991SDimitry Andric     return;
9058bcb0991SDimitry Andric 
9068bcb0991SDimitry Andric   CallSiteInfo CSInfo = CSIt->second;
9070b57cec5SDimitry Andric   CallSitesInfo[New] = CSInfo;
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric 
9105ffd83dbSDimitry Andric void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
9115ffd83dbSDimitry Andric                                        const MachineInstr *New) {
9125ffd83dbSDimitry Andric   assert(Old->shouldUpdateCallSiteInfo() &&
9135ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9145ffd83dbSDimitry Andric          "candidates inside bundles");
9155ffd83dbSDimitry Andric 
9165ffd83dbSDimitry Andric   if (!New->isCandidateForCallSiteEntry())
9175ffd83dbSDimitry Andric     return eraseCallSiteInfo(Old);
9185ffd83dbSDimitry Andric 
9195ffd83dbSDimitry Andric   const MachineInstr *OldCallMI = getCallInstr(Old);
9205ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9215ffd83dbSDimitry Andric   if (CSIt == CallSitesInfo.end())
9225ffd83dbSDimitry Andric     return;
9235ffd83dbSDimitry Andric 
9245ffd83dbSDimitry Andric   CallSiteInfo CSInfo = std::move(CSIt->second);
9255ffd83dbSDimitry Andric   CallSitesInfo.erase(CSIt);
9265ffd83dbSDimitry Andric   CallSitesInfo[New] = CSInfo;
9275ffd83dbSDimitry Andric }
9285ffd83dbSDimitry Andric 
929e8d8bef9SDimitry Andric void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
930e8d8bef9SDimitry Andric   DebugInstrNumberingCount = Num;
931e8d8bef9SDimitry Andric }
932e8d8bef9SDimitry Andric 
933e8d8bef9SDimitry Andric void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
934fe6060f1SDimitry Andric                                                  DebugInstrOperandPair B,
935fe6060f1SDimitry Andric                                                  unsigned Subreg) {
936fe6060f1SDimitry Andric   // Catch any accidental self-loops.
937fe6060f1SDimitry Andric   assert(A.first != B.first);
938349cc55cSDimitry Andric   // Don't allow any substitutions _from_ the memory operand number.
939349cc55cSDimitry Andric   assert(A.second != DebugOperandMemNumber);
940349cc55cSDimitry Andric 
941fe6060f1SDimitry Andric   DebugValueSubstitutions.push_back({A, B, Subreg});
942e8d8bef9SDimitry Andric }
943e8d8bef9SDimitry Andric 
944e8d8bef9SDimitry Andric void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
945e8d8bef9SDimitry Andric                                                    MachineInstr &New,
946e8d8bef9SDimitry Andric                                                    unsigned MaxOperand) {
947e8d8bef9SDimitry Andric   // If the Old instruction wasn't tracked at all, there is no work to do.
948e8d8bef9SDimitry Andric   unsigned OldInstrNum = Old.peekDebugInstrNum();
949e8d8bef9SDimitry Andric   if (!OldInstrNum)
950e8d8bef9SDimitry Andric     return;
951e8d8bef9SDimitry Andric 
952e8d8bef9SDimitry Andric   // Iterate over all operands looking for defs to create substitutions for.
953e8d8bef9SDimitry Andric   // Avoid creating new instr numbers unless we create a new substitution.
954e8d8bef9SDimitry Andric   // While this has no functional effect, it risks confusing someone reading
955e8d8bef9SDimitry Andric   // MIR output.
956e8d8bef9SDimitry Andric   // Examine all the operands, or the first N specified by the caller.
957e8d8bef9SDimitry Andric   MaxOperand = std::min(MaxOperand, Old.getNumOperands());
958fe6060f1SDimitry Andric   for (unsigned int I = 0; I < MaxOperand; ++I) {
959e8d8bef9SDimitry Andric     const auto &OldMO = Old.getOperand(I);
960e8d8bef9SDimitry Andric     auto &NewMO = New.getOperand(I);
961e8d8bef9SDimitry Andric     (void)NewMO;
962e8d8bef9SDimitry Andric 
963e8d8bef9SDimitry Andric     if (!OldMO.isReg() || !OldMO.isDef())
964e8d8bef9SDimitry Andric       continue;
965e8d8bef9SDimitry Andric     assert(NewMO.isDef());
966e8d8bef9SDimitry Andric 
967e8d8bef9SDimitry Andric     unsigned NewInstrNum = New.getDebugInstrNum();
968e8d8bef9SDimitry Andric     makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
969e8d8bef9SDimitry Andric                                std::make_pair(NewInstrNum, I));
970e8d8bef9SDimitry Andric   }
971e8d8bef9SDimitry Andric }
972e8d8bef9SDimitry Andric 
97381ad6265SDimitry Andric auto MachineFunction::salvageCopySSA(
97481ad6265SDimitry Andric     MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
97581ad6265SDimitry Andric     -> DebugInstrOperandPair {
97681ad6265SDimitry Andric   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
97781ad6265SDimitry Andric 
97881ad6265SDimitry Andric   // Check whether this copy-like instruction has already been salvaged into
97981ad6265SDimitry Andric   // an operand pair.
98081ad6265SDimitry Andric   Register Dest;
98181ad6265SDimitry Andric   if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
98281ad6265SDimitry Andric     Dest = CopyDstSrc->Destination->getReg();
98381ad6265SDimitry Andric   } else {
98481ad6265SDimitry Andric     assert(MI.isSubregToReg());
98581ad6265SDimitry Andric     Dest = MI.getOperand(0).getReg();
98681ad6265SDimitry Andric   }
98781ad6265SDimitry Andric 
98881ad6265SDimitry Andric   auto CacheIt = DbgPHICache.find(Dest);
98981ad6265SDimitry Andric   if (CacheIt != DbgPHICache.end())
99081ad6265SDimitry Andric     return CacheIt->second;
99181ad6265SDimitry Andric 
99281ad6265SDimitry Andric   // Calculate the instruction number to use, or install a DBG_PHI.
99381ad6265SDimitry Andric   auto OperandPair = salvageCopySSAImpl(MI);
99481ad6265SDimitry Andric   DbgPHICache.insert({Dest, OperandPair});
99581ad6265SDimitry Andric   return OperandPair;
99681ad6265SDimitry Andric }
99781ad6265SDimitry Andric 
99881ad6265SDimitry Andric auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
999fe6060f1SDimitry Andric     -> DebugInstrOperandPair {
1000fe6060f1SDimitry Andric   MachineRegisterInfo &MRI = getRegInfo();
1001fe6060f1SDimitry Andric   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1002fe6060f1SDimitry Andric   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1003fe6060f1SDimitry Andric 
1004fe6060f1SDimitry Andric   // Chase the value read by a copy-like instruction back to the instruction
1005fe6060f1SDimitry Andric   // that ultimately _defines_ that value. This may pass:
1006fe6060f1SDimitry Andric   //  * Through multiple intermediate copies, including subregister moves /
1007fe6060f1SDimitry Andric   //    copies,
1008fe6060f1SDimitry Andric   //  * Copies from physical registers that must then be traced back to the
1009fe6060f1SDimitry Andric   //    defining instruction,
1010fe6060f1SDimitry Andric   //  * Or, physical registers may be live-in to (only) the entry block, which
1011fe6060f1SDimitry Andric   //    requires a DBG_PHI to be created.
1012fe6060f1SDimitry Andric   // We can pursue this problem in that order: trace back through copies,
1013fe6060f1SDimitry Andric   // optionally through a physical register, to a defining instruction. We
1014fe6060f1SDimitry Andric   // should never move from physreg to vreg. As we're still in SSA form, no need
1015fe6060f1SDimitry Andric   // to worry about partial definitions of registers.
1016fe6060f1SDimitry Andric 
1017fe6060f1SDimitry Andric   // Helper lambda to interpret a copy-like instruction. Takes instruction,
1018fe6060f1SDimitry Andric   // returns the register read and any subregister identifying which part is
1019fe6060f1SDimitry Andric   // read.
1020fe6060f1SDimitry Andric   auto GetRegAndSubreg =
1021fe6060f1SDimitry Andric       [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1022fe6060f1SDimitry Andric     Register NewReg, OldReg;
1023fe6060f1SDimitry Andric     unsigned SubReg;
1024fe6060f1SDimitry Andric     if (Cpy.isCopy()) {
1025fe6060f1SDimitry Andric       OldReg = Cpy.getOperand(0).getReg();
1026fe6060f1SDimitry Andric       NewReg = Cpy.getOperand(1).getReg();
1027fe6060f1SDimitry Andric       SubReg = Cpy.getOperand(1).getSubReg();
1028fe6060f1SDimitry Andric     } else if (Cpy.isSubregToReg()) {
1029fe6060f1SDimitry Andric       OldReg = Cpy.getOperand(0).getReg();
1030fe6060f1SDimitry Andric       NewReg = Cpy.getOperand(2).getReg();
1031fe6060f1SDimitry Andric       SubReg = Cpy.getOperand(3).getImm();
1032fe6060f1SDimitry Andric     } else {
1033fe6060f1SDimitry Andric       auto CopyDetails = *TII.isCopyInstr(Cpy);
1034fe6060f1SDimitry Andric       const MachineOperand &Src = *CopyDetails.Source;
1035fe6060f1SDimitry Andric       const MachineOperand &Dest = *CopyDetails.Destination;
1036fe6060f1SDimitry Andric       OldReg = Dest.getReg();
1037fe6060f1SDimitry Andric       NewReg = Src.getReg();
1038fe6060f1SDimitry Andric       SubReg = Src.getSubReg();
1039fe6060f1SDimitry Andric     }
1040fe6060f1SDimitry Andric 
1041fe6060f1SDimitry Andric     return {NewReg, SubReg};
1042fe6060f1SDimitry Andric   };
1043fe6060f1SDimitry Andric 
1044fe6060f1SDimitry Andric   // First seek either the defining instruction, or a copy from a physreg.
1045fe6060f1SDimitry Andric   // During search, the current state is the current copy instruction, and which
1046fe6060f1SDimitry Andric   // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1047fe6060f1SDimitry Andric   // deal with those later.
1048fe6060f1SDimitry Andric   auto State = GetRegAndSubreg(MI);
1049fe6060f1SDimitry Andric   auto CurInst = MI.getIterator();
1050fe6060f1SDimitry Andric   SmallVector<unsigned, 4> SubregsSeen;
1051fe6060f1SDimitry Andric   while (true) {
1052fe6060f1SDimitry Andric     // If we've found a copy from a physreg, first portion of search is over.
1053fe6060f1SDimitry Andric     if (!State.first.isVirtual())
1054fe6060f1SDimitry Andric       break;
1055fe6060f1SDimitry Andric 
1056fe6060f1SDimitry Andric     // Record any subregister qualifier.
1057fe6060f1SDimitry Andric     if (State.second)
1058fe6060f1SDimitry Andric       SubregsSeen.push_back(State.second);
1059fe6060f1SDimitry Andric 
1060fe6060f1SDimitry Andric     assert(MRI.hasOneDef(State.first));
1061fe6060f1SDimitry Andric     MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1062fe6060f1SDimitry Andric     CurInst = Inst.getIterator();
1063fe6060f1SDimitry Andric 
1064fe6060f1SDimitry Andric     // Any non-copy instruction is the defining instruction we're seeking.
1065fe6060f1SDimitry Andric     if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1066fe6060f1SDimitry Andric       break;
1067fe6060f1SDimitry Andric     State = GetRegAndSubreg(Inst);
1068fe6060f1SDimitry Andric   };
1069fe6060f1SDimitry Andric 
1070fe6060f1SDimitry Andric   // Helper lambda to apply additional subregister substitutions to a known
1071fe6060f1SDimitry Andric   // instruction/operand pair. Adds new (fake) substitutions so that we can
1072fe6060f1SDimitry Andric   // record the subregister. FIXME: this isn't very space efficient if multiple
1073fe6060f1SDimitry Andric   // values are tracked back through the same copies; cache something later.
1074fe6060f1SDimitry Andric   auto ApplySubregisters =
1075fe6060f1SDimitry Andric       [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1076fe6060f1SDimitry Andric     for (unsigned Subreg : reverse(SubregsSeen)) {
1077fe6060f1SDimitry Andric       // Fetch a new instruction number, not attached to an actual instruction.
1078fe6060f1SDimitry Andric       unsigned NewInstrNumber = getNewDebugInstrNum();
1079fe6060f1SDimitry Andric       // Add a substitution from the "new" number to the known one, with a
1080fe6060f1SDimitry Andric       // qualifying subreg.
1081fe6060f1SDimitry Andric       makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1082fe6060f1SDimitry Andric       // Return the new number; to find the underlying value, consumers need to
1083fe6060f1SDimitry Andric       // deal with the qualifying subreg.
1084fe6060f1SDimitry Andric       P = {NewInstrNumber, 0};
1085fe6060f1SDimitry Andric     }
1086fe6060f1SDimitry Andric     return P;
1087fe6060f1SDimitry Andric   };
1088fe6060f1SDimitry Andric 
1089fe6060f1SDimitry Andric   // If we managed to find the defining instruction after COPYs, return an
1090fe6060f1SDimitry Andric   // instruction / operand pair after adding subregister qualifiers.
1091fe6060f1SDimitry Andric   if (State.first.isVirtual()) {
1092fe6060f1SDimitry Andric     // Virtual register def -- we can just look up where this happens.
1093fe6060f1SDimitry Andric     MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1094*fe013be4SDimitry Andric     for (auto &MO : Inst->all_defs()) {
1095*fe013be4SDimitry Andric       if (MO.getReg() != State.first)
1096fe6060f1SDimitry Andric         continue;
1097*fe013be4SDimitry Andric       return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
1098fe6060f1SDimitry Andric     }
1099fe6060f1SDimitry Andric 
1100fe6060f1SDimitry Andric     llvm_unreachable("Vreg def with no corresponding operand?");
1101fe6060f1SDimitry Andric   }
1102fe6060f1SDimitry Andric 
1103fe6060f1SDimitry Andric   // Our search ended in a copy from a physreg: walk back up the function
1104fe6060f1SDimitry Andric   // looking for whatever defines the physreg.
1105fe6060f1SDimitry Andric   assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1106fe6060f1SDimitry Andric   State = GetRegAndSubreg(*CurInst);
1107fe6060f1SDimitry Andric   Register RegToSeek = State.first;
1108fe6060f1SDimitry Andric 
1109fe6060f1SDimitry Andric   auto RMII = CurInst->getReverseIterator();
1110fe6060f1SDimitry Andric   auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1111fe6060f1SDimitry Andric   for (auto &ToExamine : PrevInstrs) {
1112*fe013be4SDimitry Andric     for (auto &MO : ToExamine.all_defs()) {
1113fe6060f1SDimitry Andric       // Test for operand that defines something aliasing RegToSeek.
1114*fe013be4SDimitry Andric       if (!TRI.regsOverlap(RegToSeek, MO.getReg()))
1115fe6060f1SDimitry Andric         continue;
1116fe6060f1SDimitry Andric 
1117fe6060f1SDimitry Andric       return ApplySubregisters(
1118*fe013be4SDimitry Andric           {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
1119fe6060f1SDimitry Andric     }
1120fe6060f1SDimitry Andric   }
1121fe6060f1SDimitry Andric 
1122fe6060f1SDimitry Andric   MachineBasicBlock &InsertBB = *CurInst->getParent();
1123fe6060f1SDimitry Andric 
1124fe6060f1SDimitry Andric   // We reached the start of the block before finding a defining instruction.
112581ad6265SDimitry Andric   // There are numerous scenarios where this can happen:
112681ad6265SDimitry Andric   // * Constant physical registers,
112781ad6265SDimitry Andric   // * Several intrinsics that allow LLVM-IR to read arbitary registers,
112881ad6265SDimitry Andric   // * Arguments in the entry block,
112981ad6265SDimitry Andric   // * Exception handling landing pads.
113081ad6265SDimitry Andric   // Validating all of them is too difficult, so just insert a DBG_PHI reading
113181ad6265SDimitry Andric   // the variable value at this position, rather than checking it makes sense.
1132fe6060f1SDimitry Andric 
1133fe6060f1SDimitry Andric   // Create DBG_PHI for specified physreg.
1134fe6060f1SDimitry Andric   auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1135fe6060f1SDimitry Andric                          TII.get(TargetOpcode::DBG_PHI));
1136349cc55cSDimitry Andric   Builder.addReg(State.first);
1137fe6060f1SDimitry Andric   unsigned NewNum = getNewDebugInstrNum();
1138fe6060f1SDimitry Andric   Builder.addImm(NewNum);
1139fe6060f1SDimitry Andric   return ApplySubregisters({NewNum, 0u});
1140fe6060f1SDimitry Andric }
1141fe6060f1SDimitry Andric 
1142fe6060f1SDimitry Andric void MachineFunction::finalizeDebugInstrRefs() {
1143fe6060f1SDimitry Andric   auto *TII = getSubtarget().getInstrInfo();
1144fe6060f1SDimitry Andric 
11454824e7fdSDimitry Andric   auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1146bdd1243dSDimitry Andric     const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
1147fe6060f1SDimitry Andric     MI.setDesc(RefII);
1148bdd1243dSDimitry Andric     MI.setDebugValueUndef();
1149fe6060f1SDimitry Andric   };
1150fe6060f1SDimitry Andric 
115181ad6265SDimitry Andric   DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
1152fe6060f1SDimitry Andric   for (auto &MBB : *this) {
1153fe6060f1SDimitry Andric     for (auto &MI : MBB) {
1154bdd1243dSDimitry Andric       if (!MI.isDebugRef())
1155fe6060f1SDimitry Andric         continue;
1156fe6060f1SDimitry Andric 
1157bdd1243dSDimitry Andric       bool IsValidRef = true;
1158bdd1243dSDimitry Andric 
1159bdd1243dSDimitry Andric       for (MachineOperand &MO : MI.debug_operands()) {
1160bdd1243dSDimitry Andric         if (!MO.isReg())
1161bdd1243dSDimitry Andric           continue;
1162bdd1243dSDimitry Andric 
1163bdd1243dSDimitry Andric         Register Reg = MO.getReg();
1164fe6060f1SDimitry Andric 
1165fe6060f1SDimitry Andric         // Some vregs can be deleted as redundant in the meantime. Mark those
11664824e7fdSDimitry Andric         // as DBG_VALUE $noreg. Additionally, some normal instructions are
11674824e7fdSDimitry Andric         // quickly deleted, leaving dangling references to vregs with no def.
11684824e7fdSDimitry Andric         if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1169bdd1243dSDimitry Andric           IsValidRef = false;
1170bdd1243dSDimitry Andric           break;
1171fe6060f1SDimitry Andric         }
1172fe6060f1SDimitry Andric 
1173fe6060f1SDimitry Andric         assert(Reg.isVirtual());
1174fe6060f1SDimitry Andric         MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1175fe6060f1SDimitry Andric 
1176fe6060f1SDimitry Andric         // If we've found a copy-like instruction, follow it back to the
1177fe6060f1SDimitry Andric         // instruction that defines the source value, see salvageCopySSA docs
1178fe6060f1SDimitry Andric         // for why this is important.
1179fe6060f1SDimitry Andric         if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
118081ad6265SDimitry Andric           auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1181bdd1243dSDimitry Andric           MO.ChangeToDbgInstrRef(Result.first, Result.second);
1182fe6060f1SDimitry Andric         } else {
1183fe6060f1SDimitry Andric           // Otherwise, identify the operand number that the VReg refers to.
1184fe6060f1SDimitry Andric           unsigned OperandIdx = 0;
1185bdd1243dSDimitry Andric           for (const auto &DefMO : DefMI.operands()) {
1186bdd1243dSDimitry Andric             if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1187fe6060f1SDimitry Andric               break;
1188fe6060f1SDimitry Andric             ++OperandIdx;
1189fe6060f1SDimitry Andric           }
1190fe6060f1SDimitry Andric           assert(OperandIdx < DefMI.getNumOperands());
1191fe6060f1SDimitry Andric 
1192fe6060f1SDimitry Andric           // Morph this instr ref to point at the given instruction and operand.
1193fe6060f1SDimitry Andric           unsigned ID = DefMI.getDebugInstrNum();
1194bdd1243dSDimitry Andric           MO.ChangeToDbgInstrRef(ID, OperandIdx);
1195fe6060f1SDimitry Andric         }
1196fe6060f1SDimitry Andric       }
1197bdd1243dSDimitry Andric 
1198bdd1243dSDimitry Andric       if (!IsValidRef)
1199bdd1243dSDimitry Andric         MakeUndefDbgValue(MI);
1200bdd1243dSDimitry Andric     }
1201fe6060f1SDimitry Andric   }
1202fe6060f1SDimitry Andric }
1203fe6060f1SDimitry Andric 
1204bdd1243dSDimitry Andric bool MachineFunction::shouldUseDebugInstrRef() const {
1205349cc55cSDimitry Andric   // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1206349cc55cSDimitry Andric   // have optimized code inlined into this unoptimized code, however with
1207349cc55cSDimitry Andric   // fewer and less aggressive optimizations happening, coverage and accuracy
1208349cc55cSDimitry Andric   // should not suffer.
1209349cc55cSDimitry Andric   if (getTarget().getOptLevel() == CodeGenOpt::None)
1210349cc55cSDimitry Andric     return false;
1211349cc55cSDimitry Andric 
1212349cc55cSDimitry Andric   // Don't use instr-ref if this function is marked optnone.
1213349cc55cSDimitry Andric   if (F.hasFnAttribute(Attribute::OptimizeNone))
1214349cc55cSDimitry Andric     return false;
1215349cc55cSDimitry Andric 
121604eeddc0SDimitry Andric   if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1217349cc55cSDimitry Andric     return true;
1218349cc55cSDimitry Andric 
1219349cc55cSDimitry Andric   return false;
1220349cc55cSDimitry Andric }
1221349cc55cSDimitry Andric 
1222bdd1243dSDimitry Andric bool MachineFunction::useDebugInstrRef() const {
1223bdd1243dSDimitry Andric   return UseDebugInstrRef;
1224bdd1243dSDimitry Andric }
1225bdd1243dSDimitry Andric 
1226bdd1243dSDimitry Andric void MachineFunction::setUseDebugInstrRef(bool Use) {
1227bdd1243dSDimitry Andric   UseDebugInstrRef = Use;
1228bdd1243dSDimitry Andric }
1229bdd1243dSDimitry Andric 
1230349cc55cSDimitry Andric // Use one million as a high / reserved number.
1231349cc55cSDimitry Andric const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1232349cc55cSDimitry Andric 
12330b57cec5SDimitry Andric /// \}
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12360b57cec5SDimitry Andric //  MachineJumpTableInfo implementation
12370b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric /// Return the size of each entry in the jump table.
12400b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
12410b57cec5SDimitry Andric   // The size of a jump table entry is 4 bytes unless the entry is just the
12420b57cec5SDimitry Andric   // address of a block, in which case it is the pointer size.
12430b57cec5SDimitry Andric   switch (getEntryKind()) {
12440b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_BlockAddress:
12450b57cec5SDimitry Andric     return TD.getPointerSize();
12460b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
12470b57cec5SDimitry Andric     return 8;
12480b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
12490b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_LabelDifference32:
12500b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Custom32:
12510b57cec5SDimitry Andric     return 4;
12520b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Inline:
12530b57cec5SDimitry Andric     return 0;
12540b57cec5SDimitry Andric   }
12550b57cec5SDimitry Andric   llvm_unreachable("Unknown jump table encoding!");
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric /// Return the alignment of each entry in the jump table.
12590b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
12600b57cec5SDimitry Andric   // The alignment of a jump table entry is the alignment of int32 unless the
12610b57cec5SDimitry Andric   // entry is just the address of a block, in which case it is the pointer
12620b57cec5SDimitry Andric   // alignment.
12630b57cec5SDimitry Andric   switch (getEntryKind()) {
12640b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_BlockAddress:
12658bcb0991SDimitry Andric     return TD.getPointerABIAlignment(0).value();
12660b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
12678bcb0991SDimitry Andric     return TD.getABIIntegerTypeAlignment(64).value();
12680b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
12690b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_LabelDifference32:
12700b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Custom32:
12718bcb0991SDimitry Andric     return TD.getABIIntegerTypeAlignment(32).value();
12720b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Inline:
12730b57cec5SDimitry Andric     return 1;
12740b57cec5SDimitry Andric   }
12750b57cec5SDimitry Andric   llvm_unreachable("Unknown jump table encoding!");
12760b57cec5SDimitry Andric }
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric /// Create a new jump table entry in the jump table info.
12790b57cec5SDimitry Andric unsigned MachineJumpTableInfo::createJumpTableIndex(
12800b57cec5SDimitry Andric                                const std::vector<MachineBasicBlock*> &DestBBs) {
12810b57cec5SDimitry Andric   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
12820b57cec5SDimitry Andric   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
12830b57cec5SDimitry Andric   return JumpTables.size()-1;
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric /// If Old is the target of any jump tables, update the jump tables to branch
12870b57cec5SDimitry Andric /// to New instead.
12880b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
12890b57cec5SDimitry Andric                                                   MachineBasicBlock *New) {
12900b57cec5SDimitry Andric   assert(Old != New && "Not making a change?");
12910b57cec5SDimitry Andric   bool MadeChange = false;
12920b57cec5SDimitry Andric   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
12930b57cec5SDimitry Andric     ReplaceMBBInJumpTable(i, Old, New);
12940b57cec5SDimitry Andric   return MadeChange;
12950b57cec5SDimitry Andric }
12960b57cec5SDimitry Andric 
1297e8d8bef9SDimitry Andric /// If MBB is present in any jump tables, remove it.
1298e8d8bef9SDimitry Andric bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1299e8d8bef9SDimitry Andric   bool MadeChange = false;
1300e8d8bef9SDimitry Andric   for (MachineJumpTableEntry &JTE : JumpTables) {
1301e8d8bef9SDimitry Andric     auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1302e8d8bef9SDimitry Andric     MadeChange |= (removeBeginItr != JTE.MBBs.end());
1303e8d8bef9SDimitry Andric     JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1304e8d8bef9SDimitry Andric   }
1305e8d8bef9SDimitry Andric   return MadeChange;
1306e8d8bef9SDimitry Andric }
1307e8d8bef9SDimitry Andric 
13080b57cec5SDimitry Andric /// If Old is a target of the jump tables, update the jump table to branch to
13090b57cec5SDimitry Andric /// New instead.
13100b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
13110b57cec5SDimitry Andric                                                  MachineBasicBlock *Old,
13120b57cec5SDimitry Andric                                                  MachineBasicBlock *New) {
13130b57cec5SDimitry Andric   assert(Old != New && "Not making a change?");
13140b57cec5SDimitry Andric   bool MadeChange = false;
13150b57cec5SDimitry Andric   MachineJumpTableEntry &JTE = JumpTables[Idx];
13164824e7fdSDimitry Andric   for (MachineBasicBlock *&MBB : JTE.MBBs)
13174824e7fdSDimitry Andric     if (MBB == Old) {
13184824e7fdSDimitry Andric       MBB = New;
13190b57cec5SDimitry Andric       MadeChange = true;
13200b57cec5SDimitry Andric     }
13210b57cec5SDimitry Andric   return MadeChange;
13220b57cec5SDimitry Andric }
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric void MachineJumpTableInfo::print(raw_ostream &OS) const {
13250b57cec5SDimitry Andric   if (JumpTables.empty()) return;
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric   OS << "Jump Tables:\n";
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
13300b57cec5SDimitry Andric     OS << printJumpTableEntryReference(i) << ':';
13314824e7fdSDimitry Andric     for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
13324824e7fdSDimitry Andric       OS << ' ' << printMBBReference(*MBB);
13330b57cec5SDimitry Andric     if (i != e)
13340b57cec5SDimitry Andric       OS << '\n';
13350b57cec5SDimitry Andric   }
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric   OS << '\n';
13380b57cec5SDimitry Andric }
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
13410b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
13420b57cec5SDimitry Andric #endif
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric Printable llvm::printJumpTableEntryReference(unsigned Idx) {
13450b57cec5SDimitry Andric   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
13460b57cec5SDimitry Andric }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13490b57cec5SDimitry Andric //  MachineConstantPool implementation
13500b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric void MachineConstantPoolValue::anchor() {}
13530b57cec5SDimitry Andric 
1354e8d8bef9SDimitry Andric unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1355e8d8bef9SDimitry Andric   return DL.getTypeAllocSize(Ty);
1356e8d8bef9SDimitry Andric }
1357e8d8bef9SDimitry Andric 
1358e8d8bef9SDimitry Andric unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
13590b57cec5SDimitry Andric   if (isMachineConstantPoolEntry())
1360e8d8bef9SDimitry Andric     return Val.MachineCPVal->getSizeInBytes(DL);
1361e8d8bef9SDimitry Andric   return DL.getTypeAllocSize(Val.ConstVal->getType());
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric bool MachineConstantPoolEntry::needsRelocation() const {
13650b57cec5SDimitry Andric   if (isMachineConstantPoolEntry())
13660b57cec5SDimitry Andric     return true;
1367fe6060f1SDimitry Andric   return Val.ConstVal->needsDynamicRelocation();
13680b57cec5SDimitry Andric }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric SectionKind
13710b57cec5SDimitry Andric MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
13720b57cec5SDimitry Andric   if (needsRelocation())
13730b57cec5SDimitry Andric     return SectionKind::getReadOnlyWithRel();
1374e8d8bef9SDimitry Andric   switch (getSizeInBytes(*DL)) {
13750b57cec5SDimitry Andric   case 4:
13760b57cec5SDimitry Andric     return SectionKind::getMergeableConst4();
13770b57cec5SDimitry Andric   case 8:
13780b57cec5SDimitry Andric     return SectionKind::getMergeableConst8();
13790b57cec5SDimitry Andric   case 16:
13800b57cec5SDimitry Andric     return SectionKind::getMergeableConst16();
13810b57cec5SDimitry Andric   case 32:
13820b57cec5SDimitry Andric     return SectionKind::getMergeableConst32();
13830b57cec5SDimitry Andric   default:
13840b57cec5SDimitry Andric     return SectionKind::getReadOnly();
13850b57cec5SDimitry Andric   }
13860b57cec5SDimitry Andric }
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric MachineConstantPool::~MachineConstantPool() {
13890b57cec5SDimitry Andric   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
13900b57cec5SDimitry Andric   // so keep track of which we've deleted to avoid double deletions.
13910b57cec5SDimitry Andric   DenseSet<MachineConstantPoolValue*> Deleted;
13920eae32dcSDimitry Andric   for (const MachineConstantPoolEntry &C : Constants)
13930eae32dcSDimitry Andric     if (C.isMachineConstantPoolEntry()) {
13940eae32dcSDimitry Andric       Deleted.insert(C.Val.MachineCPVal);
13950eae32dcSDimitry Andric       delete C.Val.MachineCPVal;
13960b57cec5SDimitry Andric     }
1397fe6060f1SDimitry Andric   for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1398fe6060f1SDimitry Andric     if (Deleted.count(CPV) == 0)
1399fe6060f1SDimitry Andric       delete CPV;
14000b57cec5SDimitry Andric   }
14010b57cec5SDimitry Andric }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric /// Test whether the given two constants can be allocated the same constant pool
1404*fe013be4SDimitry Andric /// entry referenced by \param A.
14050b57cec5SDimitry Andric static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
14060b57cec5SDimitry Andric                                       const DataLayout &DL) {
14070b57cec5SDimitry Andric   // Handle the trivial case quickly.
14080b57cec5SDimitry Andric   if (A == B) return true;
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   // If they have the same type but weren't the same constant, quickly
14110b57cec5SDimitry Andric   // reject them.
14120b57cec5SDimitry Andric   if (A->getType() == B->getType()) return false;
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   // We can't handle structs or arrays.
14150b57cec5SDimitry Andric   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
14160b57cec5SDimitry Andric       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
14170b57cec5SDimitry Andric     return false;
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   // For now, only support constants with the same size.
14200b57cec5SDimitry Andric   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
14210b57cec5SDimitry Andric   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
14220b57cec5SDimitry Andric     return false;
14230b57cec5SDimitry Andric 
1424*fe013be4SDimitry Andric   bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
1425*fe013be4SDimitry Andric 
14260b57cec5SDimitry Andric   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric   // Try constant folding a bitcast of both instructions to an integer.  If we
14290b57cec5SDimitry Andric   // get two identical ConstantInt's, then we are good to share them.  We use
14300b57cec5SDimitry Andric   // the constant folding APIs to do this so that we get the benefit of
14310b57cec5SDimitry Andric   // DataLayout.
14320b57cec5SDimitry Andric   if (isa<PointerType>(A->getType()))
14330b57cec5SDimitry Andric     A = ConstantFoldCastOperand(Instruction::PtrToInt,
14340b57cec5SDimitry Andric                                 const_cast<Constant *>(A), IntTy, DL);
14350b57cec5SDimitry Andric   else if (A->getType() != IntTy)
14360b57cec5SDimitry Andric     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
14370b57cec5SDimitry Andric                                 IntTy, DL);
14380b57cec5SDimitry Andric   if (isa<PointerType>(B->getType()))
14390b57cec5SDimitry Andric     B = ConstantFoldCastOperand(Instruction::PtrToInt,
14400b57cec5SDimitry Andric                                 const_cast<Constant *>(B), IntTy, DL);
14410b57cec5SDimitry Andric   else if (B->getType() != IntTy)
14420b57cec5SDimitry Andric     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
14430b57cec5SDimitry Andric                                 IntTy, DL);
14440b57cec5SDimitry Andric 
1445*fe013be4SDimitry Andric   if (A != B)
1446*fe013be4SDimitry Andric     return false;
1447*fe013be4SDimitry Andric 
1448*fe013be4SDimitry Andric   // Constants only safely match if A doesn't contain undef/poison.
1449*fe013be4SDimitry Andric   // As we'll be reusing A, it doesn't matter if B contain undef/poison.
1450*fe013be4SDimitry Andric   // TODO: Handle cases where A and B have the same undef/poison elements.
1451*fe013be4SDimitry Andric   // TODO: Merge A and B with mismatching undef/poison elements.
1452*fe013be4SDimitry Andric   return !ContainsUndefOrPoisonA;
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric /// Create a new entry in the constant pool or return an existing one.
14560b57cec5SDimitry Andric /// User must specify the log2 of the minimum required alignment for the object.
14570b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
14585ffd83dbSDimitry Andric                                                    Align Alignment) {
14590b57cec5SDimitry Andric   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric   // Check to see if we already have this constant.
14620b57cec5SDimitry Andric   //
14630b57cec5SDimitry Andric   // FIXME, this could be made much more efficient for large constant pools.
14640b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
14650b57cec5SDimitry Andric     if (!Constants[i].isMachineConstantPoolEntry() &&
14660b57cec5SDimitry Andric         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
14675ffd83dbSDimitry Andric       if (Constants[i].getAlign() < Alignment)
14680b57cec5SDimitry Andric         Constants[i].Alignment = Alignment;
14690b57cec5SDimitry Andric       return i;
14700b57cec5SDimitry Andric     }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
14730b57cec5SDimitry Andric   return Constants.size()-1;
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
14775ffd83dbSDimitry Andric                                                    Align Alignment) {
14780b57cec5SDimitry Andric   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric   // Check to see if we already have this constant.
14810b57cec5SDimitry Andric   //
14820b57cec5SDimitry Andric   // FIXME, this could be made much more efficient for large constant pools.
14830b57cec5SDimitry Andric   int Idx = V->getExistingMachineCPValue(this, Alignment);
14840b57cec5SDimitry Andric   if (Idx != -1) {
14850b57cec5SDimitry Andric     MachineCPVsSharingEntries.insert(V);
14860b57cec5SDimitry Andric     return (unsigned)Idx;
14870b57cec5SDimitry Andric   }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
14900b57cec5SDimitry Andric   return Constants.size()-1;
14910b57cec5SDimitry Andric }
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric void MachineConstantPool::print(raw_ostream &OS) const {
14940b57cec5SDimitry Andric   if (Constants.empty()) return;
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric   OS << "Constant Pool:\n";
14970b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
14980b57cec5SDimitry Andric     OS << "  cp#" << i << ": ";
14990b57cec5SDimitry Andric     if (Constants[i].isMachineConstantPoolEntry())
15000b57cec5SDimitry Andric       Constants[i].Val.MachineCPVal->print(OS);
15010b57cec5SDimitry Andric     else
15020b57cec5SDimitry Andric       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
15035ffd83dbSDimitry Andric     OS << ", align=" << Constants[i].getAlign().value();
15040b57cec5SDimitry Andric     OS << "\n";
15050b57cec5SDimitry Andric   }
15060b57cec5SDimitry Andric }
15070b57cec5SDimitry Andric 
1508*fe013be4SDimitry Andric //===----------------------------------------------------------------------===//
1509*fe013be4SDimitry Andric // Template specialization for MachineFunction implementation of
1510*fe013be4SDimitry Andric // ProfileSummaryInfo::getEntryCount().
1511*fe013be4SDimitry Andric //===----------------------------------------------------------------------===//
1512*fe013be4SDimitry Andric template <>
1513*fe013be4SDimitry Andric std::optional<Function::ProfileCount>
1514*fe013be4SDimitry Andric ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
1515*fe013be4SDimitry Andric     const llvm::MachineFunction *F) const {
1516*fe013be4SDimitry Andric   return F->getFunction().getEntryCount();
1517*fe013be4SDimitry Andric }
1518*fe013be4SDimitry Andric 
15190b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
15200b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
15210b57cec5SDimitry Andric #endif
1522