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