xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision 1911a50fae8a441b445eb835b98950710d28fc88)
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   MBBNumberingEpoch++;
379 }
380 
381 /// This method iterates over the basic blocks and assigns their IsBeginSection
382 /// and IsEndSection fields. This must be called after MBB layout is finalized
383 /// and the SectionID's are assigned to MBBs.
384 void MachineFunction::assignBeginEndSections() {
385   front().setIsBeginSection();
386   auto CurrentSectionID = front().getSectionID();
387   for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
388     if (MBBI->getSectionID() == CurrentSectionID)
389       continue;
390     MBBI->setIsBeginSection();
391     std::prev(MBBI)->setIsEndSection();
392     CurrentSectionID = MBBI->getSectionID();
393   }
394   back().setIsEndSection();
395 }
396 
397 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
398 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
399                                                   DebugLoc DL,
400                                                   bool NoImplicit) {
401   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
402       MachineInstr(*this, MCID, std::move(DL), NoImplicit);
403 }
404 
405 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
406 /// identical in all ways except the instruction has no parent, prev, or next.
407 MachineInstr *
408 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
409   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
410              MachineInstr(*this, *Orig);
411 }
412 
413 MachineInstr &MachineFunction::cloneMachineInstrBundle(
414     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
415     const MachineInstr &Orig) {
416   MachineInstr *FirstClone = nullptr;
417   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
418   while (true) {
419     MachineInstr *Cloned = CloneMachineInstr(&*I);
420     MBB.insert(InsertBefore, Cloned);
421     if (FirstClone == nullptr) {
422       FirstClone = Cloned;
423     } else {
424       Cloned->bundleWithPred();
425     }
426 
427     if (!I->isBundledWithSucc())
428       break;
429     ++I;
430   }
431   // Copy over call site info to the cloned instruction if needed. If Orig is in
432   // a bundle, copyCallSiteInfo takes care of finding the call instruction in
433   // the bundle.
434   if (Orig.shouldUpdateCallSiteInfo())
435     copyCallSiteInfo(&Orig, FirstClone);
436   return *FirstClone;
437 }
438 
439 /// Delete the given MachineInstr.
440 ///
441 /// This function also serves as the MachineInstr destructor - the real
442 /// ~MachineInstr() destructor must be empty.
443 void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
444   // Verify that a call site info is at valid state. This assertion should
445   // be triggered during the implementation of support for the
446   // call site info of a new architecture. If the assertion is triggered,
447   // back trace will tell where to insert a call to updateCallSiteInfo().
448   assert((!MI->isCandidateForCallSiteEntry() || !CallSitesInfo.contains(MI)) &&
449          "Call site info was not updated!");
450   // Strip it for parts. The operand array and the MI object itself are
451   // independently recyclable.
452   if (MI->Operands)
453     deallocateOperandArray(MI->CapOperands, MI->Operands);
454   // Don't call ~MachineInstr() which must be trivial anyway because
455   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
456   // destructors.
457   InstructionRecycler.Deallocate(Allocator, MI);
458 }
459 
460 /// Allocate a new MachineBasicBlock. Use this instead of
461 /// `new MachineBasicBlock'.
462 MachineBasicBlock *
463 MachineFunction::CreateMachineBasicBlock(const BasicBlock *BB,
464                                          std::optional<UniqueBBID> BBID) {
465   MachineBasicBlock *MBB =
466       new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
467           MachineBasicBlock(*this, BB);
468   // Set BBID for `-basic-block-sections=list` and `-basic-block-address-map` to
469   // allow robust mapping of profiles to basic blocks.
470   if (Target.Options.BBAddrMap ||
471       Target.getBBSectionsType() == BasicBlockSection::List)
472     MBB->setBBID(BBID.has_value() ? *BBID : UniqueBBID{NextBBID++, 0});
473   return MBB;
474 }
475 
476 /// Delete the given MachineBasicBlock.
477 void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
478   assert(MBB->getParent() == this && "MBB parent mismatch!");
479   // Clean up any references to MBB in jump tables before deleting it.
480   if (JumpTableInfo)
481     JumpTableInfo->RemoveMBBFromJumpTables(MBB);
482   MBB->~MachineBasicBlock();
483   BasicBlockRecycler.Deallocate(Allocator, MBB);
484 }
485 
486 MachineMemOperand *MachineFunction::getMachineMemOperand(
487     MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LocationSize Size,
488     Align BaseAlignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
489     SyncScope::ID SSID, AtomicOrdering Ordering,
490     AtomicOrdering FailureOrdering) {
491   assert((!Size.hasValue() ||
492           Size.getValue().getKnownMinValue() != ~UINT64_C(0)) &&
493          "Unexpected an unknown size to be represented using "
494          "LocationSize::beforeOrAfter()");
495   return new (Allocator)
496       MachineMemOperand(PtrInfo, F, Size, BaseAlignment, AAInfo, Ranges, SSID,
497                         Ordering, FailureOrdering);
498 }
499 
500 MachineMemOperand *MachineFunction::getMachineMemOperand(
501     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
502     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
503     SyncScope::ID SSID, AtomicOrdering Ordering,
504     AtomicOrdering FailureOrdering) {
505   return new (Allocator)
506       MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
507                         Ordering, FailureOrdering);
508 }
509 
510 MachineMemOperand *
511 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
512                                       const MachinePointerInfo &PtrInfo,
513                                       LocationSize Size) {
514   assert((!Size.hasValue() ||
515           Size.getValue().getKnownMinValue() != ~UINT64_C(0)) &&
516          "Unexpected an unknown size to be represented using "
517          "LocationSize::beforeOrAfter()");
518   return new (Allocator)
519       MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
520                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
521                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
522 }
523 
524 MachineMemOperand *MachineFunction::getMachineMemOperand(
525     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
526   return new (Allocator)
527       MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
528                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
529                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
530 }
531 
532 MachineMemOperand *
533 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
534                                       int64_t Offset, LLT Ty) {
535   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
536 
537   // If there is no pointer value, the offset isn't tracked so we need to adjust
538   // the base alignment.
539   Align Alignment = PtrInfo.V.isNull()
540                         ? commonAlignment(MMO->getBaseAlign(), Offset)
541                         : MMO->getBaseAlign();
542 
543   // Do not preserve ranges, since we don't necessarily know what the high bits
544   // are anymore.
545   return new (Allocator) MachineMemOperand(
546       PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
547       MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
548       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
549 }
550 
551 MachineMemOperand *
552 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
553                                       const AAMDNodes &AAInfo) {
554   MachinePointerInfo MPI = MMO->getValue() ?
555              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
556              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
557 
558   return new (Allocator) MachineMemOperand(
559       MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
560       MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
561       MMO->getFailureOrdering());
562 }
563 
564 MachineMemOperand *
565 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
566                                       MachineMemOperand::Flags Flags) {
567   return new (Allocator) MachineMemOperand(
568       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
569       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
570       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
571 }
572 
573 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
574     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
575     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
576     uint32_t CFIType, MDNode *MMRAs) {
577   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
578                                          PostInstrSymbol, HeapAllocMarker,
579                                          PCSections, CFIType, MMRAs);
580 }
581 
582 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
583   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
584   llvm::copy(Name, Dest);
585   Dest[Name.size()] = 0;
586   return Dest;
587 }
588 
589 uint32_t *MachineFunction::allocateRegMask() {
590   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
591   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
592   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
593   memset(Mask, 0, Size * sizeof(Mask[0]));
594   return Mask;
595 }
596 
597 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
598   int* AllocMask = Allocator.Allocate<int>(Mask.size());
599   copy(Mask, AllocMask);
600   return {AllocMask, Mask.size()};
601 }
602 
603 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
604 LLVM_DUMP_METHOD void MachineFunction::dump() const {
605   print(dbgs());
606 }
607 #endif
608 
609 StringRef MachineFunction::getName() const {
610   return getFunction().getName();
611 }
612 
613 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
614   OS << "# Machine code for function " << getName() << ": ";
615   getProperties().print(OS);
616   OS << '\n';
617 
618   // Print Frame Information
619   FrameInfo->print(*this, OS);
620 
621   // Print JumpTable Information
622   if (JumpTableInfo)
623     JumpTableInfo->print(OS);
624 
625   // Print Constant Pool
626   ConstantPool->print(OS);
627 
628   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
629 
630   if (RegInfo && !RegInfo->livein_empty()) {
631     OS << "Function Live Ins: ";
632     for (MachineRegisterInfo::livein_iterator
633          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
634       OS << printReg(I->first, TRI);
635       if (I->second)
636         OS << " in " << printReg(I->second, TRI);
637       if (std::next(I) != E)
638         OS << ", ";
639     }
640     OS << '\n';
641   }
642 
643   ModuleSlotTracker MST(getFunction().getParent());
644   MST.incorporateFunction(getFunction());
645   for (const auto &BB : *this) {
646     OS << '\n';
647     // If we print the whole function, print it at its most verbose level.
648     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
649   }
650 
651   OS << "\n# End machine code for function " << getName() << ".\n\n";
652 }
653 
654 /// True if this function needs frame moves for debug or exceptions.
655 bool MachineFunction::needsFrameMoves() const {
656   // TODO: Ideally, what we'd like is to have a switch that allows emitting
657   // synchronous (precise at call-sites only) CFA into .eh_frame. However, even
658   // under this switch, we'd like .debug_frame to be precise when using -g. At
659   // this moment, there's no way to specify that some CFI directives go into
660   // .eh_frame only, while others go into .debug_frame only.
661   return getTarget().Options.ForceDwarfFrameSection ||
662          F.needsUnwindTableEntry() ||
663          !F.getParent()->debug_compile_units().empty();
664 }
665 
666 namespace llvm {
667 
668   template<>
669   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
670     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
671 
672     static std::string getGraphName(const MachineFunction *F) {
673       return ("CFG for '" + F->getName() + "' function").str();
674     }
675 
676     std::string getNodeLabel(const MachineBasicBlock *Node,
677                              const MachineFunction *Graph) {
678       std::string OutStr;
679       {
680         raw_string_ostream OSS(OutStr);
681 
682         if (isSimple()) {
683           OSS << printMBBReference(*Node);
684           if (const BasicBlock *BB = Node->getBasicBlock())
685             OSS << ": " << BB->getName();
686         } else
687           Node->print(OSS);
688       }
689 
690       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
691 
692       // Process string output to make it nicer...
693       for (unsigned i = 0; i != OutStr.length(); ++i)
694         if (OutStr[i] == '\n') {                            // Left justify
695           OutStr[i] = '\\';
696           OutStr.insert(OutStr.begin()+i+1, 'l');
697         }
698       return OutStr;
699     }
700   };
701 
702 } // end namespace llvm
703 
704 void MachineFunction::viewCFG() const
705 {
706 #ifndef NDEBUG
707   ViewGraph(this, "mf" + getName());
708 #else
709   errs() << "MachineFunction::viewCFG is only available in debug builds on "
710          << "systems with Graphviz or gv!\n";
711 #endif // NDEBUG
712 }
713 
714 void MachineFunction::viewCFGOnly() const
715 {
716 #ifndef NDEBUG
717   ViewGraph(this, "mf" + getName(), true);
718 #else
719   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
720          << "systems with Graphviz or gv!\n";
721 #endif // NDEBUG
722 }
723 
724 /// Add the specified physical register as a live-in value and
725 /// create a corresponding virtual register for it.
726 Register MachineFunction::addLiveIn(MCRegister PReg,
727                                     const TargetRegisterClass *RC) {
728   MachineRegisterInfo &MRI = getRegInfo();
729   Register VReg = MRI.getLiveInVirtReg(PReg);
730   if (VReg) {
731     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
732     (void)VRegRC;
733     // A physical register can be added several times.
734     // Between two calls, the register class of the related virtual register
735     // may have been constrained to match some operation constraints.
736     // In that case, check that the current register class includes the
737     // physical register and is a sub class of the specified RC.
738     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
739                              RC->hasSubClassEq(VRegRC))) &&
740             "Register class mismatch!");
741     return VReg;
742   }
743   VReg = MRI.createVirtualRegister(RC);
744   MRI.addLiveIn(PReg, VReg);
745   return VReg;
746 }
747 
748 /// Return the MCSymbol for the specified non-empty jump table.
749 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
750 /// normal 'L' label is returned.
751 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
752                                         bool isLinkerPrivate) const {
753   const DataLayout &DL = getDataLayout();
754   assert(JumpTableInfo && "No jump tables");
755   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
756 
757   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
758                                      : DL.getPrivateGlobalPrefix();
759   SmallString<60> Name;
760   raw_svector_ostream(Name)
761     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
762   return Ctx.getOrCreateSymbol(Name);
763 }
764 
765 /// Return a function-local symbol to represent the PIC base.
766 MCSymbol *MachineFunction::getPICBaseSymbol() const {
767   const DataLayout &DL = getDataLayout();
768   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
769                                Twine(getFunctionNumber()) + "$pb");
770 }
771 
772 /// \name Exception Handling
773 /// \{
774 
775 LandingPadInfo &
776 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
777   unsigned N = LandingPads.size();
778   for (unsigned i = 0; i < N; ++i) {
779     LandingPadInfo &LP = LandingPads[i];
780     if (LP.LandingPadBlock == LandingPad)
781       return LP;
782   }
783 
784   LandingPads.push_back(LandingPadInfo(LandingPad));
785   return LandingPads[N];
786 }
787 
788 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
789                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
790   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
791   LP.BeginLabels.push_back(BeginLabel);
792   LP.EndLabels.push_back(EndLabel);
793 }
794 
795 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
796   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
797   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
798   LP.LandingPadLabel = LandingPadLabel;
799 
800   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
801   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
802     // If there's no typeid list specified, then "cleanup" is implicit.
803     // Otherwise, id 0 is reserved for the cleanup action.
804     if (LPI->isCleanup() && LPI->getNumClauses() != 0)
805       LP.TypeIds.push_back(0);
806 
807     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
808     //        correct, but we need to do it this way because of how the DWARF EH
809     //        emitter processes the clauses.
810     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
811       Value *Val = LPI->getClause(I - 1);
812       if (LPI->isCatch(I - 1)) {
813         LP.TypeIds.push_back(
814             getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
815       } else {
816         // Add filters in a list.
817         auto *CVal = cast<Constant>(Val);
818         SmallVector<unsigned, 4> FilterList;
819         for (const Use &U : CVal->operands())
820           FilterList.push_back(
821               getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
822 
823         LP.TypeIds.push_back(getFilterIDFor(FilterList));
824       }
825     }
826 
827   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
828     for (unsigned I = CPI->arg_size(); I != 0; --I) {
829       auto *TypeInfo =
830           dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
831       LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
832     }
833 
834   } else {
835     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
836   }
837 
838   return LandingPadLabel;
839 }
840 
841 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
842                                             ArrayRef<unsigned> Sites) {
843   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
844 }
845 
846 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
847   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
848     if (TypeInfos[i] == TI) return i + 1;
849 
850   TypeInfos.push_back(TI);
851   return TypeInfos.size();
852 }
853 
854 int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
855   // If the new filter coincides with the tail of an existing filter, then
856   // re-use the existing filter.  Folding filters more than this requires
857   // re-ordering filters and/or their elements - probably not worth it.
858   for (unsigned i : FilterEnds) {
859     unsigned j = TyIds.size();
860 
861     while (i && j)
862       if (FilterIds[--i] != TyIds[--j])
863         goto try_next;
864 
865     if (!j)
866       // The new filter coincides with range [i, end) of the existing filter.
867       return -(1 + i);
868 
869 try_next:;
870   }
871 
872   // Add the new filter.
873   int FilterID = -(1 + FilterIds.size());
874   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
875   llvm::append_range(FilterIds, TyIds);
876   FilterEnds.push_back(FilterIds.size());
877   FilterIds.push_back(0); // terminator
878   return FilterID;
879 }
880 
881 MachineFunction::CallSiteInfoMap::iterator
882 MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
883   assert(MI->isCandidateForCallSiteEntry() &&
884          "Call site info refers only to call (MI) candidates");
885 
886   if (!Target.Options.EmitCallSiteInfo)
887     return CallSitesInfo.end();
888   return CallSitesInfo.find(MI);
889 }
890 
891 /// Return the call machine instruction or find a call within bundle.
892 static const MachineInstr *getCallInstr(const MachineInstr *MI) {
893   if (!MI->isBundle())
894     return MI;
895 
896   for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
897                                     getBundleEnd(MI->getIterator())))
898     if (BMI.isCandidateForCallSiteEntry())
899       return &BMI;
900 
901   llvm_unreachable("Unexpected bundle without a call site candidate");
902 }
903 
904 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
905   assert(MI->shouldUpdateCallSiteInfo() &&
906          "Call site info refers only to call (MI) candidates or "
907          "candidates inside bundles");
908 
909   const MachineInstr *CallMI = getCallInstr(MI);
910   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
911   if (CSIt == CallSitesInfo.end())
912     return;
913   CallSitesInfo.erase(CSIt);
914 }
915 
916 void MachineFunction::copyCallSiteInfo(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 = CSIt->second;
931   CallSitesInfo[New] = CSInfo;
932 }
933 
934 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
935                                        const MachineInstr *New) {
936   assert(Old->shouldUpdateCallSiteInfo() &&
937          "Call site info refers only to call (MI) candidates or "
938          "candidates inside bundles");
939 
940   if (!New->isCandidateForCallSiteEntry())
941     return eraseCallSiteInfo(Old);
942 
943   const MachineInstr *OldCallMI = getCallInstr(Old);
944   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
945   if (CSIt == CallSitesInfo.end())
946     return;
947 
948   CallSiteInfo CSInfo = std::move(CSIt->second);
949   CallSitesInfo.erase(CSIt);
950   CallSitesInfo[New] = CSInfo;
951 }
952 
953 void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
954   DebugInstrNumberingCount = Num;
955 }
956 
957 void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
958                                                  DebugInstrOperandPair B,
959                                                  unsigned Subreg) {
960   // Catch any accidental self-loops.
961   assert(A.first != B.first);
962   // Don't allow any substitutions _from_ the memory operand number.
963   assert(A.second != DebugOperandMemNumber);
964 
965   DebugValueSubstitutions.push_back({A, B, Subreg});
966 }
967 
968 void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
969                                                    MachineInstr &New,
970                                                    unsigned MaxOperand) {
971   // If the Old instruction wasn't tracked at all, there is no work to do.
972   unsigned OldInstrNum = Old.peekDebugInstrNum();
973   if (!OldInstrNum)
974     return;
975 
976   // Iterate over all operands looking for defs to create substitutions for.
977   // Avoid creating new instr numbers unless we create a new substitution.
978   // While this has no functional effect, it risks confusing someone reading
979   // MIR output.
980   // Examine all the operands, or the first N specified by the caller.
981   MaxOperand = std::min(MaxOperand, Old.getNumOperands());
982   for (unsigned int I = 0; I < MaxOperand; ++I) {
983     const auto &OldMO = Old.getOperand(I);
984     auto &NewMO = New.getOperand(I);
985     (void)NewMO;
986 
987     if (!OldMO.isReg() || !OldMO.isDef())
988       continue;
989     assert(NewMO.isDef());
990 
991     unsigned NewInstrNum = New.getDebugInstrNum();
992     makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
993                                std::make_pair(NewInstrNum, I));
994   }
995 }
996 
997 auto MachineFunction::salvageCopySSA(
998     MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
999     -> DebugInstrOperandPair {
1000   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1001 
1002   // Check whether this copy-like instruction has already been salvaged into
1003   // an operand pair.
1004   Register Dest;
1005   if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
1006     Dest = CopyDstSrc->Destination->getReg();
1007   } else {
1008     assert(MI.isSubregToReg());
1009     Dest = MI.getOperand(0).getReg();
1010   }
1011 
1012   auto CacheIt = DbgPHICache.find(Dest);
1013   if (CacheIt != DbgPHICache.end())
1014     return CacheIt->second;
1015 
1016   // Calculate the instruction number to use, or install a DBG_PHI.
1017   auto OperandPair = salvageCopySSAImpl(MI);
1018   DbgPHICache.insert({Dest, OperandPair});
1019   return OperandPair;
1020 }
1021 
1022 auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
1023     -> DebugInstrOperandPair {
1024   MachineRegisterInfo &MRI = getRegInfo();
1025   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1026   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1027 
1028   // Chase the value read by a copy-like instruction back to the instruction
1029   // that ultimately _defines_ that value. This may pass:
1030   //  * Through multiple intermediate copies, including subregister moves /
1031   //    copies,
1032   //  * Copies from physical registers that must then be traced back to the
1033   //    defining instruction,
1034   //  * Or, physical registers may be live-in to (only) the entry block, which
1035   //    requires a DBG_PHI to be created.
1036   // We can pursue this problem in that order: trace back through copies,
1037   // optionally through a physical register, to a defining instruction. We
1038   // should never move from physreg to vreg. As we're still in SSA form, no need
1039   // to worry about partial definitions of registers.
1040 
1041   // Helper lambda to interpret a copy-like instruction. Takes instruction,
1042   // returns the register read and any subregister identifying which part is
1043   // read.
1044   auto GetRegAndSubreg =
1045       [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1046     Register NewReg, OldReg;
1047     unsigned SubReg;
1048     if (Cpy.isCopy()) {
1049       OldReg = Cpy.getOperand(0).getReg();
1050       NewReg = Cpy.getOperand(1).getReg();
1051       SubReg = Cpy.getOperand(1).getSubReg();
1052     } else if (Cpy.isSubregToReg()) {
1053       OldReg = Cpy.getOperand(0).getReg();
1054       NewReg = Cpy.getOperand(2).getReg();
1055       SubReg = Cpy.getOperand(3).getImm();
1056     } else {
1057       auto CopyDetails = *TII.isCopyInstr(Cpy);
1058       const MachineOperand &Src = *CopyDetails.Source;
1059       const MachineOperand &Dest = *CopyDetails.Destination;
1060       OldReg = Dest.getReg();
1061       NewReg = Src.getReg();
1062       SubReg = Src.getSubReg();
1063     }
1064 
1065     return {NewReg, SubReg};
1066   };
1067 
1068   // First seek either the defining instruction, or a copy from a physreg.
1069   // During search, the current state is the current copy instruction, and which
1070   // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1071   // deal with those later.
1072   auto State = GetRegAndSubreg(MI);
1073   auto CurInst = MI.getIterator();
1074   SmallVector<unsigned, 4> SubregsSeen;
1075   while (true) {
1076     // If we've found a copy from a physreg, first portion of search is over.
1077     if (!State.first.isVirtual())
1078       break;
1079 
1080     // Record any subregister qualifier.
1081     if (State.second)
1082       SubregsSeen.push_back(State.second);
1083 
1084     assert(MRI.hasOneDef(State.first));
1085     MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1086     CurInst = Inst.getIterator();
1087 
1088     // Any non-copy instruction is the defining instruction we're seeking.
1089     if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1090       break;
1091     State = GetRegAndSubreg(Inst);
1092   };
1093 
1094   // Helper lambda to apply additional subregister substitutions to a known
1095   // instruction/operand pair. Adds new (fake) substitutions so that we can
1096   // record the subregister. FIXME: this isn't very space efficient if multiple
1097   // values are tracked back through the same copies; cache something later.
1098   auto ApplySubregisters =
1099       [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1100     for (unsigned Subreg : reverse(SubregsSeen)) {
1101       // Fetch a new instruction number, not attached to an actual instruction.
1102       unsigned NewInstrNumber = getNewDebugInstrNum();
1103       // Add a substitution from the "new" number to the known one, with a
1104       // qualifying subreg.
1105       makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1106       // Return the new number; to find the underlying value, consumers need to
1107       // deal with the qualifying subreg.
1108       P = {NewInstrNumber, 0};
1109     }
1110     return P;
1111   };
1112 
1113   // If we managed to find the defining instruction after COPYs, return an
1114   // instruction / operand pair after adding subregister qualifiers.
1115   if (State.first.isVirtual()) {
1116     // Virtual register def -- we can just look up where this happens.
1117     MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1118     for (auto &MO : Inst->all_defs()) {
1119       if (MO.getReg() != State.first)
1120         continue;
1121       return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
1122     }
1123 
1124     llvm_unreachable("Vreg def with no corresponding operand?");
1125   }
1126 
1127   // Our search ended in a copy from a physreg: walk back up the function
1128   // looking for whatever defines the physreg.
1129   assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1130   State = GetRegAndSubreg(*CurInst);
1131   Register RegToSeek = State.first;
1132 
1133   auto RMII = CurInst->getReverseIterator();
1134   auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1135   for (auto &ToExamine : PrevInstrs) {
1136     for (auto &MO : ToExamine.all_defs()) {
1137       // Test for operand that defines something aliasing RegToSeek.
1138       if (!TRI.regsOverlap(RegToSeek, MO.getReg()))
1139         continue;
1140 
1141       return ApplySubregisters(
1142           {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
1143     }
1144   }
1145 
1146   MachineBasicBlock &InsertBB = *CurInst->getParent();
1147 
1148   // We reached the start of the block before finding a defining instruction.
1149   // There are numerous scenarios where this can happen:
1150   // * Constant physical registers,
1151   // * Several intrinsics that allow LLVM-IR to read arbitary registers,
1152   // * Arguments in the entry block,
1153   // * Exception handling landing pads.
1154   // Validating all of them is too difficult, so just insert a DBG_PHI reading
1155   // the variable value at this position, rather than checking it makes sense.
1156 
1157   // Create DBG_PHI for specified physreg.
1158   auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1159                          TII.get(TargetOpcode::DBG_PHI));
1160   Builder.addReg(State.first);
1161   unsigned NewNum = getNewDebugInstrNum();
1162   Builder.addImm(NewNum);
1163   return ApplySubregisters({NewNum, 0u});
1164 }
1165 
1166 void MachineFunction::finalizeDebugInstrRefs() {
1167   auto *TII = getSubtarget().getInstrInfo();
1168 
1169   auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1170     const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
1171     MI.setDesc(RefII);
1172     MI.setDebugValueUndef();
1173   };
1174 
1175   DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
1176   for (auto &MBB : *this) {
1177     for (auto &MI : MBB) {
1178       if (!MI.isDebugRef())
1179         continue;
1180 
1181       bool IsValidRef = true;
1182 
1183       for (MachineOperand &MO : MI.debug_operands()) {
1184         if (!MO.isReg())
1185           continue;
1186 
1187         Register Reg = MO.getReg();
1188 
1189         // Some vregs can be deleted as redundant in the meantime. Mark those
1190         // as DBG_VALUE $noreg. Additionally, some normal instructions are
1191         // quickly deleted, leaving dangling references to vregs with no def.
1192         if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1193           IsValidRef = false;
1194           break;
1195         }
1196 
1197         assert(Reg.isVirtual());
1198         MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1199 
1200         // If we've found a copy-like instruction, follow it back to the
1201         // instruction that defines the source value, see salvageCopySSA docs
1202         // for why this is important.
1203         if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1204           auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1205           MO.ChangeToDbgInstrRef(Result.first, Result.second);
1206         } else {
1207           // Otherwise, identify the operand number that the VReg refers to.
1208           unsigned OperandIdx = 0;
1209           for (const auto &DefMO : DefMI.operands()) {
1210             if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1211               break;
1212             ++OperandIdx;
1213           }
1214           assert(OperandIdx < DefMI.getNumOperands());
1215 
1216           // Morph this instr ref to point at the given instruction and operand.
1217           unsigned ID = DefMI.getDebugInstrNum();
1218           MO.ChangeToDbgInstrRef(ID, OperandIdx);
1219         }
1220       }
1221 
1222       if (!IsValidRef)
1223         MakeUndefDbgValue(MI);
1224     }
1225   }
1226 }
1227 
1228 bool MachineFunction::shouldUseDebugInstrRef() const {
1229   // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1230   // have optimized code inlined into this unoptimized code, however with
1231   // fewer and less aggressive optimizations happening, coverage and accuracy
1232   // should not suffer.
1233   if (getTarget().getOptLevel() == CodeGenOptLevel::None)
1234     return false;
1235 
1236   // Don't use instr-ref if this function is marked optnone.
1237   if (F.hasFnAttribute(Attribute::OptimizeNone))
1238     return false;
1239 
1240   if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1241     return true;
1242 
1243   return false;
1244 }
1245 
1246 bool MachineFunction::useDebugInstrRef() const {
1247   return UseDebugInstrRef;
1248 }
1249 
1250 void MachineFunction::setUseDebugInstrRef(bool Use) {
1251   UseDebugInstrRef = Use;
1252 }
1253 
1254 // Use one million as a high / reserved number.
1255 const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1256 
1257 /// \}
1258 
1259 //===----------------------------------------------------------------------===//
1260 //  MachineJumpTableInfo implementation
1261 //===----------------------------------------------------------------------===//
1262 
1263 /// Return the size of each entry in the jump table.
1264 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
1265   // The size of a jump table entry is 4 bytes unless the entry is just the
1266   // address of a block, in which case it is the pointer size.
1267   switch (getEntryKind()) {
1268   case MachineJumpTableInfo::EK_BlockAddress:
1269     return TD.getPointerSize();
1270   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1271   case MachineJumpTableInfo::EK_LabelDifference64:
1272     return 8;
1273   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1274   case MachineJumpTableInfo::EK_LabelDifference32:
1275   case MachineJumpTableInfo::EK_Custom32:
1276     return 4;
1277   case MachineJumpTableInfo::EK_Inline:
1278     return 0;
1279   }
1280   llvm_unreachable("Unknown jump table encoding!");
1281 }
1282 
1283 /// Return the alignment of each entry in the jump table.
1284 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1285   // The alignment of a jump table entry is the alignment of int32 unless the
1286   // entry is just the address of a block, in which case it is the pointer
1287   // alignment.
1288   switch (getEntryKind()) {
1289   case MachineJumpTableInfo::EK_BlockAddress:
1290     return TD.getPointerABIAlignment(0).value();
1291   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1292   case MachineJumpTableInfo::EK_LabelDifference64:
1293     return TD.getABIIntegerTypeAlignment(64).value();
1294   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1295   case MachineJumpTableInfo::EK_LabelDifference32:
1296   case MachineJumpTableInfo::EK_Custom32:
1297     return TD.getABIIntegerTypeAlignment(32).value();
1298   case MachineJumpTableInfo::EK_Inline:
1299     return 1;
1300   }
1301   llvm_unreachable("Unknown jump table encoding!");
1302 }
1303 
1304 /// Create a new jump table entry in the jump table info.
1305 unsigned MachineJumpTableInfo::createJumpTableIndex(
1306                                const std::vector<MachineBasicBlock*> &DestBBs) {
1307   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1308   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1309   return JumpTables.size()-1;
1310 }
1311 
1312 /// If Old is the target of any jump tables, update the jump tables to branch
1313 /// to New instead.
1314 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1315                                                   MachineBasicBlock *New) {
1316   assert(Old != New && "Not making a change?");
1317   bool MadeChange = false;
1318   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1319     ReplaceMBBInJumpTable(i, Old, New);
1320   return MadeChange;
1321 }
1322 
1323 /// If MBB is present in any jump tables, remove it.
1324 bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1325   bool MadeChange = false;
1326   for (MachineJumpTableEntry &JTE : JumpTables) {
1327     auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1328     MadeChange |= (removeBeginItr != JTE.MBBs.end());
1329     JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1330   }
1331   return MadeChange;
1332 }
1333 
1334 /// If Old is a target of the jump tables, update the jump table to branch to
1335 /// New instead.
1336 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1337                                                  MachineBasicBlock *Old,
1338                                                  MachineBasicBlock *New) {
1339   assert(Old != New && "Not making a change?");
1340   bool MadeChange = false;
1341   MachineJumpTableEntry &JTE = JumpTables[Idx];
1342   for (MachineBasicBlock *&MBB : JTE.MBBs)
1343     if (MBB == Old) {
1344       MBB = New;
1345       MadeChange = true;
1346     }
1347   return MadeChange;
1348 }
1349 
1350 void MachineJumpTableInfo::print(raw_ostream &OS) const {
1351   if (JumpTables.empty()) return;
1352 
1353   OS << "Jump Tables:\n";
1354 
1355   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1356     OS << printJumpTableEntryReference(i) << ':';
1357     for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
1358       OS << ' ' << printMBBReference(*MBB);
1359     if (i != e)
1360       OS << '\n';
1361   }
1362 
1363   OS << '\n';
1364 }
1365 
1366 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1367 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1368 #endif
1369 
1370 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1371   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1372 }
1373 
1374 //===----------------------------------------------------------------------===//
1375 //  MachineConstantPool implementation
1376 //===----------------------------------------------------------------------===//
1377 
1378 void MachineConstantPoolValue::anchor() {}
1379 
1380 unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1381   return DL.getTypeAllocSize(Ty);
1382 }
1383 
1384 unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1385   if (isMachineConstantPoolEntry())
1386     return Val.MachineCPVal->getSizeInBytes(DL);
1387   return DL.getTypeAllocSize(Val.ConstVal->getType());
1388 }
1389 
1390 bool MachineConstantPoolEntry::needsRelocation() const {
1391   if (isMachineConstantPoolEntry())
1392     return true;
1393   return Val.ConstVal->needsDynamicRelocation();
1394 }
1395 
1396 SectionKind
1397 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1398   if (needsRelocation())
1399     return SectionKind::getReadOnlyWithRel();
1400   switch (getSizeInBytes(*DL)) {
1401   case 4:
1402     return SectionKind::getMergeableConst4();
1403   case 8:
1404     return SectionKind::getMergeableConst8();
1405   case 16:
1406     return SectionKind::getMergeableConst16();
1407   case 32:
1408     return SectionKind::getMergeableConst32();
1409   default:
1410     return SectionKind::getReadOnly();
1411   }
1412 }
1413 
1414 MachineConstantPool::~MachineConstantPool() {
1415   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1416   // so keep track of which we've deleted to avoid double deletions.
1417   DenseSet<MachineConstantPoolValue*> Deleted;
1418   for (const MachineConstantPoolEntry &C : Constants)
1419     if (C.isMachineConstantPoolEntry()) {
1420       Deleted.insert(C.Val.MachineCPVal);
1421       delete C.Val.MachineCPVal;
1422     }
1423   for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1424     if (Deleted.count(CPV) == 0)
1425       delete CPV;
1426   }
1427 }
1428 
1429 /// Test whether the given two constants can be allocated the same constant pool
1430 /// entry referenced by \param A.
1431 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1432                                       const DataLayout &DL) {
1433   // Handle the trivial case quickly.
1434   if (A == B) return true;
1435 
1436   // If they have the same type but weren't the same constant, quickly
1437   // reject them.
1438   if (A->getType() == B->getType()) return false;
1439 
1440   // We can't handle structs or arrays.
1441   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1442       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1443     return false;
1444 
1445   // For now, only support constants with the same size.
1446   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1447   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1448     return false;
1449 
1450   bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
1451 
1452   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1453 
1454   // Try constant folding a bitcast of both instructions to an integer.  If we
1455   // get two identical ConstantInt's, then we are good to share them.  We use
1456   // the constant folding APIs to do this so that we get the benefit of
1457   // DataLayout.
1458   if (isa<PointerType>(A->getType()))
1459     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1460                                 const_cast<Constant *>(A), IntTy, DL);
1461   else if (A->getType() != IntTy)
1462     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1463                                 IntTy, DL);
1464   if (isa<PointerType>(B->getType()))
1465     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1466                                 const_cast<Constant *>(B), IntTy, DL);
1467   else if (B->getType() != IntTy)
1468     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1469                                 IntTy, DL);
1470 
1471   if (A != B)
1472     return false;
1473 
1474   // Constants only safely match if A doesn't contain undef/poison.
1475   // As we'll be reusing A, it doesn't matter if B contain undef/poison.
1476   // TODO: Handle cases where A and B have the same undef/poison elements.
1477   // TODO: Merge A and B with mismatching undef/poison elements.
1478   return !ContainsUndefOrPoisonA;
1479 }
1480 
1481 /// Create a new entry in the constant pool or return an existing one.
1482 /// User must specify the log2 of the minimum required alignment for the object.
1483 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1484                                                    Align Alignment) {
1485   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1486 
1487   // Check to see if we already have this constant.
1488   //
1489   // FIXME, this could be made much more efficient for large constant pools.
1490   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1491     if (!Constants[i].isMachineConstantPoolEntry() &&
1492         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1493       if (Constants[i].getAlign() < Alignment)
1494         Constants[i].Alignment = Alignment;
1495       return i;
1496     }
1497 
1498   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1499   return Constants.size()-1;
1500 }
1501 
1502 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1503                                                    Align Alignment) {
1504   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1505 
1506   // Check to see if we already have this constant.
1507   //
1508   // FIXME, this could be made much more efficient for large constant pools.
1509   int Idx = V->getExistingMachineCPValue(this, Alignment);
1510   if (Idx != -1) {
1511     MachineCPVsSharingEntries.insert(V);
1512     return (unsigned)Idx;
1513   }
1514 
1515   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1516   return Constants.size()-1;
1517 }
1518 
1519 void MachineConstantPool::print(raw_ostream &OS) const {
1520   if (Constants.empty()) return;
1521 
1522   OS << "Constant Pool:\n";
1523   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1524     OS << "  cp#" << i << ": ";
1525     if (Constants[i].isMachineConstantPoolEntry())
1526       Constants[i].Val.MachineCPVal->print(OS);
1527     else
1528       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1529     OS << ", align=" << Constants[i].getAlign().value();
1530     OS << "\n";
1531   }
1532 }
1533 
1534 //===----------------------------------------------------------------------===//
1535 // Template specialization for MachineFunction implementation of
1536 // ProfileSummaryInfo::getEntryCount().
1537 //===----------------------------------------------------------------------===//
1538 template <>
1539 std::optional<Function::ProfileCount>
1540 ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
1541     const llvm::MachineFunction *F) const {
1542   return F->getFunction().getEntryCount();
1543 }
1544 
1545 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1546 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1547 #endif
1548