1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
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/CodeGen/PseudoSourceValue.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSlotTracker.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetFrameLowering.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
46 #define DEBUG_TYPE "codegen"
48 void MachineFunctionInitializer::anchor() {}
50 //===----------------------------------------------------------------------===//
51 // MachineFunction implementation
52 //===----------------------------------------------------------------------===//
54 // Out-of-line virtual method.
55 MachineFunctionInfo::~MachineFunctionInfo() {}
57 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
58 MBB->getParent()->DeleteMachineBasicBlock(MBB);
61 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
62 unsigned FunctionNum, MachineModuleInfo &mmi)
63 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
65 if (STI->getRegisterInfo())
66 RegInfo = new (Allocator) MachineRegisterInfo(this);
71 FrameInfo = new (Allocator)
72 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
73 STI->getFrameLowering()->isStackRealignable(),
74 !F->hasFnAttribute("no-realign-stack"));
76 if (Fn->hasFnAttribute(Attribute::StackAlignment))
77 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
79 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
80 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
82 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
83 // FIXME: Use Function::optForSize().
84 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
85 Alignment = std::max(Alignment,
86 STI->getTargetLowering()->getPrefFunctionAlignment());
88 FunctionNumber = FunctionNum;
89 JumpTableInfo = nullptr;
90 PSVManager = llvm::make_unique<PseudoSourceValueManager>();
93 MachineFunction::~MachineFunction() {
94 // Don't call destructors on MachineInstr and MachineOperand. All of their
95 // memory comes from the BumpPtrAllocator which is about to be purged.
97 // Do call MachineBasicBlock destructors, it contains std::vectors.
98 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
99 I->Insts.clearAndLeakNodesUnsafely();
101 InstructionRecycler.clear(Allocator);
102 OperandRecycler.clear(Allocator);
103 BasicBlockRecycler.clear(Allocator);
105 RegInfo->~MachineRegisterInfo();
106 Allocator.Deallocate(RegInfo);
109 MFInfo->~MachineFunctionInfo();
110 Allocator.Deallocate(MFInfo);
113 FrameInfo->~MachineFrameInfo();
114 Allocator.Deallocate(FrameInfo);
116 ConstantPool->~MachineConstantPool();
117 Allocator.Deallocate(ConstantPool);
120 JumpTableInfo->~MachineJumpTableInfo();
121 Allocator.Deallocate(JumpTableInfo);
125 const DataLayout &MachineFunction::getDataLayout() const {
126 return Fn->getParent()->getDataLayout();
129 /// Get the JumpTableInfo for this function.
130 /// If it does not already exist, allocate one.
131 MachineJumpTableInfo *MachineFunction::
132 getOrCreateJumpTableInfo(unsigned EntryKind) {
133 if (JumpTableInfo) return JumpTableInfo;
135 JumpTableInfo = new (Allocator)
136 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
137 return JumpTableInfo;
140 /// Should we be emitting segmented stack stuff for the function
141 bool MachineFunction::shouldSplitStack() {
142 return getFunction()->hasFnAttribute("split-stack");
145 /// This discards all of the MachineBasicBlock numbers and recomputes them.
146 /// This guarantees that the MBB numbers are sequential, dense, and match the
147 /// ordering of the blocks within the function. If a specific MachineBasicBlock
148 /// is specified, only that block and those after it are renumbered.
149 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
150 if (empty()) { MBBNumbering.clear(); return; }
151 MachineFunction::iterator MBBI, E = end();
157 // Figure out the block number this should have.
158 unsigned BlockNo = 0;
160 BlockNo = std::prev(MBBI)->getNumber() + 1;
162 for (; MBBI != E; ++MBBI, ++BlockNo) {
163 if (MBBI->getNumber() != (int)BlockNo) {
164 // Remove use of the old number.
165 if (MBBI->getNumber() != -1) {
166 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
167 "MBB number mismatch!");
168 MBBNumbering[MBBI->getNumber()] = nullptr;
171 // If BlockNo is already taken, set that block's number to -1.
172 if (MBBNumbering[BlockNo])
173 MBBNumbering[BlockNo]->setNumber(-1);
175 MBBNumbering[BlockNo] = MBBI;
176 MBBI->setNumber(BlockNo);
180 // Okay, all the blocks are renumbered. If we have compactified the block
181 // numbering, shrink MBBNumbering now.
182 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
183 MBBNumbering.resize(BlockNo);
186 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
188 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
189 DebugLoc DL, bool NoImp) {
190 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
191 MachineInstr(*this, MCID, DL, NoImp);
194 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
195 /// identical in all ways except the instruction has no parent, prev, or next.
197 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
198 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
199 MachineInstr(*this, *Orig);
202 /// Delete the given MachineInstr.
204 /// This function also serves as the MachineInstr destructor - the real
205 /// ~MachineInstr() destructor must be empty.
207 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
208 // Strip it for parts. The operand array and the MI object itself are
209 // independently recyclable.
211 deallocateOperandArray(MI->CapOperands, MI->Operands);
212 // Don't call ~MachineInstr() which must be trivial anyway because
213 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
215 InstructionRecycler.Deallocate(Allocator, MI);
218 /// Allocate a new MachineBasicBlock. Use this instead of
219 /// `new MachineBasicBlock'.
221 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
222 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
223 MachineBasicBlock(*this, bb);
226 /// Delete the given MachineBasicBlock.
228 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
229 assert(MBB->getParent() == this && "MBB parent mismatch!");
230 MBB->~MachineBasicBlock();
231 BasicBlockRecycler.Deallocate(Allocator, MBB);
235 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
236 uint64_t s, unsigned base_alignment,
237 const AAMDNodes &AAInfo,
238 const MDNode *Ranges) {
239 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
244 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
245 int64_t Offset, uint64_t Size) {
247 return new (Allocator)
248 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
249 MMO->getOffset()+Offset),
250 MMO->getFlags(), Size,
251 MMO->getBaseAlignment());
252 return new (Allocator)
253 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
254 MMO->getOffset()+Offset),
255 MMO->getFlags(), Size,
256 MMO->getBaseAlignment());
259 MachineInstr::mmo_iterator
260 MachineFunction::allocateMemRefsArray(unsigned long Num) {
261 return Allocator.Allocate<MachineMemOperand *>(Num);
264 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
265 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
266 MachineInstr::mmo_iterator End) {
267 // Count the number of load mem refs.
269 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
273 // Allocate a new array and populate it with the load information.
274 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
276 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
277 if ((*I)->isLoad()) {
278 if (!(*I)->isStore())
282 // Clone the MMO and unset the store flag.
283 MachineMemOperand *JustLoad =
284 getMachineMemOperand((*I)->getPointerInfo(),
285 (*I)->getFlags() & ~MachineMemOperand::MOStore,
286 (*I)->getSize(), (*I)->getBaseAlignment(),
288 Result[Index] = JustLoad;
293 return std::make_pair(Result, Result + Num);
296 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
297 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
298 MachineInstr::mmo_iterator End) {
299 // Count the number of load mem refs.
301 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
305 // Allocate a new array and populate it with the store information.
306 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
308 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
309 if ((*I)->isStore()) {
314 // Clone the MMO and unset the load flag.
315 MachineMemOperand *JustStore =
316 getMachineMemOperand((*I)->getPointerInfo(),
317 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
318 (*I)->getSize(), (*I)->getBaseAlignment(),
320 Result[Index] = JustStore;
325 return std::make_pair(Result, Result + Num);
328 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
329 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
330 std::copy(Name.begin(), Name.end(), Dest);
331 Dest[Name.size()] = 0;
335 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
336 void MachineFunction::dump() const {
341 StringRef MachineFunction::getName() const {
342 assert(getFunction() && "No function!");
343 return getFunction()->getName();
346 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
347 OS << "# Machine code for function " << getName() << ": ";
349 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
350 if (!RegInfo->tracksLiveness())
351 OS << ", not tracking liveness";
355 // Print Frame Information
356 FrameInfo->print(*this, OS);
358 // Print JumpTable Information
360 JumpTableInfo->print(OS);
362 // Print Constant Pool
363 ConstantPool->print(OS);
365 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
367 if (RegInfo && !RegInfo->livein_empty()) {
368 OS << "Function Live Ins: ";
369 for (MachineRegisterInfo::livein_iterator
370 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
371 OS << PrintReg(I->first, TRI);
373 OS << " in " << PrintReg(I->second, TRI);
374 if (std::next(I) != E)
380 ModuleSlotTracker MST(getFunction()->getParent());
381 MST.incorporateFunction(*getFunction());
382 for (const auto &BB : *this) {
384 BB.print(OS, MST, Indexes);
387 OS << "\n# End machine code for function " << getName() << ".\n\n";
392 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
394 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
396 static std::string getGraphName(const MachineFunction *F) {
397 return ("CFG for '" + F->getName() + "' function").str();
400 std::string getNodeLabel(const MachineBasicBlock *Node,
401 const MachineFunction *Graph) {
404 raw_string_ostream OSS(OutStr);
407 OSS << "BB#" << Node->getNumber();
408 if (const BasicBlock *BB = Node->getBasicBlock())
409 OSS << ": " << BB->getName();
414 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
416 // Process string output to make it nicer...
417 for (unsigned i = 0; i != OutStr.length(); ++i)
418 if (OutStr[i] == '\n') { // Left justify
420 OutStr.insert(OutStr.begin()+i+1, 'l');
427 void MachineFunction::viewCFG() const
430 ViewGraph(this, "mf" + getName());
432 errs() << "MachineFunction::viewCFG is only available in debug builds on "
433 << "systems with Graphviz or gv!\n";
437 void MachineFunction::viewCFGOnly() const
440 ViewGraph(this, "mf" + getName(), true);
442 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
443 << "systems with Graphviz or gv!\n";
447 /// Add the specified physical register as a live-in value and
448 /// create a corresponding virtual register for it.
449 unsigned MachineFunction::addLiveIn(unsigned PReg,
450 const TargetRegisterClass *RC) {
451 MachineRegisterInfo &MRI = getRegInfo();
452 unsigned VReg = MRI.getLiveInVirtReg(PReg);
454 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
456 // A physical register can be added several times.
457 // Between two calls, the register class of the related virtual register
458 // may have been constrained to match some operation constraints.
459 // In that case, check that the current register class includes the
460 // physical register and is a sub class of the specified RC.
461 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
462 RC->hasSubClassEq(VRegRC))) &&
463 "Register class mismatch!");
466 VReg = MRI.createVirtualRegister(RC);
467 MRI.addLiveIn(PReg, VReg);
471 /// Return the MCSymbol for the specified non-empty jump table.
472 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
473 /// normal 'L' label is returned.
474 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
475 bool isLinkerPrivate) const {
476 const DataLayout &DL = getDataLayout();
477 assert(JumpTableInfo && "No jump tables");
478 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
480 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
481 : DL.getPrivateGlobalPrefix();
482 SmallString<60> Name;
483 raw_svector_ostream(Name)
484 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
485 return Ctx.getOrCreateSymbol(Name);
488 /// Return a function-local symbol to represent the PIC base.
489 MCSymbol *MachineFunction::getPICBaseSymbol() const {
490 const DataLayout &DL = getDataLayout();
491 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
492 Twine(getFunctionNumber()) + "$pb");
495 //===----------------------------------------------------------------------===//
496 // MachineFrameInfo implementation
497 //===----------------------------------------------------------------------===//
499 /// Make sure the function is at least Align bytes aligned.
500 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
501 if (!StackRealignable || !RealignOption)
502 assert(Align <= StackAlignment &&
503 "For targets without stack realignment, Align is out of limit!");
504 if (MaxAlignment < Align) MaxAlignment = Align;
507 /// Clamp the alignment if requested and emit a warning.
508 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
509 unsigned StackAlign) {
510 if (!ShouldClamp || Align <= StackAlign)
512 DEBUG(dbgs() << "Warning: requested alignment " << Align
513 << " exceeds the stack alignment " << StackAlign
514 << " when stack realignment is off" << '\n');
518 /// Create a new statically sized stack object, returning a nonnegative
519 /// identifier to represent it.
520 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
521 bool isSS, const AllocaInst *Alloca) {
522 assert(Size != 0 && "Cannot allocate zero size stack objects!");
523 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
524 Alignment, StackAlignment);
525 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
527 int Index = (int)Objects.size() - NumFixedObjects - 1;
528 assert(Index >= 0 && "Bad frame index!");
529 ensureMaxAlignment(Alignment);
533 /// Create a new statically sized stack object that represents a spill slot,
534 /// returning a nonnegative identifier to represent it.
535 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
536 unsigned Alignment) {
537 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
538 Alignment, StackAlignment);
539 CreateStackObject(Size, Alignment, true);
540 int Index = (int)Objects.size() - NumFixedObjects - 1;
541 ensureMaxAlignment(Alignment);
545 /// Notify the MachineFrameInfo object that a variable sized object has been
546 /// created. This must be created whenever a variable sized object is created,
547 /// whether or not the index returned is actually used.
548 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
549 const AllocaInst *Alloca) {
550 HasVarSizedObjects = true;
551 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
552 Alignment, StackAlignment);
553 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
554 ensureMaxAlignment(Alignment);
555 return (int)Objects.size()-NumFixedObjects-1;
558 /// Create a new object at a fixed location on the stack.
559 /// All fixed objects should be created before other objects are created for
560 /// efficiency. By default, fixed objects are immutable. This returns an
561 /// index with a negative value.
562 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
563 bool Immutable, bool isAliased) {
564 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
565 // The alignment of the frame index can be determined from its offset from
566 // the incoming frame position. If the frame object is at offset 32 and
567 // the stack is guaranteed to be 16-byte aligned, then we know that the
568 // object is 16-byte aligned.
569 unsigned Align = MinAlign(SPOffset, StackAlignment);
570 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
572 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
574 /*Alloca*/ nullptr, isAliased));
575 return -++NumFixedObjects;
578 /// Create a spill slot at a fixed location on the stack.
579 /// Returns an index with a negative value.
580 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
582 unsigned Align = MinAlign(SPOffset, StackAlignment);
583 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
585 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
589 /*isAliased*/ false));
590 return -++NumFixedObjects;
593 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
594 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
595 BitVector BV(TRI->getNumRegs());
597 // Before CSI is calculated, no registers are considered pristine. They can be
598 // freely used and PEI will make sure they are saved.
599 if (!isCalleeSavedInfoValid())
602 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
605 // Saved CSRs are not pristine.
606 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
607 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
608 E = CSI.end(); I != E; ++I)
609 BV.reset(I->getReg());
614 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
615 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
616 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
617 unsigned MaxAlign = getMaxAlignment();
620 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
621 // It really should be refactored to share code. Until then, changes
622 // should keep in mind that there's tight coupling between the two.
624 for (int i = getObjectIndexBegin(); i != 0; ++i) {
625 int FixedOff = -getObjectOffset(i);
626 if (FixedOff > Offset) Offset = FixedOff;
628 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
629 if (isDeadObjectIndex(i))
631 Offset += getObjectSize(i);
632 unsigned Align = getObjectAlignment(i);
633 // Adjust to alignment boundary
634 Offset = (Offset+Align-1)/Align*Align;
636 MaxAlign = std::max(Align, MaxAlign);
639 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
640 Offset += getMaxCallFrameSize();
642 // Round up the size to a multiple of the alignment. If the function has
643 // any calls or alloca's, align to the target's StackAlignment value to
644 // ensure that the callee's frame or the alloca data is suitably aligned;
645 // otherwise, for leaf functions, align to the TransientStackAlignment
648 if (adjustsStack() || hasVarSizedObjects() ||
649 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
650 StackAlign = TFI->getStackAlignment();
652 StackAlign = TFI->getTransientStackAlignment();
654 // If the frame pointer is eliminated, all frame offsets will be relative to
655 // SP not FP. Align to MaxAlign so this works.
656 StackAlign = std::max(StackAlign, MaxAlign);
657 unsigned AlignMask = StackAlign - 1;
658 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
660 return (unsigned)Offset;
663 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
664 if (Objects.empty()) return;
666 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
667 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
669 OS << "Frame Objects:\n";
671 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
672 const StackObject &SO = Objects[i];
673 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
674 if (SO.Size == ~0ULL) {
679 OS << "variable sized";
681 OS << "size=" << SO.Size;
682 OS << ", align=" << SO.Alignment;
684 if (i < NumFixedObjects)
686 if (i < NumFixedObjects || SO.SPOffset != -1) {
687 int64_t Off = SO.SPOffset - ValOffset;
688 OS << ", at location [SP";
699 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
700 void MachineFrameInfo::dump(const MachineFunction &MF) const {
705 //===----------------------------------------------------------------------===//
706 // MachineJumpTableInfo implementation
707 //===----------------------------------------------------------------------===//
709 /// Return the size of each entry in the jump table.
710 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
711 // The size of a jump table entry is 4 bytes unless the entry is just the
712 // address of a block, in which case it is the pointer size.
713 switch (getEntryKind()) {
714 case MachineJumpTableInfo::EK_BlockAddress:
715 return TD.getPointerSize();
716 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
718 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
719 case MachineJumpTableInfo::EK_LabelDifference32:
720 case MachineJumpTableInfo::EK_Custom32:
722 case MachineJumpTableInfo::EK_Inline:
725 llvm_unreachable("Unknown jump table encoding!");
728 /// Return the alignment of each entry in the jump table.
729 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
730 // The alignment of a jump table entry is the alignment of int32 unless the
731 // entry is just the address of a block, in which case it is the pointer
733 switch (getEntryKind()) {
734 case MachineJumpTableInfo::EK_BlockAddress:
735 return TD.getPointerABIAlignment();
736 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
737 return TD.getABIIntegerTypeAlignment(64);
738 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
739 case MachineJumpTableInfo::EK_LabelDifference32:
740 case MachineJumpTableInfo::EK_Custom32:
741 return TD.getABIIntegerTypeAlignment(32);
742 case MachineJumpTableInfo::EK_Inline:
745 llvm_unreachable("Unknown jump table encoding!");
748 /// Create a new jump table entry in the jump table info.
749 unsigned MachineJumpTableInfo::createJumpTableIndex(
750 const std::vector<MachineBasicBlock*> &DestBBs) {
751 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
752 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
753 return JumpTables.size()-1;
756 /// If Old is the target of any jump tables, update the jump tables to branch
758 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
759 MachineBasicBlock *New) {
760 assert(Old != New && "Not making a change?");
761 bool MadeChange = false;
762 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
763 ReplaceMBBInJumpTable(i, Old, New);
767 /// If Old is a target of the jump tables, update the jump table to branch to
769 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
770 MachineBasicBlock *Old,
771 MachineBasicBlock *New) {
772 assert(Old != New && "Not making a change?");
773 bool MadeChange = false;
774 MachineJumpTableEntry &JTE = JumpTables[Idx];
775 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
776 if (JTE.MBBs[j] == Old) {
783 void MachineJumpTableInfo::print(raw_ostream &OS) const {
784 if (JumpTables.empty()) return;
786 OS << "Jump Tables:\n";
788 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
789 OS << " jt#" << i << ": ";
790 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
791 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
797 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
798 void MachineJumpTableInfo::dump() const { print(dbgs()); }
802 //===----------------------------------------------------------------------===//
803 // MachineConstantPool implementation
804 //===----------------------------------------------------------------------===//
806 void MachineConstantPoolValue::anchor() { }
808 Type *MachineConstantPoolEntry::getType() const {
809 if (isMachineConstantPoolEntry())
810 return Val.MachineCPVal->getType();
811 return Val.ConstVal->getType();
815 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
816 if (isMachineConstantPoolEntry())
817 return Val.MachineCPVal->getRelocationInfo();
818 return Val.ConstVal->getRelocationInfo();
822 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
824 switch (getRelocationInfo()) {
826 llvm_unreachable("Unknown section kind");
827 case Constant::GlobalRelocations:
828 Kind = SectionKind::getReadOnlyWithRel();
830 case Constant::LocalRelocation:
831 Kind = SectionKind::getReadOnlyWithRelLocal();
833 case Constant::NoRelocation:
834 switch (DL->getTypeAllocSize(getType())) {
836 Kind = SectionKind::getMergeableConst4();
839 Kind = SectionKind::getMergeableConst8();
842 Kind = SectionKind::getMergeableConst16();
845 Kind = SectionKind::getReadOnly();
852 MachineConstantPool::~MachineConstantPool() {
853 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
854 if (Constants[i].isMachineConstantPoolEntry())
855 delete Constants[i].Val.MachineCPVal;
856 for (DenseSet<MachineConstantPoolValue*>::iterator I =
857 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
862 /// Test whether the given two constants can be allocated the same constant pool
864 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
865 const DataLayout &DL) {
866 // Handle the trivial case quickly.
867 if (A == B) return true;
869 // If they have the same type but weren't the same constant, quickly
871 if (A->getType() == B->getType()) return false;
873 // We can't handle structs or arrays.
874 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
875 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
878 // For now, only support constants with the same size.
879 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
880 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
883 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
885 // Try constant folding a bitcast of both instructions to an integer. If we
886 // get two identical ConstantInt's, then we are good to share them. We use
887 // the constant folding APIs to do this so that we get the benefit of
889 if (isa<PointerType>(A->getType()))
890 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
891 const_cast<Constant *>(A), DL);
892 else if (A->getType() != IntTy)
893 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
894 const_cast<Constant *>(A), DL);
895 if (isa<PointerType>(B->getType()))
896 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
897 const_cast<Constant *>(B), DL);
898 else if (B->getType() != IntTy)
899 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
900 const_cast<Constant *>(B), DL);
905 /// Create a new entry in the constant pool or return an existing one.
906 /// User must specify the log2 of the minimum required alignment for the object.
907 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
908 unsigned Alignment) {
909 assert(Alignment && "Alignment must be specified!");
910 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
912 // Check to see if we already have this constant.
914 // FIXME, this could be made much more efficient for large constant pools.
915 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
916 if (!Constants[i].isMachineConstantPoolEntry() &&
917 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
918 if ((unsigned)Constants[i].getAlignment() < Alignment)
919 Constants[i].Alignment = Alignment;
923 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
924 return Constants.size()-1;
927 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
928 unsigned Alignment) {
929 assert(Alignment && "Alignment must be specified!");
930 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
932 // Check to see if we already have this constant.
934 // FIXME, this could be made much more efficient for large constant pools.
935 int Idx = V->getExistingMachineCPValue(this, Alignment);
937 MachineCPVsSharingEntries.insert(V);
938 return (unsigned)Idx;
941 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
942 return Constants.size()-1;
945 void MachineConstantPool::print(raw_ostream &OS) const {
946 if (Constants.empty()) return;
948 OS << "Constant Pool:\n";
949 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
950 OS << " cp#" << i << ": ";
951 if (Constants[i].isMachineConstantPoolEntry())
952 Constants[i].Val.MachineCPVal->print(OS);
954 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
955 OS << ", align=" << Constants[i].getAlignment();
960 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
961 void MachineConstantPool::dump() const { print(dbgs()); }