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