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