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