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