xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision 24faf859e52b5d06068c3696ca1c89c09ffa2698)
1 //===- MachineFunction.cpp ------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect native machine code information for a function.  This allows
11 // target-specific information about the generated code to be stored with each
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/EHPersonalities.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/TargetFrameLowering.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/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/GraphWriter.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <iterator>
73 #include <string>
74 #include <utility>
75 #include <vector>
76 
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "codegen"
80 
81 static cl::opt<unsigned>
82 AlignAllFunctions("align-all-functions",
83                   cl::desc("Force the alignment of all functions."),
84                   cl::init(0), cl::Hidden);
85 
86 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
87   using P = MachineFunctionProperties::Property;
88 
89   switch(Prop) {
90   case P::FailedISel: return "FailedISel";
91   case P::IsSSA: return "IsSSA";
92   case P::Legalized: return "Legalized";
93   case P::NoPHIs: return "NoPHIs";
94   case P::NoVRegs: return "NoVRegs";
95   case P::RegBankSelected: return "RegBankSelected";
96   case P::Selected: return "Selected";
97   case P::TracksLiveness: return "TracksLiveness";
98   }
99   llvm_unreachable("Invalid machine function property");
100 }
101 
102 // Pin the vtable to this file.
103 void MachineFunction::Delegate::anchor() {}
104 
105 void MachineFunctionProperties::print(raw_ostream &OS) const {
106   const char *Separator = "";
107   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
108     if (!Properties[I])
109       continue;
110     OS << Separator << getPropertyName(static_cast<Property>(I));
111     Separator = ", ";
112   }
113 }
114 
115 //===----------------------------------------------------------------------===//
116 // MachineFunction implementation
117 //===----------------------------------------------------------------------===//
118 
119 // Out-of-line virtual method.
120 MachineFunctionInfo::~MachineFunctionInfo() = default;
121 
122 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
123   MBB->getParent()->DeleteMachineBasicBlock(MBB);
124 }
125 
126 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
127                                            const Function &F) {
128   if (F.hasFnAttribute(Attribute::StackAlignment))
129     return F.getFnStackAlignment();
130   return STI->getFrameLowering()->getStackAlignment();
131 }
132 
133 MachineFunction::MachineFunction(const Function &F, const TargetMachine &Target,
134                                  const TargetSubtargetInfo &STI,
135                                  unsigned FunctionNum, MachineModuleInfo &mmi)
136     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
137   FunctionNumber = FunctionNum;
138   init();
139 }
140 
141 void MachineFunction::handleInsertion(const MachineInstr &MI) {
142   if (TheDelegate)
143     TheDelegate->MF_HandleInsertion(MI);
144 }
145 
146 void MachineFunction::handleRemoval(const MachineInstr &MI) {
147   if (TheDelegate)
148     TheDelegate->MF_HandleRemoval(MI);
149 }
150 
151 void MachineFunction::init() {
152   // Assume the function starts in SSA form with correct liveness.
153   Properties.set(MachineFunctionProperties::Property::IsSSA);
154   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
155   if (STI->getRegisterInfo())
156     RegInfo = new (Allocator) MachineRegisterInfo(this);
157   else
158     RegInfo = nullptr;
159 
160   MFInfo = nullptr;
161   // We can realign the stack if the target supports it and the user hasn't
162   // explicitly asked us not to.
163   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
164                       !F.hasFnAttribute("no-realign-stack");
165   FrameInfo = new (Allocator) MachineFrameInfo(
166       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
167       /*ForceRealign=*/CanRealignSP &&
168           F.hasFnAttribute(Attribute::StackAlignment));
169 
170   if (F.hasFnAttribute(Attribute::StackAlignment))
171     FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
172 
173   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
174   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
175 
176   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
177   // FIXME: Use Function::optForSize().
178   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
179     Alignment = std::max(Alignment,
180                          STI->getTargetLowering()->getPrefFunctionAlignment());
181 
182   if (AlignAllFunctions)
183     Alignment = AlignAllFunctions;
184 
185   JumpTableInfo = nullptr;
186 
187   if (isFuncletEHPersonality(classifyEHPersonality(
188           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
189     WinEHInfo = new (Allocator) WinEHFuncInfo();
190   }
191 
192   if (isScopedEHPersonality(classifyEHPersonality(
193           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
194     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
195   }
196 
197   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
198          "Can't create a MachineFunction using a Module with a "
199          "Target-incompatible DataLayout attached\n");
200 
201   PSVManager =
202     llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget().
203                                                   getInstrInfo()));
204 }
205 
206 MachineFunction::~MachineFunction() {
207   clear();
208 }
209 
210 void MachineFunction::clear() {
211   Properties.reset();
212   // Don't call destructors on MachineInstr and MachineOperand. All of their
213   // memory comes from the BumpPtrAllocator which is about to be purged.
214   //
215   // Do call MachineBasicBlock destructors, it contains std::vectors.
216   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
217     I->Insts.clearAndLeakNodesUnsafely();
218   MBBNumbering.clear();
219 
220   InstructionRecycler.clear(Allocator);
221   OperandRecycler.clear(Allocator);
222   BasicBlockRecycler.clear(Allocator);
223   CodeViewAnnotations.clear();
224   VariableDbgInfos.clear();
225   if (RegInfo) {
226     RegInfo->~MachineRegisterInfo();
227     Allocator.Deallocate(RegInfo);
228   }
229   if (MFInfo) {
230     MFInfo->~MachineFunctionInfo();
231     Allocator.Deallocate(MFInfo);
232   }
233 
234   FrameInfo->~MachineFrameInfo();
235   Allocator.Deallocate(FrameInfo);
236 
237   ConstantPool->~MachineConstantPool();
238   Allocator.Deallocate(ConstantPool);
239 
240   if (JumpTableInfo) {
241     JumpTableInfo->~MachineJumpTableInfo();
242     Allocator.Deallocate(JumpTableInfo);
243   }
244 
245   if (WinEHInfo) {
246     WinEHInfo->~WinEHFuncInfo();
247     Allocator.Deallocate(WinEHInfo);
248   }
249 
250   if (WasmEHInfo) {
251     WasmEHInfo->~WasmEHFuncInfo();
252     Allocator.Deallocate(WasmEHInfo);
253   }
254 }
255 
256 const DataLayout &MachineFunction::getDataLayout() const {
257   return F.getParent()->getDataLayout();
258 }
259 
260 /// Get the JumpTableInfo for this function.
261 /// If it does not already exist, allocate one.
262 MachineJumpTableInfo *MachineFunction::
263 getOrCreateJumpTableInfo(unsigned EntryKind) {
264   if (JumpTableInfo) return JumpTableInfo;
265 
266   JumpTableInfo = new (Allocator)
267     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
268   return JumpTableInfo;
269 }
270 
271 /// Should we be emitting segmented stack stuff for the function
272 bool MachineFunction::shouldSplitStack() const {
273   return getFunction().hasFnAttribute("split-stack");
274 }
275 
276 /// This discards all of the MachineBasicBlock numbers and recomputes them.
277 /// This guarantees that the MBB numbers are sequential, dense, and match the
278 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
279 /// is specified, only that block and those after it are renumbered.
280 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
281   if (empty()) { MBBNumbering.clear(); return; }
282   MachineFunction::iterator MBBI, E = end();
283   if (MBB == nullptr)
284     MBBI = begin();
285   else
286     MBBI = MBB->getIterator();
287 
288   // Figure out the block number this should have.
289   unsigned BlockNo = 0;
290   if (MBBI != begin())
291     BlockNo = std::prev(MBBI)->getNumber() + 1;
292 
293   for (; MBBI != E; ++MBBI, ++BlockNo) {
294     if (MBBI->getNumber() != (int)BlockNo) {
295       // Remove use of the old number.
296       if (MBBI->getNumber() != -1) {
297         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
298                "MBB number mismatch!");
299         MBBNumbering[MBBI->getNumber()] = nullptr;
300       }
301 
302       // If BlockNo is already taken, set that block's number to -1.
303       if (MBBNumbering[BlockNo])
304         MBBNumbering[BlockNo]->setNumber(-1);
305 
306       MBBNumbering[BlockNo] = &*MBBI;
307       MBBI->setNumber(BlockNo);
308     }
309   }
310 
311   // Okay, all the blocks are renumbered.  If we have compactified the block
312   // numbering, shrink MBBNumbering now.
313   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
314   MBBNumbering.resize(BlockNo);
315 }
316 
317 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
318 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
319                                                   const DebugLoc &DL,
320                                                   bool NoImp) {
321   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
322     MachineInstr(*this, MCID, DL, NoImp);
323 }
324 
325 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
326 /// identical in all ways except the instruction has no parent, prev, or next.
327 MachineInstr *
328 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
329   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
330              MachineInstr(*this, *Orig);
331 }
332 
333 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
334     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
335   MachineInstr *FirstClone = nullptr;
336   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
337   while (true) {
338     MachineInstr *Cloned = CloneMachineInstr(&*I);
339     MBB.insert(InsertBefore, Cloned);
340     if (FirstClone == nullptr) {
341       FirstClone = Cloned;
342     } else {
343       Cloned->bundleWithPred();
344     }
345 
346     if (!I->isBundledWithSucc())
347       break;
348     ++I;
349   }
350   return *FirstClone;
351 }
352 
353 /// Delete the given MachineInstr.
354 ///
355 /// This function also serves as the MachineInstr destructor - the real
356 /// ~MachineInstr() destructor must be empty.
357 void
358 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
359   // Strip it for parts. The operand array and the MI object itself are
360   // independently recyclable.
361   if (MI->Operands)
362     deallocateOperandArray(MI->CapOperands, MI->Operands);
363   // Don't call ~MachineInstr() which must be trivial anyway because
364   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
365   // destructors.
366   InstructionRecycler.Deallocate(Allocator, MI);
367 }
368 
369 /// Allocate a new MachineBasicBlock. Use this instead of
370 /// `new MachineBasicBlock'.
371 MachineBasicBlock *
372 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
373   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
374              MachineBasicBlock(*this, bb);
375 }
376 
377 /// Delete the given MachineBasicBlock.
378 void
379 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
380   assert(MBB->getParent() == this && "MBB parent mismatch!");
381   MBB->~MachineBasicBlock();
382   BasicBlockRecycler.Deallocate(Allocator, MBB);
383 }
384 
385 MachineMemOperand *MachineFunction::getMachineMemOperand(
386     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
387     unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
388     SyncScope::ID SSID, AtomicOrdering Ordering,
389     AtomicOrdering FailureOrdering) {
390   return new (Allocator)
391       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
392                         SSID, Ordering, FailureOrdering);
393 }
394 
395 MachineMemOperand *
396 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
397                                       int64_t Offset, uint64_t Size) {
398   if (MMO->getValue())
399     return new (Allocator)
400                MachineMemOperand(MachinePointerInfo(MMO->getValue(),
401                                                     MMO->getOffset()+Offset),
402                                  MMO->getFlags(), Size, MMO->getBaseAlignment(),
403                                  AAMDNodes(), nullptr, MMO->getSyncScopeID(),
404                                  MMO->getOrdering(), MMO->getFailureOrdering());
405   return new (Allocator)
406              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
407                                                   MMO->getOffset()+Offset),
408                                MMO->getFlags(), Size, MMO->getBaseAlignment(),
409                                AAMDNodes(), nullptr, MMO->getSyncScopeID(),
410                                MMO->getOrdering(), MMO->getFailureOrdering());
411 }
412 
413 MachineMemOperand *
414 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
415                                       const AAMDNodes &AAInfo) {
416   MachinePointerInfo MPI = MMO->getValue() ?
417              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
418              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
419 
420   return new (Allocator)
421              MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
422                                MMO->getBaseAlignment(), AAInfo,
423                                MMO->getRanges(), MMO->getSyncScopeID(),
424                                MMO->getOrdering(), MMO->getFailureOrdering());
425 }
426 
427 MachineInstr::ExtraInfo *
428 MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
429                                    MCSymbol *PreInstrSymbol,
430                                    MCSymbol *PostInstrSymbol) {
431   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
432                                          PostInstrSymbol);
433 }
434 
435 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
436   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
437   std::copy(Name.begin(), Name.end(), Dest);
438   Dest[Name.size()] = 0;
439   return Dest;
440 }
441 
442 uint32_t *MachineFunction::allocateRegMask() {
443   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
444   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
445   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
446   memset(Mask, 0, Size * sizeof(Mask[0]));
447   return Mask;
448 }
449 
450 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
451 LLVM_DUMP_METHOD void MachineFunction::dump() const {
452   print(dbgs());
453 }
454 #endif
455 
456 StringRef MachineFunction::getName() const {
457   return getFunction().getName();
458 }
459 
460 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
461   OS << "# Machine code for function " << getName() << ": ";
462   getProperties().print(OS);
463   OS << '\n';
464 
465   // Print Frame Information
466   FrameInfo->print(*this, OS);
467 
468   // Print JumpTable Information
469   if (JumpTableInfo)
470     JumpTableInfo->print(OS);
471 
472   // Print Constant Pool
473   ConstantPool->print(OS);
474 
475   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
476 
477   if (RegInfo && !RegInfo->livein_empty()) {
478     OS << "Function Live Ins: ";
479     for (MachineRegisterInfo::livein_iterator
480          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
481       OS << printReg(I->first, TRI);
482       if (I->second)
483         OS << " in " << printReg(I->second, TRI);
484       if (std::next(I) != E)
485         OS << ", ";
486     }
487     OS << '\n';
488   }
489 
490   ModuleSlotTracker MST(getFunction().getParent());
491   MST.incorporateFunction(getFunction());
492   for (const auto &BB : *this) {
493     OS << '\n';
494     // If we print the whole function, print it at its most verbose level.
495     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
496   }
497 
498   OS << "\n# End machine code for function " << getName() << ".\n\n";
499 }
500 
501 namespace llvm {
502 
503   template<>
504   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
505     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
506 
507     static std::string getGraphName(const MachineFunction *F) {
508       return ("CFG for '" + F->getName() + "' function").str();
509     }
510 
511     std::string getNodeLabel(const MachineBasicBlock *Node,
512                              const MachineFunction *Graph) {
513       std::string OutStr;
514       {
515         raw_string_ostream OSS(OutStr);
516 
517         if (isSimple()) {
518           OSS << printMBBReference(*Node);
519           if (const BasicBlock *BB = Node->getBasicBlock())
520             OSS << ": " << BB->getName();
521         } else
522           Node->print(OSS);
523       }
524 
525       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
526 
527       // Process string output to make it nicer...
528       for (unsigned i = 0; i != OutStr.length(); ++i)
529         if (OutStr[i] == '\n') {                            // Left justify
530           OutStr[i] = '\\';
531           OutStr.insert(OutStr.begin()+i+1, 'l');
532         }
533       return OutStr;
534     }
535   };
536 
537 } // end namespace llvm
538 
539 void MachineFunction::viewCFG() const
540 {
541 #ifndef NDEBUG
542   ViewGraph(this, "mf" + getName());
543 #else
544   errs() << "MachineFunction::viewCFG is only available in debug builds on "
545          << "systems with Graphviz or gv!\n";
546 #endif // NDEBUG
547 }
548 
549 void MachineFunction::viewCFGOnly() const
550 {
551 #ifndef NDEBUG
552   ViewGraph(this, "mf" + getName(), true);
553 #else
554   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
555          << "systems with Graphviz or gv!\n";
556 #endif // NDEBUG
557 }
558 
559 /// Add the specified physical register as a live-in value and
560 /// create a corresponding virtual register for it.
561 unsigned MachineFunction::addLiveIn(unsigned PReg,
562                                     const TargetRegisterClass *RC) {
563   MachineRegisterInfo &MRI = getRegInfo();
564   unsigned VReg = MRI.getLiveInVirtReg(PReg);
565   if (VReg) {
566     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
567     (void)VRegRC;
568     // A physical register can be added several times.
569     // Between two calls, the register class of the related virtual register
570     // may have been constrained to match some operation constraints.
571     // In that case, check that the current register class includes the
572     // physical register and is a sub class of the specified RC.
573     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
574                              RC->hasSubClassEq(VRegRC))) &&
575             "Register class mismatch!");
576     return VReg;
577   }
578   VReg = MRI.createVirtualRegister(RC);
579   MRI.addLiveIn(PReg, VReg);
580   return VReg;
581 }
582 
583 /// Return the MCSymbol for the specified non-empty jump table.
584 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
585 /// normal 'L' label is returned.
586 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
587                                         bool isLinkerPrivate) const {
588   const DataLayout &DL = getDataLayout();
589   assert(JumpTableInfo && "No jump tables");
590   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
591 
592   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
593                                      : DL.getPrivateGlobalPrefix();
594   SmallString<60> Name;
595   raw_svector_ostream(Name)
596     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
597   return Ctx.getOrCreateSymbol(Name);
598 }
599 
600 /// Return a function-local symbol to represent the PIC base.
601 MCSymbol *MachineFunction::getPICBaseSymbol() const {
602   const DataLayout &DL = getDataLayout();
603   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
604                                Twine(getFunctionNumber()) + "$pb");
605 }
606 
607 /// \name Exception Handling
608 /// \{
609 
610 LandingPadInfo &
611 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
612   unsigned N = LandingPads.size();
613   for (unsigned i = 0; i < N; ++i) {
614     LandingPadInfo &LP = LandingPads[i];
615     if (LP.LandingPadBlock == LandingPad)
616       return LP;
617   }
618 
619   LandingPads.push_back(LandingPadInfo(LandingPad));
620   return LandingPads[N];
621 }
622 
623 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
624                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
625   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
626   LP.BeginLabels.push_back(BeginLabel);
627   LP.EndLabels.push_back(EndLabel);
628 }
629 
630 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
631   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
632   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
633   LP.LandingPadLabel = LandingPadLabel;
634 
635   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
636   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
637     if (const auto *PF =
638             dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
639       getMMI().addPersonality(PF);
640 
641     if (LPI->isCleanup())
642       addCleanup(LandingPad);
643 
644     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
645     //        correct, but we need to do it this way because of how the DWARF EH
646     //        emitter processes the clauses.
647     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
648       Value *Val = LPI->getClause(I - 1);
649       if (LPI->isCatch(I - 1)) {
650         addCatchTypeInfo(LandingPad,
651                          dyn_cast<GlobalValue>(Val->stripPointerCasts()));
652       } else {
653         // Add filters in a list.
654         auto *CVal = cast<Constant>(Val);
655         SmallVector<const GlobalValue *, 4> FilterList;
656         for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
657              II != IE; ++II)
658           FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
659 
660         addFilterTypeInfo(LandingPad, FilterList);
661       }
662     }
663 
664   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
665     for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
666       Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
667       addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
668     }
669 
670   } else {
671     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
672   }
673 
674   return LandingPadLabel;
675 }
676 
677 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
678                                        ArrayRef<const GlobalValue *> TyInfo) {
679   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
680   for (unsigned N = TyInfo.size(); N; --N)
681     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
682 }
683 
684 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
685                                         ArrayRef<const GlobalValue *> TyInfo) {
686   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
687   std::vector<unsigned> IdsInFilter(TyInfo.size());
688   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
689     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
690   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
691 }
692 
693 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
694                                       bool TidyIfNoBeginLabels) {
695   for (unsigned i = 0; i != LandingPads.size(); ) {
696     LandingPadInfo &LandingPad = LandingPads[i];
697     if (LandingPad.LandingPadLabel &&
698         !LandingPad.LandingPadLabel->isDefined() &&
699         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
700       LandingPad.LandingPadLabel = nullptr;
701 
702     // Special case: we *should* emit LPs with null LP MBB. This indicates
703     // "nounwind" case.
704     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
705       LandingPads.erase(LandingPads.begin() + i);
706       continue;
707     }
708 
709     if (TidyIfNoBeginLabels) {
710       for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
711         MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
712         MCSymbol *EndLabel = LandingPad.EndLabels[j];
713         if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
714             (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
715           continue;
716 
717         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
718         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
719         --j;
720         --e;
721       }
722 
723       // Remove landing pads with no try-ranges.
724       if (LandingPads[i].BeginLabels.empty()) {
725         LandingPads.erase(LandingPads.begin() + i);
726         continue;
727       }
728     }
729 
730     // If there is no landing pad, ensure that the list of typeids is empty.
731     // If the only typeid is a cleanup, this is the same as having no typeids.
732     if (!LandingPad.LandingPadBlock ||
733         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
734       LandingPad.TypeIds.clear();
735     ++i;
736   }
737 }
738 
739 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
740   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
741   LP.TypeIds.push_back(0);
742 }
743 
744 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
745                                          const Function *Filter,
746                                          const BlockAddress *RecoverBA) {
747   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
748   SEHHandler Handler;
749   Handler.FilterOrFinally = Filter;
750   Handler.RecoverBA = RecoverBA;
751   LP.SEHHandlers.push_back(Handler);
752 }
753 
754 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
755                                            const Function *Cleanup) {
756   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
757   SEHHandler Handler;
758   Handler.FilterOrFinally = Cleanup;
759   Handler.RecoverBA = nullptr;
760   LP.SEHHandlers.push_back(Handler);
761 }
762 
763 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
764                                             ArrayRef<unsigned> Sites) {
765   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
766 }
767 
768 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
769   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
770     if (TypeInfos[i] == TI) return i + 1;
771 
772   TypeInfos.push_back(TI);
773   return TypeInfos.size();
774 }
775 
776 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
777   // If the new filter coincides with the tail of an existing filter, then
778   // re-use the existing filter.  Folding filters more than this requires
779   // re-ordering filters and/or their elements - probably not worth it.
780   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
781        E = FilterEnds.end(); I != E; ++I) {
782     unsigned i = *I, j = TyIds.size();
783 
784     while (i && j)
785       if (FilterIds[--i] != TyIds[--j])
786         goto try_next;
787 
788     if (!j)
789       // The new filter coincides with range [i, end) of the existing filter.
790       return -(1 + i);
791 
792 try_next:;
793   }
794 
795   // Add the new filter.
796   int FilterID = -(1 + FilterIds.size());
797   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
798   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
799   FilterEnds.push_back(FilterIds.size());
800   FilterIds.push_back(0); // terminator
801   return FilterID;
802 }
803 
804 /// \}
805 
806 //===----------------------------------------------------------------------===//
807 //  MachineJumpTableInfo implementation
808 //===----------------------------------------------------------------------===//
809 
810 /// Return the size of each entry in the jump table.
811 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
812   // The size of a jump table entry is 4 bytes unless the entry is just the
813   // address of a block, in which case it is the pointer size.
814   switch (getEntryKind()) {
815   case MachineJumpTableInfo::EK_BlockAddress:
816     return TD.getPointerSize();
817   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
818     return 8;
819   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
820   case MachineJumpTableInfo::EK_LabelDifference32:
821   case MachineJumpTableInfo::EK_Custom32:
822     return 4;
823   case MachineJumpTableInfo::EK_Inline:
824     return 0;
825   }
826   llvm_unreachable("Unknown jump table encoding!");
827 }
828 
829 /// Return the alignment of each entry in the jump table.
830 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
831   // The alignment of a jump table entry is the alignment of int32 unless the
832   // entry is just the address of a block, in which case it is the pointer
833   // alignment.
834   switch (getEntryKind()) {
835   case MachineJumpTableInfo::EK_BlockAddress:
836     return TD.getPointerABIAlignment(0);
837   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
838     return TD.getABIIntegerTypeAlignment(64);
839   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
840   case MachineJumpTableInfo::EK_LabelDifference32:
841   case MachineJumpTableInfo::EK_Custom32:
842     return TD.getABIIntegerTypeAlignment(32);
843   case MachineJumpTableInfo::EK_Inline:
844     return 1;
845   }
846   llvm_unreachable("Unknown jump table encoding!");
847 }
848 
849 /// Create a new jump table entry in the jump table info.
850 unsigned MachineJumpTableInfo::createJumpTableIndex(
851                                const std::vector<MachineBasicBlock*> &DestBBs) {
852   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
853   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
854   return JumpTables.size()-1;
855 }
856 
857 /// If Old is the target of any jump tables, update the jump tables to branch
858 /// to New instead.
859 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
860                                                   MachineBasicBlock *New) {
861   assert(Old != New && "Not making a change?");
862   bool MadeChange = false;
863   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
864     ReplaceMBBInJumpTable(i, Old, New);
865   return MadeChange;
866 }
867 
868 /// If Old is a target of the jump tables, update the jump table to branch to
869 /// New instead.
870 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
871                                                  MachineBasicBlock *Old,
872                                                  MachineBasicBlock *New) {
873   assert(Old != New && "Not making a change?");
874   bool MadeChange = false;
875   MachineJumpTableEntry &JTE = JumpTables[Idx];
876   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
877     if (JTE.MBBs[j] == Old) {
878       JTE.MBBs[j] = New;
879       MadeChange = true;
880     }
881   return MadeChange;
882 }
883 
884 void MachineJumpTableInfo::print(raw_ostream &OS) const {
885   if (JumpTables.empty()) return;
886 
887   OS << "Jump Tables:\n";
888 
889   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
890     OS << printJumpTableEntryReference(i) << ": ";
891     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
892       OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
893   }
894 
895   OS << '\n';
896 }
897 
898 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
899 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
900 #endif
901 
902 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
903   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
904 }
905 
906 //===----------------------------------------------------------------------===//
907 //  MachineConstantPool implementation
908 //===----------------------------------------------------------------------===//
909 
910 void MachineConstantPoolValue::anchor() {}
911 
912 Type *MachineConstantPoolEntry::getType() const {
913   if (isMachineConstantPoolEntry())
914     return Val.MachineCPVal->getType();
915   return Val.ConstVal->getType();
916 }
917 
918 bool MachineConstantPoolEntry::needsRelocation() const {
919   if (isMachineConstantPoolEntry())
920     return true;
921   return Val.ConstVal->needsRelocation();
922 }
923 
924 SectionKind
925 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
926   if (needsRelocation())
927     return SectionKind::getReadOnlyWithRel();
928   switch (DL->getTypeAllocSize(getType())) {
929   case 4:
930     return SectionKind::getMergeableConst4();
931   case 8:
932     return SectionKind::getMergeableConst8();
933   case 16:
934     return SectionKind::getMergeableConst16();
935   case 32:
936     return SectionKind::getMergeableConst32();
937   default:
938     return SectionKind::getReadOnly();
939   }
940 }
941 
942 MachineConstantPool::~MachineConstantPool() {
943   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
944   // so keep track of which we've deleted to avoid double deletions.
945   DenseSet<MachineConstantPoolValue*> Deleted;
946   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
947     if (Constants[i].isMachineConstantPoolEntry()) {
948       Deleted.insert(Constants[i].Val.MachineCPVal);
949       delete Constants[i].Val.MachineCPVal;
950     }
951   for (DenseSet<MachineConstantPoolValue*>::iterator I =
952        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
953        I != E; ++I) {
954     if (Deleted.count(*I) == 0)
955       delete *I;
956   }
957 }
958 
959 /// Test whether the given two constants can be allocated the same constant pool
960 /// entry.
961 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
962                                       const DataLayout &DL) {
963   // Handle the trivial case quickly.
964   if (A == B) return true;
965 
966   // If they have the same type but weren't the same constant, quickly
967   // reject them.
968   if (A->getType() == B->getType()) return false;
969 
970   // We can't handle structs or arrays.
971   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
972       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
973     return false;
974 
975   // For now, only support constants with the same size.
976   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
977   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
978     return false;
979 
980   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
981 
982   // Try constant folding a bitcast of both instructions to an integer.  If we
983   // get two identical ConstantInt's, then we are good to share them.  We use
984   // the constant folding APIs to do this so that we get the benefit of
985   // DataLayout.
986   if (isa<PointerType>(A->getType()))
987     A = ConstantFoldCastOperand(Instruction::PtrToInt,
988                                 const_cast<Constant *>(A), IntTy, DL);
989   else if (A->getType() != IntTy)
990     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
991                                 IntTy, DL);
992   if (isa<PointerType>(B->getType()))
993     B = ConstantFoldCastOperand(Instruction::PtrToInt,
994                                 const_cast<Constant *>(B), IntTy, DL);
995   else if (B->getType() != IntTy)
996     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
997                                 IntTy, DL);
998 
999   return A == B;
1000 }
1001 
1002 /// Create a new entry in the constant pool or return an existing one.
1003 /// User must specify the log2 of the minimum required alignment for the object.
1004 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1005                                                    unsigned Alignment) {
1006   assert(Alignment && "Alignment must be specified!");
1007   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1008 
1009   // Check to see if we already have this constant.
1010   //
1011   // FIXME, this could be made much more efficient for large constant pools.
1012   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1013     if (!Constants[i].isMachineConstantPoolEntry() &&
1014         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1015       if ((unsigned)Constants[i].getAlignment() < Alignment)
1016         Constants[i].Alignment = Alignment;
1017       return i;
1018     }
1019 
1020   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1021   return Constants.size()-1;
1022 }
1023 
1024 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1025                                                    unsigned Alignment) {
1026   assert(Alignment && "Alignment must be specified!");
1027   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1028 
1029   // Check to see if we already have this constant.
1030   //
1031   // FIXME, this could be made much more efficient for large constant pools.
1032   int Idx = V->getExistingMachineCPValue(this, Alignment);
1033   if (Idx != -1) {
1034     MachineCPVsSharingEntries.insert(V);
1035     return (unsigned)Idx;
1036   }
1037 
1038   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1039   return Constants.size()-1;
1040 }
1041 
1042 void MachineConstantPool::print(raw_ostream &OS) const {
1043   if (Constants.empty()) return;
1044 
1045   OS << "Constant Pool:\n";
1046   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1047     OS << "  cp#" << i << ": ";
1048     if (Constants[i].isMachineConstantPoolEntry())
1049       Constants[i].Val.MachineCPVal->print(OS);
1050     else
1051       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1052     OS << ", align=" << Constants[i].getAlignment();
1053     OS << "\n";
1054   }
1055 }
1056 
1057 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1058 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1059 #endif
1060