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