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