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   for (BitVector::size_type i = 0; i < Properties.size(); ++i) {
61     bool HasProperty = Properties[i];
62     if (OnlySet && !HasProperty)
63       continue;
64     switch(static_cast<Property>(i)) {
65       case Property::IsSSA:
66         ROS << (HasProperty ? "SSA, " : "Post SSA, ");
67         break;
68       case Property::TracksLiveness:
69         ROS << (HasProperty ? "" : "not ") << "tracking liveness, ";
70         break;
71       case Property::AllVRegsAllocated:
72         ROS << (HasProperty ? "AllVRegsAllocated" : "HasVRegs");
73         break;
74       default:
75         break;
76     }
77   }
78 #endif
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 *
251 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
252                                     DebugLoc DL, 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 *
298 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
299                                       uint64_t s, unsigned base_alignment,
300                                       const AAMDNodes &AAInfo,
301                                       const MDNode *Ranges) {
302   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
303                                            AAInfo, Ranges);
304 }
305 
306 MachineMemOperand *
307 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
308                                       int64_t Offset, uint64_t Size) {
309   if (MMO->getValue())
310     return new (Allocator)
311                MachineMemOperand(MachinePointerInfo(MMO->getValue(),
312                                                     MMO->getOffset()+Offset),
313                                  MMO->getFlags(), Size,
314                                  MMO->getBaseAlignment());
315   return new (Allocator)
316              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
317                                                   MMO->getOffset()+Offset),
318                                MMO->getFlags(), Size,
319                                MMO->getBaseAlignment());
320 }
321 
322 MachineInstr::mmo_iterator
323 MachineFunction::allocateMemRefsArray(unsigned long Num) {
324   return Allocator.Allocate<MachineMemOperand *>(Num);
325 }
326 
327 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
328 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
329                                     MachineInstr::mmo_iterator End) {
330   // Count the number of load mem refs.
331   unsigned Num = 0;
332   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
333     if ((*I)->isLoad())
334       ++Num;
335 
336   // Allocate a new array and populate it with the load information.
337   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
338   unsigned Index = 0;
339   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
340     if ((*I)->isLoad()) {
341       if (!(*I)->isStore())
342         // Reuse the MMO.
343         Result[Index] = *I;
344       else {
345         // Clone the MMO and unset the store flag.
346         MachineMemOperand *JustLoad =
347           getMachineMemOperand((*I)->getPointerInfo(),
348                                (*I)->getFlags() & ~MachineMemOperand::MOStore,
349                                (*I)->getSize(), (*I)->getBaseAlignment(),
350                                (*I)->getAAInfo());
351         Result[Index] = JustLoad;
352       }
353       ++Index;
354     }
355   }
356   return std::make_pair(Result, Result + Num);
357 }
358 
359 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
360 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
361                                      MachineInstr::mmo_iterator End) {
362   // Count the number of load mem refs.
363   unsigned Num = 0;
364   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
365     if ((*I)->isStore())
366       ++Num;
367 
368   // Allocate a new array and populate it with the store information.
369   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
370   unsigned Index = 0;
371   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
372     if ((*I)->isStore()) {
373       if (!(*I)->isLoad())
374         // Reuse the MMO.
375         Result[Index] = *I;
376       else {
377         // Clone the MMO and unset the load flag.
378         MachineMemOperand *JustStore =
379           getMachineMemOperand((*I)->getPointerInfo(),
380                                (*I)->getFlags() & ~MachineMemOperand::MOLoad,
381                                (*I)->getSize(), (*I)->getBaseAlignment(),
382                                (*I)->getAAInfo());
383         Result[Index] = JustStore;
384       }
385       ++Index;
386     }
387   }
388   return std::make_pair(Result, Result + Num);
389 }
390 
391 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
392   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
393   std::copy(Name.begin(), Name.end(), Dest);
394   Dest[Name.size()] = 0;
395   return Dest;
396 }
397 
398 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
399 LLVM_DUMP_METHOD void MachineFunction::dump() const {
400   print(dbgs());
401 }
402 #endif
403 
404 StringRef MachineFunction::getName() const {
405   assert(getFunction() && "No function!");
406   return getFunction()->getName();
407 }
408 
409 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
410   OS << "# Machine code for function " << getName() << ": ";
411   OS << "Properties: <";
412   getProperties().print(OS);
413   OS << ">\n";
414 
415   // Print Frame Information
416   FrameInfo->print(*this, OS);
417 
418   // Print JumpTable Information
419   if (JumpTableInfo)
420     JumpTableInfo->print(OS);
421 
422   // Print Constant Pool
423   ConstantPool->print(OS);
424 
425   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
426 
427   if (RegInfo && !RegInfo->livein_empty()) {
428     OS << "Function Live Ins: ";
429     for (MachineRegisterInfo::livein_iterator
430          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
431       OS << PrintReg(I->first, TRI);
432       if (I->second)
433         OS << " in " << PrintReg(I->second, TRI);
434       if (std::next(I) != E)
435         OS << ", ";
436     }
437     OS << '\n';
438   }
439 
440   ModuleSlotTracker MST(getFunction()->getParent());
441   MST.incorporateFunction(*getFunction());
442   for (const auto &BB : *this) {
443     OS << '\n';
444     BB.print(OS, MST, Indexes);
445   }
446 
447   OS << "\n# End machine code for function " << getName() << ".\n\n";
448 }
449 
450 namespace llvm {
451   template<>
452   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
453 
454   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
455 
456     static std::string getGraphName(const MachineFunction *F) {
457       return ("CFG for '" + F->getName() + "' function").str();
458     }
459 
460     std::string getNodeLabel(const MachineBasicBlock *Node,
461                              const MachineFunction *Graph) {
462       std::string OutStr;
463       {
464         raw_string_ostream OSS(OutStr);
465 
466         if (isSimple()) {
467           OSS << "BB#" << Node->getNumber();
468           if (const BasicBlock *BB = Node->getBasicBlock())
469             OSS << ": " << BB->getName();
470         } else
471           Node->print(OSS);
472       }
473 
474       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
475 
476       // Process string output to make it nicer...
477       for (unsigned i = 0; i != OutStr.length(); ++i)
478         if (OutStr[i] == '\n') {                            // Left justify
479           OutStr[i] = '\\';
480           OutStr.insert(OutStr.begin()+i+1, 'l');
481         }
482       return OutStr;
483     }
484   };
485 }
486 
487 void MachineFunction::viewCFG() const
488 {
489 #ifndef NDEBUG
490   ViewGraph(this, "mf" + getName());
491 #else
492   errs() << "MachineFunction::viewCFG is only available in debug builds on "
493          << "systems with Graphviz or gv!\n";
494 #endif // NDEBUG
495 }
496 
497 void MachineFunction::viewCFGOnly() const
498 {
499 #ifndef NDEBUG
500   ViewGraph(this, "mf" + getName(), true);
501 #else
502   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
503          << "systems with Graphviz or gv!\n";
504 #endif // NDEBUG
505 }
506 
507 /// Add the specified physical register as a live-in value and
508 /// create a corresponding virtual register for it.
509 unsigned MachineFunction::addLiveIn(unsigned PReg,
510                                     const TargetRegisterClass *RC) {
511   MachineRegisterInfo &MRI = getRegInfo();
512   unsigned VReg = MRI.getLiveInVirtReg(PReg);
513   if (VReg) {
514     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
515     (void)VRegRC;
516     // A physical register can be added several times.
517     // Between two calls, the register class of the related virtual register
518     // may have been constrained to match some operation constraints.
519     // In that case, check that the current register class includes the
520     // physical register and is a sub class of the specified RC.
521     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
522                              RC->hasSubClassEq(VRegRC))) &&
523             "Register class mismatch!");
524     return VReg;
525   }
526   VReg = MRI.createVirtualRegister(RC);
527   MRI.addLiveIn(PReg, VReg);
528   return VReg;
529 }
530 
531 /// Return the MCSymbol for the specified non-empty jump table.
532 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
533 /// normal 'L' label is returned.
534 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
535                                         bool isLinkerPrivate) const {
536   const DataLayout &DL = getDataLayout();
537   assert(JumpTableInfo && "No jump tables");
538   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
539 
540   const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
541                                        : DL.getPrivateGlobalPrefix();
542   SmallString<60> Name;
543   raw_svector_ostream(Name)
544     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
545   return Ctx.getOrCreateSymbol(Name);
546 }
547 
548 /// Return a function-local symbol to represent the PIC base.
549 MCSymbol *MachineFunction::getPICBaseSymbol() const {
550   const DataLayout &DL = getDataLayout();
551   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
552                                Twine(getFunctionNumber()) + "$pb");
553 }
554 
555 //===----------------------------------------------------------------------===//
556 //  MachineFrameInfo implementation
557 //===----------------------------------------------------------------------===//
558 
559 /// Make sure the function is at least Align bytes aligned.
560 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
561   if (!StackRealignable)
562     assert(Align <= StackAlignment &&
563            "For targets without stack realignment, Align is out of limit!");
564   if (MaxAlignment < Align) MaxAlignment = Align;
565 }
566 
567 /// Clamp the alignment if requested and emit a warning.
568 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
569                                            unsigned StackAlign) {
570   if (!ShouldClamp || Align <= StackAlign)
571     return Align;
572   DEBUG(dbgs() << "Warning: requested alignment " << Align
573                << " exceeds the stack alignment " << StackAlign
574                << " when stack realignment is off" << '\n');
575   return StackAlign;
576 }
577 
578 /// Create a new statically sized stack object, returning a nonnegative
579 /// identifier to represent it.
580 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
581                       bool isSS, const AllocaInst *Alloca) {
582   assert(Size != 0 && "Cannot allocate zero size stack objects!");
583   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
584   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
585                                 !isSS));
586   int Index = (int)Objects.size() - NumFixedObjects - 1;
587   assert(Index >= 0 && "Bad frame index!");
588   ensureMaxAlignment(Alignment);
589   return Index;
590 }
591 
592 /// Create a new statically sized stack object that represents a spill slot,
593 /// returning a nonnegative identifier to represent it.
594 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
595                                              unsigned Alignment) {
596   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
597   CreateStackObject(Size, Alignment, true);
598   int Index = (int)Objects.size() - NumFixedObjects - 1;
599   ensureMaxAlignment(Alignment);
600   return Index;
601 }
602 
603 /// Notify the MachineFrameInfo object that a variable sized object has been
604 /// created. This must be created whenever a variable sized object is created,
605 /// whether or not the index returned is actually used.
606 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
607                                                 const AllocaInst *Alloca) {
608   HasVarSizedObjects = true;
609   Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
610   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
611   ensureMaxAlignment(Alignment);
612   return (int)Objects.size()-NumFixedObjects-1;
613 }
614 
615 /// Create a new object at a fixed location on the stack.
616 /// All fixed objects should be created before other objects are created for
617 /// efficiency. By default, fixed objects are immutable. This returns an
618 /// index with a negative value.
619 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
620                                         bool Immutable, bool isAliased) {
621   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
622   // The alignment of the frame index can be determined from its offset from
623   // the incoming frame position.  If the frame object is at offset 32 and
624   // the stack is guaranteed to be 16-byte aligned, then we know that the
625   // object is 16-byte aligned. Note that unlike the non-fixed case, if the
626   // stack needs realignment, we can't assume that the stack will in fact be
627   // aligned.
628   unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment);
629   Align = clampStackAlignment(!StackRealignable, Align, StackAlignment);
630   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
631                                               /*isSS*/   false,
632                                               /*Alloca*/ nullptr, isAliased));
633   return -++NumFixedObjects;
634 }
635 
636 /// Create a spill slot at a fixed location on the stack.
637 /// Returns an index with a negative value.
638 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
639                                                   int64_t SPOffset) {
640   unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment);
641   Align = clampStackAlignment(!StackRealignable, Align, StackAlignment);
642   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
643                                               /*Immutable*/ true,
644                                               /*isSS*/ true,
645                                               /*Alloca*/ nullptr,
646                                               /*isAliased*/ false));
647   return -++NumFixedObjects;
648 }
649 
650 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
651   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
652   BitVector BV(TRI->getNumRegs());
653 
654   // Before CSI is calculated, no registers are considered pristine. They can be
655   // freely used and PEI will make sure they are saved.
656   if (!isCalleeSavedInfoValid())
657     return BV;
658 
659   for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
660     BV.set(*CSR);
661 
662   // Saved CSRs are not pristine.
663   for (auto &I : getCalleeSavedInfo())
664     for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S)
665       BV.reset(*S);
666 
667   return BV;
668 }
669 
670 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
671   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
672   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
673   unsigned MaxAlign = getMaxAlignment();
674   int Offset = 0;
675 
676   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
677   // It really should be refactored to share code. Until then, changes
678   // should keep in mind that there's tight coupling between the two.
679 
680   for (int i = getObjectIndexBegin(); i != 0; ++i) {
681     int FixedOff = -getObjectOffset(i);
682     if (FixedOff > Offset) Offset = FixedOff;
683   }
684   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
685     if (isDeadObjectIndex(i))
686       continue;
687     Offset += getObjectSize(i);
688     unsigned Align = getObjectAlignment(i);
689     // Adjust to alignment boundary
690     Offset = (Offset+Align-1)/Align*Align;
691 
692     MaxAlign = std::max(Align, MaxAlign);
693   }
694 
695   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
696     Offset += getMaxCallFrameSize();
697 
698   // Round up the size to a multiple of the alignment.  If the function has
699   // any calls or alloca's, align to the target's StackAlignment value to
700   // ensure that the callee's frame or the alloca data is suitably aligned;
701   // otherwise, for leaf functions, align to the TransientStackAlignment
702   // value.
703   unsigned StackAlign;
704   if (adjustsStack() || hasVarSizedObjects() ||
705       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
706     StackAlign = TFI->getStackAlignment();
707   else
708     StackAlign = TFI->getTransientStackAlignment();
709 
710   // If the frame pointer is eliminated, all frame offsets will be relative to
711   // SP not FP. Align to MaxAlign so this works.
712   StackAlign = std::max(StackAlign, MaxAlign);
713   unsigned AlignMask = StackAlign - 1;
714   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
715 
716   return (unsigned)Offset;
717 }
718 
719 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
720   if (Objects.empty()) return;
721 
722   const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
723   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
724 
725   OS << "Frame Objects:\n";
726 
727   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
728     const StackObject &SO = Objects[i];
729     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
730     if (SO.Size == ~0ULL) {
731       OS << "dead\n";
732       continue;
733     }
734     if (SO.Size == 0)
735       OS << "variable sized";
736     else
737       OS << "size=" << SO.Size;
738     OS << ", align=" << SO.Alignment;
739 
740     if (i < NumFixedObjects)
741       OS << ", fixed";
742     if (i < NumFixedObjects || SO.SPOffset != -1) {
743       int64_t Off = SO.SPOffset - ValOffset;
744       OS << ", at location [SP";
745       if (Off > 0)
746         OS << "+" << Off;
747       else if (Off < 0)
748         OS << Off;
749       OS << "]";
750     }
751     OS << "\n";
752   }
753 }
754 
755 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
756 void MachineFrameInfo::dump(const MachineFunction &MF) const {
757   print(MF, dbgs());
758 }
759 #endif
760 
761 //===----------------------------------------------------------------------===//
762 //  MachineJumpTableInfo implementation
763 //===----------------------------------------------------------------------===//
764 
765 /// Return the size of each entry in the jump table.
766 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
767   // The size of a jump table entry is 4 bytes unless the entry is just the
768   // address of a block, in which case it is the pointer size.
769   switch (getEntryKind()) {
770   case MachineJumpTableInfo::EK_BlockAddress:
771     return TD.getPointerSize();
772   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
773     return 8;
774   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
775   case MachineJumpTableInfo::EK_LabelDifference32:
776   case MachineJumpTableInfo::EK_Custom32:
777     return 4;
778   case MachineJumpTableInfo::EK_Inline:
779     return 0;
780   }
781   llvm_unreachable("Unknown jump table encoding!");
782 }
783 
784 /// Return the alignment of each entry in the jump table.
785 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
786   // The alignment of a jump table entry is the alignment of int32 unless the
787   // entry is just the address of a block, in which case it is the pointer
788   // alignment.
789   switch (getEntryKind()) {
790   case MachineJumpTableInfo::EK_BlockAddress:
791     return TD.getPointerABIAlignment();
792   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
793     return TD.getABIIntegerTypeAlignment(64);
794   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
795   case MachineJumpTableInfo::EK_LabelDifference32:
796   case MachineJumpTableInfo::EK_Custom32:
797     return TD.getABIIntegerTypeAlignment(32);
798   case MachineJumpTableInfo::EK_Inline:
799     return 1;
800   }
801   llvm_unreachable("Unknown jump table encoding!");
802 }
803 
804 /// Create a new jump table entry in the jump table info.
805 unsigned MachineJumpTableInfo::createJumpTableIndex(
806                                const std::vector<MachineBasicBlock*> &DestBBs) {
807   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
808   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
809   return JumpTables.size()-1;
810 }
811 
812 /// If Old is the target of any jump tables, update the jump tables to branch
813 /// to New instead.
814 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
815                                                   MachineBasicBlock *New) {
816   assert(Old != New && "Not making a change?");
817   bool MadeChange = false;
818   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
819     ReplaceMBBInJumpTable(i, Old, New);
820   return MadeChange;
821 }
822 
823 /// If Old is a target of the jump tables, update the jump table to branch to
824 /// New instead.
825 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
826                                                  MachineBasicBlock *Old,
827                                                  MachineBasicBlock *New) {
828   assert(Old != New && "Not making a change?");
829   bool MadeChange = false;
830   MachineJumpTableEntry &JTE = JumpTables[Idx];
831   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
832     if (JTE.MBBs[j] == Old) {
833       JTE.MBBs[j] = New;
834       MadeChange = true;
835     }
836   return MadeChange;
837 }
838 
839 void MachineJumpTableInfo::print(raw_ostream &OS) const {
840   if (JumpTables.empty()) return;
841 
842   OS << "Jump Tables:\n";
843 
844   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
845     OS << "  jt#" << i << ": ";
846     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
847       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
848   }
849 
850   OS << '\n';
851 }
852 
853 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
854 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
855 #endif
856 
857 
858 //===----------------------------------------------------------------------===//
859 //  MachineConstantPool implementation
860 //===----------------------------------------------------------------------===//
861 
862 void MachineConstantPoolValue::anchor() { }
863 
864 Type *MachineConstantPoolEntry::getType() const {
865   if (isMachineConstantPoolEntry())
866     return Val.MachineCPVal->getType();
867   return Val.ConstVal->getType();
868 }
869 
870 bool MachineConstantPoolEntry::needsRelocation() const {
871   if (isMachineConstantPoolEntry())
872     return true;
873   return Val.ConstVal->needsRelocation();
874 }
875 
876 SectionKind
877 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
878   if (needsRelocation())
879     return SectionKind::getReadOnlyWithRel();
880   switch (DL->getTypeAllocSize(getType())) {
881   case 4:
882     return SectionKind::getMergeableConst4();
883   case 8:
884     return SectionKind::getMergeableConst8();
885   case 16:
886     return SectionKind::getMergeableConst16();
887   case 32:
888     return SectionKind::getMergeableConst32();
889   default:
890     return SectionKind::getReadOnly();
891   }
892 }
893 
894 MachineConstantPool::~MachineConstantPool() {
895   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
896     if (Constants[i].isMachineConstantPoolEntry())
897       delete Constants[i].Val.MachineCPVal;
898   for (DenseSet<MachineConstantPoolValue*>::iterator I =
899        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
900        I != E; ++I)
901     delete *I;
902 }
903 
904 /// Test whether the given two constants can be allocated the same constant pool
905 /// entry.
906 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
907                                       const DataLayout &DL) {
908   // Handle the trivial case quickly.
909   if (A == B) return true;
910 
911   // If they have the same type but weren't the same constant, quickly
912   // reject them.
913   if (A->getType() == B->getType()) return false;
914 
915   // We can't handle structs or arrays.
916   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
917       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
918     return false;
919 
920   // For now, only support constants with the same size.
921   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
922   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
923     return false;
924 
925   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
926 
927   // Try constant folding a bitcast of both instructions to an integer.  If we
928   // get two identical ConstantInt's, then we are good to share them.  We use
929   // the constant folding APIs to do this so that we get the benefit of
930   // DataLayout.
931   if (isa<PointerType>(A->getType()))
932     A = ConstantFoldCastOperand(Instruction::PtrToInt,
933                                 const_cast<Constant *>(A), IntTy, DL);
934   else if (A->getType() != IntTy)
935     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
936                                 IntTy, DL);
937   if (isa<PointerType>(B->getType()))
938     B = ConstantFoldCastOperand(Instruction::PtrToInt,
939                                 const_cast<Constant *>(B), IntTy, DL);
940   else if (B->getType() != IntTy)
941     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
942                                 IntTy, DL);
943 
944   return A == B;
945 }
946 
947 /// Create a new entry in the constant pool or return an existing one.
948 /// User must specify the log2 of the minimum required alignment for the object.
949 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
950                                                    unsigned Alignment) {
951   assert(Alignment && "Alignment must be specified!");
952   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
953 
954   // Check to see if we already have this constant.
955   //
956   // FIXME, this could be made much more efficient for large constant pools.
957   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
958     if (!Constants[i].isMachineConstantPoolEntry() &&
959         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
960       if ((unsigned)Constants[i].getAlignment() < Alignment)
961         Constants[i].Alignment = Alignment;
962       return i;
963     }
964 
965   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
966   return Constants.size()-1;
967 }
968 
969 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
970                                                    unsigned Alignment) {
971   assert(Alignment && "Alignment must be specified!");
972   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
973 
974   // Check to see if we already have this constant.
975   //
976   // FIXME, this could be made much more efficient for large constant pools.
977   int Idx = V->getExistingMachineCPValue(this, Alignment);
978   if (Idx != -1) {
979     MachineCPVsSharingEntries.insert(V);
980     return (unsigned)Idx;
981   }
982 
983   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
984   return Constants.size()-1;
985 }
986 
987 void MachineConstantPool::print(raw_ostream &OS) const {
988   if (Constants.empty()) return;
989 
990   OS << "Constant Pool:\n";
991   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
992     OS << "  cp#" << i << ": ";
993     if (Constants[i].isMachineConstantPoolEntry())
994       Constants[i].Val.MachineCPVal->print(OS);
995     else
996       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
997     OS << ", align=" << Constants[i].getAlignment();
998     OS << "\n";
999   }
1000 }
1001 
1002 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1003 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1004 #endif
1005