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/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/EHPersonalities.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionInitializer.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/CodeGen/WinEHFuncInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ModuleSlotTracker.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "codegen"
49 
50 static cl::opt<unsigned>
51     AlignAllFunctions("align-all-functions",
52                       cl::desc("Force the alignment of all functions."),
53                       cl::init(0), cl::Hidden);
54 
55 void MachineFunctionInitializer::anchor() {}
56 
57 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
58   typedef MachineFunctionProperties::Property P;
59   switch(Prop) {
60   case P::AllVRegsAllocated: return "AllVRegsAllocated";
61   case P::IsSSA: return "IsSSA";
62   case P::Legalized: return "Legalized";
63   case P::NoPHIs: return "NoPHIs";
64   case P::RegBankSelected: return "RegBankSelected";
65   case P::Selected: return "Selected";
66   case P::TracksLiveness: return "TracksLiveness";
67   }
68   llvm_unreachable("Invalid machine function property");
69 }
70 
71 void MachineFunctionProperties::print(raw_ostream &OS) const {
72   const char *Separator = "";
73   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
74     if (!Properties[I])
75       continue;
76     OS << Separator << getPropertyName(static_cast<Property>(I));
77     Separator = ", ";
78   }
79 }
80 
81 //===----------------------------------------------------------------------===//
82 // MachineFunction implementation
83 //===----------------------------------------------------------------------===//
84 
85 // Out-of-line virtual method.
86 MachineFunctionInfo::~MachineFunctionInfo() {}
87 
88 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
89   MBB->getParent()->DeleteMachineBasicBlock(MBB);
90 }
91 
92 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
93                                            const Function *Fn) {
94   if (Fn->hasFnAttribute(Attribute::StackAlignment))
95     return Fn->getFnStackAlignment();
96   return STI->getFrameLowering()->getStackAlignment();
97 }
98 
99 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
100                                  unsigned FunctionNum, MachineModuleInfo &mmi)
101     : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
102       MMI(mmi) {
103   // Assume the function starts in SSA form with correct liveness.
104   Properties.set(MachineFunctionProperties::Property::IsSSA);
105   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
106   if (STI->getRegisterInfo())
107     RegInfo = new (Allocator) MachineRegisterInfo(this);
108   else
109     RegInfo = nullptr;
110 
111   MFInfo = nullptr;
112   // We can realign the stack if the target supports it and the user hasn't
113   // explicitly asked us not to.
114   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
115                       !F->hasFnAttribute("no-realign-stack");
116   FrameInfo = new (Allocator) MachineFrameInfo(
117       getFnStackAlignment(STI, Fn), /*StackRealignable=*/CanRealignSP,
118       /*ForceRealign=*/CanRealignSP &&
119           F->hasFnAttribute(Attribute::StackAlignment));
120 
121   if (Fn->hasFnAttribute(Attribute::StackAlignment))
122     FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
123 
124   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
125   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
126 
127   // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
128   // FIXME: Use Function::optForSize().
129   if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
130     Alignment = std::max(Alignment,
131                          STI->getTargetLowering()->getPrefFunctionAlignment());
132 
133   if (AlignAllFunctions)
134     Alignment = AlignAllFunctions;
135 
136   FunctionNumber = FunctionNum;
137   JumpTableInfo = nullptr;
138 
139   if (isFuncletEHPersonality(classifyEHPersonality(
140           F->hasPersonalityFn() ? F->getPersonalityFn() : nullptr))) {
141     WinEHInfo = new (Allocator) WinEHFuncInfo();
142   }
143 
144   assert(TM.isCompatibleDataLayout(getDataLayout()) &&
145          "Can't create a MachineFunction using a Module with a "
146          "Target-incompatible DataLayout attached\n");
147 
148   PSVManager = llvm::make_unique<PseudoSourceValueManager>();
149 }
150 
151 MachineFunction::~MachineFunction() {
152   // Don't call destructors on MachineInstr and MachineOperand. All of their
153   // memory comes from the BumpPtrAllocator which is about to be purged.
154   //
155   // Do call MachineBasicBlock destructors, it contains std::vectors.
156   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
157     I->Insts.clearAndLeakNodesUnsafely();
158 
159   InstructionRecycler.clear(Allocator);
160   OperandRecycler.clear(Allocator);
161   BasicBlockRecycler.clear(Allocator);
162   if (RegInfo) {
163     RegInfo->~MachineRegisterInfo();
164     Allocator.Deallocate(RegInfo);
165   }
166   if (MFInfo) {
167     MFInfo->~MachineFunctionInfo();
168     Allocator.Deallocate(MFInfo);
169   }
170 
171   FrameInfo->~MachineFrameInfo();
172   Allocator.Deallocate(FrameInfo);
173 
174   ConstantPool->~MachineConstantPool();
175   Allocator.Deallocate(ConstantPool);
176 
177   if (JumpTableInfo) {
178     JumpTableInfo->~MachineJumpTableInfo();
179     Allocator.Deallocate(JumpTableInfo);
180   }
181 
182   if (WinEHInfo) {
183     WinEHInfo->~WinEHFuncInfo();
184     Allocator.Deallocate(WinEHInfo);
185   }
186 }
187 
188 const DataLayout &MachineFunction::getDataLayout() const {
189   return Fn->getParent()->getDataLayout();
190 }
191 
192 /// Get the JumpTableInfo for this function.
193 /// If it does not already exist, allocate one.
194 MachineJumpTableInfo *MachineFunction::
195 getOrCreateJumpTableInfo(unsigned EntryKind) {
196   if (JumpTableInfo) return JumpTableInfo;
197 
198   JumpTableInfo = new (Allocator)
199     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
200   return JumpTableInfo;
201 }
202 
203 /// Should we be emitting segmented stack stuff for the function
204 bool MachineFunction::shouldSplitStack() const {
205   return getFunction()->hasFnAttribute("split-stack");
206 }
207 
208 /// This discards all of the MachineBasicBlock numbers and recomputes them.
209 /// This guarantees that the MBB numbers are sequential, dense, and match the
210 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
211 /// is specified, only that block and those after it are renumbered.
212 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
213   if (empty()) { MBBNumbering.clear(); return; }
214   MachineFunction::iterator MBBI, E = end();
215   if (MBB == nullptr)
216     MBBI = begin();
217   else
218     MBBI = MBB->getIterator();
219 
220   // Figure out the block number this should have.
221   unsigned BlockNo = 0;
222   if (MBBI != begin())
223     BlockNo = std::prev(MBBI)->getNumber() + 1;
224 
225   for (; MBBI != E; ++MBBI, ++BlockNo) {
226     if (MBBI->getNumber() != (int)BlockNo) {
227       // Remove use of the old number.
228       if (MBBI->getNumber() != -1) {
229         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
230                "MBB number mismatch!");
231         MBBNumbering[MBBI->getNumber()] = nullptr;
232       }
233 
234       // If BlockNo is already taken, set that block's number to -1.
235       if (MBBNumbering[BlockNo])
236         MBBNumbering[BlockNo]->setNumber(-1);
237 
238       MBBNumbering[BlockNo] = &*MBBI;
239       MBBI->setNumber(BlockNo);
240     }
241   }
242 
243   // Okay, all the blocks are renumbered.  If we have compactified the block
244   // numbering, shrink MBBNumbering now.
245   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
246   MBBNumbering.resize(BlockNo);
247 }
248 
249 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
250 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
251                                                   const DebugLoc &DL,
252                                                   bool NoImp) {
253   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
254     MachineInstr(*this, MCID, DL, NoImp);
255 }
256 
257 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
258 /// identical in all ways except the instruction has no parent, prev, or next.
259 MachineInstr *
260 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
261   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
262              MachineInstr(*this, *Orig);
263 }
264 
265 /// Delete the given MachineInstr.
266 ///
267 /// This function also serves as the MachineInstr destructor - the real
268 /// ~MachineInstr() destructor must be empty.
269 void
270 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
271   // Strip it for parts. The operand array and the MI object itself are
272   // independently recyclable.
273   if (MI->Operands)
274     deallocateOperandArray(MI->CapOperands, MI->Operands);
275   // Don't call ~MachineInstr() which must be trivial anyway because
276   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
277   // destructors.
278   InstructionRecycler.Deallocate(Allocator, MI);
279 }
280 
281 /// Allocate a new MachineBasicBlock. Use this instead of
282 /// `new MachineBasicBlock'.
283 MachineBasicBlock *
284 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
285   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
286              MachineBasicBlock(*this, bb);
287 }
288 
289 /// Delete the given MachineBasicBlock.
290 void
291 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
292   assert(MBB->getParent() == this && "MBB parent mismatch!");
293   MBB->~MachineBasicBlock();
294   BasicBlockRecycler.Deallocate(Allocator, MBB);
295 }
296 
297 MachineMemOperand *MachineFunction::getMachineMemOperand(
298     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
299     unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges) {
300   return new (Allocator)
301       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges);
302 }
303 
304 MachineMemOperand *
305 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
306                                       int64_t Offset, uint64_t Size) {
307   if (MMO->getValue())
308     return new (Allocator)
309                MachineMemOperand(MachinePointerInfo(MMO->getValue(),
310                                                     MMO->getOffset()+Offset),
311                                  MMO->getFlags(), Size,
312                                  MMO->getBaseAlignment());
313   return new (Allocator)
314              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
315                                                   MMO->getOffset()+Offset),
316                                MMO->getFlags(), Size,
317                                MMO->getBaseAlignment());
318 }
319 
320 MachineInstr::mmo_iterator
321 MachineFunction::allocateMemRefsArray(unsigned long Num) {
322   return Allocator.Allocate<MachineMemOperand *>(Num);
323 }
324 
325 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
326 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
327                                     MachineInstr::mmo_iterator End) {
328   // Count the number of load mem refs.
329   unsigned Num = 0;
330   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
331     if ((*I)->isLoad())
332       ++Num;
333 
334   // Allocate a new array and populate it with the load information.
335   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
336   unsigned Index = 0;
337   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
338     if ((*I)->isLoad()) {
339       if (!(*I)->isStore())
340         // Reuse the MMO.
341         Result[Index] = *I;
342       else {
343         // Clone the MMO and unset the store flag.
344         MachineMemOperand *JustLoad =
345           getMachineMemOperand((*I)->getPointerInfo(),
346                                (*I)->getFlags() & ~MachineMemOperand::MOStore,
347                                (*I)->getSize(), (*I)->getBaseAlignment(),
348                                (*I)->getAAInfo());
349         Result[Index] = JustLoad;
350       }
351       ++Index;
352     }
353   }
354   return std::make_pair(Result, Result + Num);
355 }
356 
357 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
358 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
359                                      MachineInstr::mmo_iterator End) {
360   // Count the number of load mem refs.
361   unsigned Num = 0;
362   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
363     if ((*I)->isStore())
364       ++Num;
365 
366   // Allocate a new array and populate it with the store information.
367   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
368   unsigned Index = 0;
369   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
370     if ((*I)->isStore()) {
371       if (!(*I)->isLoad())
372         // Reuse the MMO.
373         Result[Index] = *I;
374       else {
375         // Clone the MMO and unset the load flag.
376         MachineMemOperand *JustStore =
377           getMachineMemOperand((*I)->getPointerInfo(),
378                                (*I)->getFlags() & ~MachineMemOperand::MOLoad,
379                                (*I)->getSize(), (*I)->getBaseAlignment(),
380                                (*I)->getAAInfo());
381         Result[Index] = JustStore;
382       }
383       ++Index;
384     }
385   }
386   return std::make_pair(Result, Result + Num);
387 }
388 
389 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
390   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
391   std::copy(Name.begin(), Name.end(), Dest);
392   Dest[Name.size()] = 0;
393   return Dest;
394 }
395 
396 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
397 LLVM_DUMP_METHOD void MachineFunction::dump() const {
398   print(dbgs());
399 }
400 #endif
401 
402 StringRef MachineFunction::getName() const {
403   assert(getFunction() && "No function!");
404   return getFunction()->getName();
405 }
406 
407 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
408   OS << "# Machine code for function " << getName() << ": ";
409   getProperties().print(OS);
410 
411   // Print Frame Information
412   FrameInfo->print(*this, OS);
413 
414   // Print JumpTable Information
415   if (JumpTableInfo)
416     JumpTableInfo->print(OS);
417 
418   // Print Constant Pool
419   ConstantPool->print(OS);
420 
421   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
422 
423   if (RegInfo && !RegInfo->livein_empty()) {
424     OS << "Function Live Ins: ";
425     for (MachineRegisterInfo::livein_iterator
426          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
427       OS << PrintReg(I->first, TRI);
428       if (I->second)
429         OS << " in " << PrintReg(I->second, TRI);
430       if (std::next(I) != E)
431         OS << ", ";
432     }
433     OS << '\n';
434   }
435 
436   ModuleSlotTracker MST(getFunction()->getParent());
437   MST.incorporateFunction(*getFunction());
438   for (const auto &BB : *this) {
439     OS << '\n';
440     BB.print(OS, MST, Indexes);
441   }
442 
443   OS << "\n# End machine code for function " << getName() << ".\n\n";
444 }
445 
446 namespace llvm {
447   template<>
448   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
449 
450   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
451 
452     static std::string getGraphName(const MachineFunction *F) {
453       return ("CFG for '" + F->getName() + "' function").str();
454     }
455 
456     std::string getNodeLabel(const MachineBasicBlock *Node,
457                              const MachineFunction *Graph) {
458       std::string OutStr;
459       {
460         raw_string_ostream OSS(OutStr);
461 
462         if (isSimple()) {
463           OSS << "BB#" << Node->getNumber();
464           if (const BasicBlock *BB = Node->getBasicBlock())
465             OSS << ": " << BB->getName();
466         } else
467           Node->print(OSS);
468       }
469 
470       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
471 
472       // Process string output to make it nicer...
473       for (unsigned i = 0; i != OutStr.length(); ++i)
474         if (OutStr[i] == '\n') {                            // Left justify
475           OutStr[i] = '\\';
476           OutStr.insert(OutStr.begin()+i+1, 'l');
477         }
478       return OutStr;
479     }
480   };
481 }
482 
483 void MachineFunction::viewCFG() const
484 {
485 #ifndef NDEBUG
486   ViewGraph(this, "mf" + getName());
487 #else
488   errs() << "MachineFunction::viewCFG is only available in debug builds on "
489          << "systems with Graphviz or gv!\n";
490 #endif // NDEBUG
491 }
492 
493 void MachineFunction::viewCFGOnly() const
494 {
495 #ifndef NDEBUG
496   ViewGraph(this, "mf" + getName(), true);
497 #else
498   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
499          << "systems with Graphviz or gv!\n";
500 #endif // NDEBUG
501 }
502 
503 /// Add the specified physical register as a live-in value and
504 /// create a corresponding virtual register for it.
505 unsigned MachineFunction::addLiveIn(unsigned PReg,
506                                     const TargetRegisterClass *RC) {
507   MachineRegisterInfo &MRI = getRegInfo();
508   unsigned VReg = MRI.getLiveInVirtReg(PReg);
509   if (VReg) {
510     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
511     (void)VRegRC;
512     // A physical register can be added several times.
513     // Between two calls, the register class of the related virtual register
514     // may have been constrained to match some operation constraints.
515     // In that case, check that the current register class includes the
516     // physical register and is a sub class of the specified RC.
517     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
518                              RC->hasSubClassEq(VRegRC))) &&
519             "Register class mismatch!");
520     return VReg;
521   }
522   VReg = MRI.createVirtualRegister(RC);
523   MRI.addLiveIn(PReg, VReg);
524   return VReg;
525 }
526 
527 /// Return the MCSymbol for the specified non-empty jump table.
528 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
529 /// normal 'L' label is returned.
530 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
531                                         bool isLinkerPrivate) const {
532   const DataLayout &DL = getDataLayout();
533   assert(JumpTableInfo && "No jump tables");
534   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
535 
536   const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
537                                        : DL.getPrivateGlobalPrefix();
538   SmallString<60> Name;
539   raw_svector_ostream(Name)
540     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
541   return Ctx.getOrCreateSymbol(Name);
542 }
543 
544 /// Return a function-local symbol to represent the PIC base.
545 MCSymbol *MachineFunction::getPICBaseSymbol() const {
546   const DataLayout &DL = getDataLayout();
547   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
548                                Twine(getFunctionNumber()) + "$pb");
549 }
550 
551 //===----------------------------------------------------------------------===//
552 //  MachineFrameInfo implementation
553 //===----------------------------------------------------------------------===//
554 
555 /// Make sure the function is at least Align bytes aligned.
556 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
557   if (!StackRealignable)
558     assert(Align <= StackAlignment &&
559            "For targets without stack realignment, Align is out of limit!");
560   if (MaxAlignment < Align) MaxAlignment = Align;
561 }
562 
563 /// Clamp the alignment if requested and emit a warning.
564 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
565                                            unsigned StackAlign) {
566   if (!ShouldClamp || Align <= StackAlign)
567     return Align;
568   DEBUG(dbgs() << "Warning: requested alignment " << Align
569                << " exceeds the stack alignment " << StackAlign
570                << " when stack realignment is off" << '\n');
571   return StackAlign;
572 }
573 
574 /// Create a new statically sized stack object, returning a nonnegative
575 /// identifier to represent it.
576 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
577                       bool isSS, const AllocaInst *Alloca) {
578   assert(Size != 0 && "Cannot allocate zero size stack objects!");
579   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
580   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
581                                 !isSS));
582   int Index = (int)Objects.size() - NumFixedObjects - 1;
583   assert(Index >= 0 && "Bad frame index!");
584   ensureMaxAlignment(Alignment);
585   return Index;
586 }
587 
588 /// Create a new statically sized stack object that represents a spill slot,
589 /// returning a nonnegative identifier to represent it.
590 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
591                                              unsigned Alignment) {
592   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
593   CreateStackObject(Size, Alignment, true);
594   int Index = (int)Objects.size() - NumFixedObjects - 1;
595   ensureMaxAlignment(Alignment);
596   return Index;
597 }
598 
599 /// Notify the MachineFrameInfo object that a variable sized object has been
600 /// created. This must be created whenever a variable sized object is created,
601 /// whether or not the index returned is actually used.
602 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
603                                                 const AllocaInst *Alloca) {
604   HasVarSizedObjects = true;
605   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
606   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
607   ensureMaxAlignment(Alignment);
608   return (int)Objects.size()-NumFixedObjects-1;
609 }
610 
611 /// Create a new object at a fixed location on the stack.
612 /// All fixed objects should be created before other objects are created for
613 /// efficiency. By default, fixed objects are immutable. This returns an
614 /// index with a negative value.
615 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
616                                         bool Immutable, bool isAliased) {
617   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
618   // The alignment of the frame index can be determined from its offset from
619   // the incoming frame position.  If the frame object is at offset 32 and
620   // the stack is guaranteed to be 16-byte aligned, then we know that the
621   // object is 16-byte aligned. Note that unlike the non-fixed case, if the
622   // stack needs realignment, we can't assume that the stack will in fact be
623   // aligned.
624   unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment);
625   Align = clampStackAlignment(!StackRealignable, Align, StackAlignment);
626   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
627                                               /*isSS*/   false,
628                                               /*Alloca*/ nullptr, isAliased));
629   return -++NumFixedObjects;
630 }
631 
632 /// Create a spill slot at a fixed location on the stack.
633 /// Returns an index with a negative value.
634 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
635                                                   int64_t SPOffset) {
636   unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment);
637   Align = clampStackAlignment(!StackRealignable, Align, StackAlignment);
638   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
639                                               /*Immutable*/ true,
640                                               /*isSS*/ true,
641                                               /*Alloca*/ nullptr,
642                                               /*isAliased*/ false));
643   return -++NumFixedObjects;
644 }
645 
646 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
647   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
648   BitVector BV(TRI->getNumRegs());
649 
650   // Before CSI is calculated, no registers are considered pristine. They can be
651   // freely used and PEI will make sure they are saved.
652   if (!isCalleeSavedInfoValid())
653     return BV;
654 
655   for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
656     BV.set(*CSR);
657 
658   // Saved CSRs are not pristine.
659   for (auto &I : getCalleeSavedInfo())
660     for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S)
661       BV.reset(*S);
662 
663   return BV;
664 }
665 
666 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
667   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
668   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
669   unsigned MaxAlign = getMaxAlignment();
670   int Offset = 0;
671 
672   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
673   // It really should be refactored to share code. Until then, changes
674   // should keep in mind that there's tight coupling between the two.
675 
676   for (int i = getObjectIndexBegin(); i != 0; ++i) {
677     int FixedOff = -getObjectOffset(i);
678     if (FixedOff > Offset) Offset = FixedOff;
679   }
680   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
681     if (isDeadObjectIndex(i))
682       continue;
683     Offset += getObjectSize(i);
684     unsigned Align = getObjectAlignment(i);
685     // Adjust to alignment boundary
686     Offset = (Offset+Align-1)/Align*Align;
687 
688     MaxAlign = std::max(Align, MaxAlign);
689   }
690 
691   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
692     Offset += getMaxCallFrameSize();
693 
694   // Round up the size to a multiple of the alignment.  If the function has
695   // any calls or alloca's, align to the target's StackAlignment value to
696   // ensure that the callee's frame or the alloca data is suitably aligned;
697   // otherwise, for leaf functions, align to the TransientStackAlignment
698   // value.
699   unsigned StackAlign;
700   if (adjustsStack() || hasVarSizedObjects() ||
701       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
702     StackAlign = TFI->getStackAlignment();
703   else
704     StackAlign = TFI->getTransientStackAlignment();
705 
706   // If the frame pointer is eliminated, all frame offsets will be relative to
707   // SP not FP. Align to MaxAlign so this works.
708   StackAlign = std::max(StackAlign, MaxAlign);
709   unsigned AlignMask = StackAlign - 1;
710   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
711 
712   return (unsigned)Offset;
713 }
714 
715 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
716   if (Objects.empty()) return;
717 
718   const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
719   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
720 
721   OS << "Frame Objects:\n";
722 
723   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
724     const StackObject &SO = Objects[i];
725     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
726     if (SO.Size == ~0ULL) {
727       OS << "dead\n";
728       continue;
729     }
730     if (SO.Size == 0)
731       OS << "variable sized";
732     else
733       OS << "size=" << SO.Size;
734     OS << ", align=" << SO.Alignment;
735 
736     if (i < NumFixedObjects)
737       OS << ", fixed";
738     if (i < NumFixedObjects || SO.SPOffset != -1) {
739       int64_t Off = SO.SPOffset - ValOffset;
740       OS << ", at location [SP";
741       if (Off > 0)
742         OS << "+" << Off;
743       else if (Off < 0)
744         OS << Off;
745       OS << "]";
746     }
747     OS << "\n";
748   }
749 }
750 
751 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
752 void MachineFrameInfo::dump(const MachineFunction &MF) const {
753   print(MF, dbgs());
754 }
755 #endif
756 
757 //===----------------------------------------------------------------------===//
758 //  MachineJumpTableInfo implementation
759 //===----------------------------------------------------------------------===//
760 
761 /// Return the size of each entry in the jump table.
762 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
763   // The size of a jump table entry is 4 bytes unless the entry is just the
764   // address of a block, in which case it is the pointer size.
765   switch (getEntryKind()) {
766   case MachineJumpTableInfo::EK_BlockAddress:
767     return TD.getPointerSize();
768   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
769     return 8;
770   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
771   case MachineJumpTableInfo::EK_LabelDifference32:
772   case MachineJumpTableInfo::EK_Custom32:
773     return 4;
774   case MachineJumpTableInfo::EK_Inline:
775     return 0;
776   }
777   llvm_unreachable("Unknown jump table encoding!");
778 }
779 
780 /// Return the alignment of each entry in the jump table.
781 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
782   // The alignment of a jump table entry is the alignment of int32 unless the
783   // entry is just the address of a block, in which case it is the pointer
784   // alignment.
785   switch (getEntryKind()) {
786   case MachineJumpTableInfo::EK_BlockAddress:
787     return TD.getPointerABIAlignment();
788   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
789     return TD.getABIIntegerTypeAlignment(64);
790   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
791   case MachineJumpTableInfo::EK_LabelDifference32:
792   case MachineJumpTableInfo::EK_Custom32:
793     return TD.getABIIntegerTypeAlignment(32);
794   case MachineJumpTableInfo::EK_Inline:
795     return 1;
796   }
797   llvm_unreachable("Unknown jump table encoding!");
798 }
799 
800 /// Create a new jump table entry in the jump table info.
801 unsigned MachineJumpTableInfo::createJumpTableIndex(
802                                const std::vector<MachineBasicBlock*> &DestBBs) {
803   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
804   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
805   return JumpTables.size()-1;
806 }
807 
808 /// If Old is the target of any jump tables, update the jump tables to branch
809 /// to New instead.
810 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
811                                                   MachineBasicBlock *New) {
812   assert(Old != New && "Not making a change?");
813   bool MadeChange = false;
814   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
815     ReplaceMBBInJumpTable(i, Old, New);
816   return MadeChange;
817 }
818 
819 /// If Old is a target of the jump tables, update the jump table to branch to
820 /// New instead.
821 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
822                                                  MachineBasicBlock *Old,
823                                                  MachineBasicBlock *New) {
824   assert(Old != New && "Not making a change?");
825   bool MadeChange = false;
826   MachineJumpTableEntry &JTE = JumpTables[Idx];
827   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
828     if (JTE.MBBs[j] == Old) {
829       JTE.MBBs[j] = New;
830       MadeChange = true;
831     }
832   return MadeChange;
833 }
834 
835 void MachineJumpTableInfo::print(raw_ostream &OS) const {
836   if (JumpTables.empty()) return;
837 
838   OS << "Jump Tables:\n";
839 
840   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
841     OS << "  jt#" << i << ": ";
842     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
843       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
844   }
845 
846   OS << '\n';
847 }
848 
849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
850 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
851 #endif
852 
853 
854 //===----------------------------------------------------------------------===//
855 //  MachineConstantPool implementation
856 //===----------------------------------------------------------------------===//
857 
858 void MachineConstantPoolValue::anchor() { }
859 
860 Type *MachineConstantPoolEntry::getType() const {
861   if (isMachineConstantPoolEntry())
862     return Val.MachineCPVal->getType();
863   return Val.ConstVal->getType();
864 }
865 
866 bool MachineConstantPoolEntry::needsRelocation() const {
867   if (isMachineConstantPoolEntry())
868     return true;
869   return Val.ConstVal->needsRelocation();
870 }
871 
872 SectionKind
873 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
874   if (needsRelocation())
875     return SectionKind::getReadOnlyWithRel();
876   switch (DL->getTypeAllocSize(getType())) {
877   case 4:
878     return SectionKind::getMergeableConst4();
879   case 8:
880     return SectionKind::getMergeableConst8();
881   case 16:
882     return SectionKind::getMergeableConst16();
883   case 32:
884     return SectionKind::getMergeableConst32();
885   default:
886     return SectionKind::getReadOnly();
887   }
888 }
889 
890 MachineConstantPool::~MachineConstantPool() {
891   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
892     if (Constants[i].isMachineConstantPoolEntry())
893       delete Constants[i].Val.MachineCPVal;
894   for (DenseSet<MachineConstantPoolValue*>::iterator I =
895        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
896        I != E; ++I)
897     delete *I;
898 }
899 
900 /// Test whether the given two constants can be allocated the same constant pool
901 /// entry.
902 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
903                                       const DataLayout &DL) {
904   // Handle the trivial case quickly.
905   if (A == B) return true;
906 
907   // If they have the same type but weren't the same constant, quickly
908   // reject them.
909   if (A->getType() == B->getType()) return false;
910 
911   // We can't handle structs or arrays.
912   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
913       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
914     return false;
915 
916   // For now, only support constants with the same size.
917   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
918   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
919     return false;
920 
921   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
922 
923   // Try constant folding a bitcast of both instructions to an integer.  If we
924   // get two identical ConstantInt's, then we are good to share them.  We use
925   // the constant folding APIs to do this so that we get the benefit of
926   // DataLayout.
927   if (isa<PointerType>(A->getType()))
928     A = ConstantFoldCastOperand(Instruction::PtrToInt,
929                                 const_cast<Constant *>(A), IntTy, DL);
930   else if (A->getType() != IntTy)
931     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
932                                 IntTy, DL);
933   if (isa<PointerType>(B->getType()))
934     B = ConstantFoldCastOperand(Instruction::PtrToInt,
935                                 const_cast<Constant *>(B), IntTy, DL);
936   else if (B->getType() != IntTy)
937     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
938                                 IntTy, DL);
939 
940   return A == B;
941 }
942 
943 /// Create a new entry in the constant pool or return an existing one.
944 /// User must specify the log2 of the minimum required alignment for the object.
945 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
946                                                    unsigned Alignment) {
947   assert(Alignment && "Alignment must be specified!");
948   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
949 
950   // Check to see if we already have this constant.
951   //
952   // FIXME, this could be made much more efficient for large constant pools.
953   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
954     if (!Constants[i].isMachineConstantPoolEntry() &&
955         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
956       if ((unsigned)Constants[i].getAlignment() < Alignment)
957         Constants[i].Alignment = Alignment;
958       return i;
959     }
960 
961   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
962   return Constants.size()-1;
963 }
964 
965 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
966                                                    unsigned Alignment) {
967   assert(Alignment && "Alignment must be specified!");
968   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
969 
970   // Check to see if we already have this constant.
971   //
972   // FIXME, this could be made much more efficient for large constant pools.
973   int Idx = V->getExistingMachineCPValue(this, Alignment);
974   if (Idx != -1) {
975     MachineCPVsSharingEntries.insert(V);
976     return (unsigned)Idx;
977   }
978 
979   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
980   return Constants.size()-1;
981 }
982 
983 void MachineConstantPool::print(raw_ostream &OS) const {
984   if (Constants.empty()) return;
985 
986   OS << "Constant Pool:\n";
987   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
988     OS << "  cp#" << i << ": ";
989     if (Constants[i].isMachineConstantPoolEntry())
990       Constants[i].Val.MachineCPVal->print(OS);
991     else
992       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
993     OS << ", align=" << Constants[i].getAlignment();
994     OS << "\n";
995   }
996 }
997 
998 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
999 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1000 #endif
1001