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