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