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