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