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