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/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GraphWriter.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "codegen"
47 void MachineFunctionInitializer::anchor() {}
49 //===----------------------------------------------------------------------===//
50 // MachineFunction implementation
51 //===----------------------------------------------------------------------===//
53 // Out-of-line virtual method.
54 MachineFunctionInfo::~MachineFunctionInfo() {}
56 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
57 MBB->getParent()->DeleteMachineBasicBlock(MBB);
60 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
61 unsigned FunctionNum, MachineModuleInfo &mmi)
62 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
64 if (STI->getRegisterInfo())
65 RegInfo = new (Allocator) MachineRegisterInfo(this);
70 FrameInfo = new (Allocator)
71 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
72 STI->getFrameLowering()->isStackRealignable(),
73 !F->hasFnAttribute("no-realign-stack"));
75 if (Fn->hasFnAttribute(Attribute::StackAlignment))
76 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
78 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
79 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
81 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
82 // FIXME: Use Function::optForSize().
83 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
84 Alignment = std::max(Alignment,
85 STI->getTargetLowering()->getPrefFunctionAlignment());
87 FunctionNumber = FunctionNum;
88 JumpTableInfo = nullptr;
90 assert(TM.isCompatibleDataLayout(getDataLayout()) &&
91 "Can't create a MachineFunction using a Module with a "
92 "Target-incompatible DataLayout attached\n");
95 MachineFunction::~MachineFunction() {
96 // Don't call destructors on MachineInstr and MachineOperand. All of their
97 // memory comes from the BumpPtrAllocator which is about to be purged.
99 // Do call MachineBasicBlock destructors, it contains std::vectors.
100 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
101 I->Insts.clearAndLeakNodesUnsafely();
103 InstructionRecycler.clear(Allocator);
104 OperandRecycler.clear(Allocator);
105 BasicBlockRecycler.clear(Allocator);
107 RegInfo->~MachineRegisterInfo();
108 Allocator.Deallocate(RegInfo);
111 MFInfo->~MachineFunctionInfo();
112 Allocator.Deallocate(MFInfo);
115 FrameInfo->~MachineFrameInfo();
116 Allocator.Deallocate(FrameInfo);
118 ConstantPool->~MachineConstantPool();
119 Allocator.Deallocate(ConstantPool);
122 JumpTableInfo->~MachineJumpTableInfo();
123 Allocator.Deallocate(JumpTableInfo);
127 const DataLayout &MachineFunction::getDataLayout() const {
128 return Fn->getParent()->getDataLayout();
131 /// Get the JumpTableInfo for this function.
132 /// If it does not already exist, allocate one.
133 MachineJumpTableInfo *MachineFunction::
134 getOrCreateJumpTableInfo(unsigned EntryKind) {
135 if (JumpTableInfo) return JumpTableInfo;
137 JumpTableInfo = new (Allocator)
138 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
139 return JumpTableInfo;
142 /// Should we be emitting segmented stack stuff for the function
143 bool MachineFunction::shouldSplitStack() {
144 return getFunction()->hasFnAttribute("split-stack");
147 /// This discards all of the MachineBasicBlock numbers and recomputes them.
148 /// This guarantees that the MBB numbers are sequential, dense, and match the
149 /// ordering of the blocks within the function. If a specific MachineBasicBlock
150 /// is specified, only that block and those after it are renumbered.
151 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
152 if (empty()) { MBBNumbering.clear(); return; }
153 MachineFunction::iterator MBBI, E = end();
159 // Figure out the block number this should have.
160 unsigned BlockNo = 0;
162 BlockNo = std::prev(MBBI)->getNumber() + 1;
164 for (; MBBI != E; ++MBBI, ++BlockNo) {
165 if (MBBI->getNumber() != (int)BlockNo) {
166 // Remove use of the old number.
167 if (MBBI->getNumber() != -1) {
168 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
169 "MBB number mismatch!");
170 MBBNumbering[MBBI->getNumber()] = nullptr;
173 // If BlockNo is already taken, set that block's number to -1.
174 if (MBBNumbering[BlockNo])
175 MBBNumbering[BlockNo]->setNumber(-1);
177 MBBNumbering[BlockNo] = MBBI;
178 MBBI->setNumber(BlockNo);
182 // Okay, all the blocks are renumbered. If we have compactified the block
183 // numbering, shrink MBBNumbering now.
184 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
185 MBBNumbering.resize(BlockNo);
188 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
190 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
191 DebugLoc DL, bool NoImp) {
192 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
193 MachineInstr(*this, MCID, DL, NoImp);
196 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
197 /// identical in all ways except the instruction has no parent, prev, or next.
199 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
200 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
201 MachineInstr(*this, *Orig);
204 /// Delete the given MachineInstr.
206 /// This function also serves as the MachineInstr destructor - the real
207 /// ~MachineInstr() destructor must be empty.
209 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
210 // Strip it for parts. The operand array and the MI object itself are
211 // independently recyclable.
213 deallocateOperandArray(MI->CapOperands, MI->Operands);
214 // Don't call ~MachineInstr() which must be trivial anyway because
215 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
217 InstructionRecycler.Deallocate(Allocator, MI);
220 /// Allocate a new MachineBasicBlock. Use this instead of
221 /// `new MachineBasicBlock'.
223 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
224 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
225 MachineBasicBlock(*this, bb);
228 /// Delete the given MachineBasicBlock.
230 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
231 assert(MBB->getParent() == this && "MBB parent mismatch!");
232 MBB->~MachineBasicBlock();
233 BasicBlockRecycler.Deallocate(Allocator, MBB);
237 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
238 uint64_t s, unsigned base_alignment,
239 const AAMDNodes &AAInfo,
240 const MDNode *Ranges) {
241 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
246 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
247 int64_t Offset, uint64_t Size) {
249 return new (Allocator)
250 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
251 MMO->getOffset()+Offset),
252 MMO->getFlags(), Size,
253 MMO->getBaseAlignment());
254 return new (Allocator)
255 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
256 MMO->getOffset()+Offset),
257 MMO->getFlags(), Size,
258 MMO->getBaseAlignment());
261 MachineInstr::mmo_iterator
262 MachineFunction::allocateMemRefsArray(unsigned long Num) {
263 return Allocator.Allocate<MachineMemOperand *>(Num);
266 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
267 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
268 MachineInstr::mmo_iterator End) {
269 // Count the number of load mem refs.
271 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
275 // Allocate a new array and populate it with the load information.
276 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
278 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
279 if ((*I)->isLoad()) {
280 if (!(*I)->isStore())
284 // Clone the MMO and unset the store flag.
285 MachineMemOperand *JustLoad =
286 getMachineMemOperand((*I)->getPointerInfo(),
287 (*I)->getFlags() & ~MachineMemOperand::MOStore,
288 (*I)->getSize(), (*I)->getBaseAlignment(),
290 Result[Index] = JustLoad;
295 return std::make_pair(Result, Result + Num);
298 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
299 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
300 MachineInstr::mmo_iterator End) {
301 // Count the number of load mem refs.
303 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
307 // Allocate a new array and populate it with the store information.
308 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
310 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
311 if ((*I)->isStore()) {
316 // Clone the MMO and unset the load flag.
317 MachineMemOperand *JustStore =
318 getMachineMemOperand((*I)->getPointerInfo(),
319 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
320 (*I)->getSize(), (*I)->getBaseAlignment(),
322 Result[Index] = JustStore;
327 return std::make_pair(Result, Result + Num);
330 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
331 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
332 std::copy(Name.begin(), Name.end(), Dest);
333 Dest[Name.size()] = 0;
337 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
338 void MachineFunction::dump() const {
343 StringRef MachineFunction::getName() const {
344 assert(getFunction() && "No function!");
345 return getFunction()->getName();
348 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
349 OS << "# Machine code for function " << getName() << ": ";
351 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
352 if (!RegInfo->tracksLiveness())
353 OS << ", not tracking liveness";
357 // Print Frame Information
358 FrameInfo->print(*this, OS);
360 // Print JumpTable Information
362 JumpTableInfo->print(OS);
364 // Print Constant Pool
365 ConstantPool->print(OS);
367 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
369 if (RegInfo && !RegInfo->livein_empty()) {
370 OS << "Function Live Ins: ";
371 for (MachineRegisterInfo::livein_iterator
372 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
373 OS << PrintReg(I->first, TRI);
375 OS << " in " << PrintReg(I->second, TRI);
376 if (std::next(I) != E)
382 ModuleSlotTracker MST(getFunction()->getParent());
383 MST.incorporateFunction(*getFunction());
384 for (const auto &BB : *this) {
386 BB.print(OS, MST, Indexes);
389 OS << "\n# End machine code for function " << getName() << ".\n\n";
394 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
396 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
398 static std::string getGraphName(const MachineFunction *F) {
399 return ("CFG for '" + F->getName() + "' function").str();
402 std::string getNodeLabel(const MachineBasicBlock *Node,
403 const MachineFunction *Graph) {
406 raw_string_ostream OSS(OutStr);
409 OSS << "BB#" << Node->getNumber();
410 if (const BasicBlock *BB = Node->getBasicBlock())
411 OSS << ": " << BB->getName();
416 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
418 // Process string output to make it nicer...
419 for (unsigned i = 0; i != OutStr.length(); ++i)
420 if (OutStr[i] == '\n') { // Left justify
422 OutStr.insert(OutStr.begin()+i+1, 'l');
429 void MachineFunction::viewCFG() const
432 ViewGraph(this, "mf" + getName());
434 errs() << "MachineFunction::viewCFG is only available in debug builds on "
435 << "systems with Graphviz or gv!\n";
439 void MachineFunction::viewCFGOnly() const
442 ViewGraph(this, "mf" + getName(), true);
444 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
445 << "systems with Graphviz or gv!\n";
449 /// Add the specified physical register as a live-in value and
450 /// create a corresponding virtual register for it.
451 unsigned MachineFunction::addLiveIn(unsigned PReg,
452 const TargetRegisterClass *RC) {
453 MachineRegisterInfo &MRI = getRegInfo();
454 unsigned VReg = MRI.getLiveInVirtReg(PReg);
456 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
458 // A physical register can be added several times.
459 // Between two calls, the register class of the related virtual register
460 // may have been constrained to match some operation constraints.
461 // In that case, check that the current register class includes the
462 // physical register and is a sub class of the specified RC.
463 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
464 RC->hasSubClassEq(VRegRC))) &&
465 "Register class mismatch!");
468 VReg = MRI.createVirtualRegister(RC);
469 MRI.addLiveIn(PReg, VReg);
473 /// Return the MCSymbol for the specified non-empty jump table.
474 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
475 /// normal 'L' label is returned.
476 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
477 bool isLinkerPrivate) const {
478 const DataLayout &DL = getDataLayout();
479 assert(JumpTableInfo && "No jump tables");
480 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
482 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
483 : DL.getPrivateGlobalPrefix();
484 SmallString<60> Name;
485 raw_svector_ostream(Name)
486 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
487 return Ctx.getOrCreateSymbol(Name);
490 /// Return a function-local symbol to represent the PIC base.
491 MCSymbol *MachineFunction::getPICBaseSymbol() const {
492 const DataLayout &DL = getDataLayout();
493 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
494 Twine(getFunctionNumber()) + "$pb");
497 //===----------------------------------------------------------------------===//
498 // MachineFrameInfo implementation
499 //===----------------------------------------------------------------------===//
501 /// Make sure the function is at least Align bytes aligned.
502 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
503 if (!StackRealignable || !RealignOption)
504 assert(Align <= StackAlignment &&
505 "For targets without stack realignment, Align is out of limit!");
506 if (MaxAlignment < Align) MaxAlignment = Align;
509 /// Clamp the alignment if requested and emit a warning.
510 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
511 unsigned StackAlign) {
512 if (!ShouldClamp || Align <= StackAlign)
514 DEBUG(dbgs() << "Warning: requested alignment " << Align
515 << " exceeds the stack alignment " << StackAlign
516 << " when stack realignment is off" << '\n');
520 /// Create a new statically sized stack object, returning a nonnegative
521 /// identifier to represent it.
522 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
523 bool isSS, const AllocaInst *Alloca) {
524 assert(Size != 0 && "Cannot allocate zero size stack objects!");
525 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
526 Alignment, StackAlignment);
527 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
529 int Index = (int)Objects.size() - NumFixedObjects - 1;
530 assert(Index >= 0 && "Bad frame index!");
531 ensureMaxAlignment(Alignment);
535 /// Create a new statically sized stack object that represents a spill slot,
536 /// returning a nonnegative identifier to represent it.
537 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
538 unsigned Alignment) {
539 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
540 Alignment, StackAlignment);
541 CreateStackObject(Size, Alignment, true);
542 int Index = (int)Objects.size() - NumFixedObjects - 1;
543 ensureMaxAlignment(Alignment);
547 /// Notify the MachineFrameInfo object that a variable sized object has been
548 /// created. This must be created whenever a variable sized object is created,
549 /// whether or not the index returned is actually used.
550 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
551 const AllocaInst *Alloca) {
552 HasVarSizedObjects = true;
553 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
554 Alignment, StackAlignment);
555 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
556 ensureMaxAlignment(Alignment);
557 return (int)Objects.size()-NumFixedObjects-1;
560 /// Create a new object at a fixed location on the stack.
561 /// All fixed objects should be created before other objects are created for
562 /// efficiency. By default, fixed objects are immutable. This returns an
563 /// index with a negative value.
564 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
565 bool Immutable, bool isAliased) {
566 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
567 // The alignment of the frame index can be determined from its offset from
568 // the incoming frame position. If the frame object is at offset 32 and
569 // the stack is guaranteed to be 16-byte aligned, then we know that the
570 // object is 16-byte aligned.
571 unsigned Align = MinAlign(SPOffset, StackAlignment);
572 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
574 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
576 /*Alloca*/ nullptr, isAliased));
577 return -++NumFixedObjects;
580 /// Create a spill slot at a fixed location on the stack.
581 /// Returns an index with a negative value.
582 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
584 unsigned Align = MinAlign(SPOffset, StackAlignment);
585 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
587 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
591 /*isAliased*/ false));
592 return -++NumFixedObjects;
595 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
596 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
597 BitVector BV(TRI->getNumRegs());
599 // Before CSI is calculated, no registers are considered pristine. They can be
600 // freely used and PEI will make sure they are saved.
601 if (!isCalleeSavedInfoValid())
604 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
607 // Saved CSRs are not pristine.
608 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
609 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
610 E = CSI.end(); I != E; ++I)
611 BV.reset(I->getReg());
616 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
617 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
618 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
619 unsigned MaxAlign = getMaxAlignment();
622 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
623 // It really should be refactored to share code. Until then, changes
624 // should keep in mind that there's tight coupling between the two.
626 for (int i = getObjectIndexBegin(); i != 0; ++i) {
627 int FixedOff = -getObjectOffset(i);
628 if (FixedOff > Offset) Offset = FixedOff;
630 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
631 if (isDeadObjectIndex(i))
633 Offset += getObjectSize(i);
634 unsigned Align = getObjectAlignment(i);
635 // Adjust to alignment boundary
636 Offset = (Offset+Align-1)/Align*Align;
638 MaxAlign = std::max(Align, MaxAlign);
641 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
642 Offset += getMaxCallFrameSize();
644 // Round up the size to a multiple of the alignment. If the function has
645 // any calls or alloca's, align to the target's StackAlignment value to
646 // ensure that the callee's frame or the alloca data is suitably aligned;
647 // otherwise, for leaf functions, align to the TransientStackAlignment
650 if (adjustsStack() || hasVarSizedObjects() ||
651 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
652 StackAlign = TFI->getStackAlignment();
654 StackAlign = TFI->getTransientStackAlignment();
656 // If the frame pointer is eliminated, all frame offsets will be relative to
657 // SP not FP. Align to MaxAlign so this works.
658 StackAlign = std::max(StackAlign, MaxAlign);
659 unsigned AlignMask = StackAlign - 1;
660 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
662 return (unsigned)Offset;
665 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
666 if (Objects.empty()) return;
668 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
669 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
671 OS << "Frame Objects:\n";
673 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
674 const StackObject &SO = Objects[i];
675 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
676 if (SO.Size == ~0ULL) {
681 OS << "variable sized";
683 OS << "size=" << SO.Size;
684 OS << ", align=" << SO.Alignment;
686 if (i < NumFixedObjects)
688 if (i < NumFixedObjects || SO.SPOffset != -1) {
689 int64_t Off = SO.SPOffset - ValOffset;
690 OS << ", at location [SP";
701 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
702 void MachineFrameInfo::dump(const MachineFunction &MF) const {
707 //===----------------------------------------------------------------------===//
708 // MachineJumpTableInfo implementation
709 //===----------------------------------------------------------------------===//
711 /// Return the size of each entry in the jump table.
712 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
713 // The size of a jump table entry is 4 bytes unless the entry is just the
714 // address of a block, in which case it is the pointer size.
715 switch (getEntryKind()) {
716 case MachineJumpTableInfo::EK_BlockAddress:
717 return TD.getPointerSize();
718 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
720 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
721 case MachineJumpTableInfo::EK_LabelDifference32:
722 case MachineJumpTableInfo::EK_Custom32:
724 case MachineJumpTableInfo::EK_Inline:
727 llvm_unreachable("Unknown jump table encoding!");
730 /// Return the alignment of each entry in the jump table.
731 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
732 // The alignment of a jump table entry is the alignment of int32 unless the
733 // entry is just the address of a block, in which case it is the pointer
735 switch (getEntryKind()) {
736 case MachineJumpTableInfo::EK_BlockAddress:
737 return TD.getPointerABIAlignment();
738 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
739 return TD.getABIIntegerTypeAlignment(64);
740 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
741 case MachineJumpTableInfo::EK_LabelDifference32:
742 case MachineJumpTableInfo::EK_Custom32:
743 return TD.getABIIntegerTypeAlignment(32);
744 case MachineJumpTableInfo::EK_Inline:
747 llvm_unreachable("Unknown jump table encoding!");
750 /// Create a new jump table entry in the jump table info.
751 unsigned MachineJumpTableInfo::createJumpTableIndex(
752 const std::vector<MachineBasicBlock*> &DestBBs) {
753 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
754 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
755 return JumpTables.size()-1;
758 /// If Old is the target of any jump tables, update the jump tables to branch
760 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
761 MachineBasicBlock *New) {
762 assert(Old != New && "Not making a change?");
763 bool MadeChange = false;
764 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
765 ReplaceMBBInJumpTable(i, Old, New);
769 /// If Old is a target of the jump tables, update the jump table to branch to
771 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
772 MachineBasicBlock *Old,
773 MachineBasicBlock *New) {
774 assert(Old != New && "Not making a change?");
775 bool MadeChange = false;
776 MachineJumpTableEntry &JTE = JumpTables[Idx];
777 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
778 if (JTE.MBBs[j] == Old) {
785 void MachineJumpTableInfo::print(raw_ostream &OS) const {
786 if (JumpTables.empty()) return;
788 OS << "Jump Tables:\n";
790 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
791 OS << " jt#" << i << ": ";
792 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
793 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
799 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
800 void MachineJumpTableInfo::dump() const { print(dbgs()); }
804 //===----------------------------------------------------------------------===//
805 // MachineConstantPool implementation
806 //===----------------------------------------------------------------------===//
808 void MachineConstantPoolValue::anchor() { }
810 Type *MachineConstantPoolEntry::getType() const {
811 if (isMachineConstantPoolEntry())
812 return Val.MachineCPVal->getType();
813 return Val.ConstVal->getType();
817 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
818 if (isMachineConstantPoolEntry())
819 return Val.MachineCPVal->getRelocationInfo();
820 return Val.ConstVal->getRelocationInfo();
824 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
826 switch (getRelocationInfo()) {
828 llvm_unreachable("Unknown section kind");
829 case Constant::GlobalRelocations:
830 Kind = SectionKind::getReadOnlyWithRel();
832 case Constant::LocalRelocation:
833 Kind = SectionKind::getReadOnlyWithRelLocal();
835 case Constant::NoRelocation:
836 switch (DL->getTypeAllocSize(getType())) {
838 Kind = SectionKind::getMergeableConst4();
841 Kind = SectionKind::getMergeableConst8();
844 Kind = SectionKind::getMergeableConst16();
847 Kind = SectionKind::getReadOnly();
854 MachineConstantPool::~MachineConstantPool() {
855 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
856 if (Constants[i].isMachineConstantPoolEntry())
857 delete Constants[i].Val.MachineCPVal;
858 for (DenseSet<MachineConstantPoolValue*>::iterator I =
859 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
864 /// Test whether the given two constants can be allocated the same constant pool
866 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
867 const DataLayout &DL) {
868 // Handle the trivial case quickly.
869 if (A == B) return true;
871 // If they have the same type but weren't the same constant, quickly
873 if (A->getType() == B->getType()) return false;
875 // We can't handle structs or arrays.
876 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
877 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
880 // For now, only support constants with the same size.
881 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
882 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
885 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
887 // Try constant folding a bitcast of both instructions to an integer. If we
888 // get two identical ConstantInt's, then we are good to share them. We use
889 // the constant folding APIs to do this so that we get the benefit of
891 if (isa<PointerType>(A->getType()))
892 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
893 const_cast<Constant *>(A), DL);
894 else if (A->getType() != IntTy)
895 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
896 const_cast<Constant *>(A), DL);
897 if (isa<PointerType>(B->getType()))
898 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
899 const_cast<Constant *>(B), DL);
900 else if (B->getType() != IntTy)
901 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
902 const_cast<Constant *>(B), DL);
907 /// Create a new entry in the constant pool or return an existing one.
908 /// User must specify the log2 of the minimum required alignment for the object.
909 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
910 unsigned Alignment) {
911 assert(Alignment && "Alignment must be specified!");
912 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
914 // Check to see if we already have this constant.
916 // FIXME, this could be made much more efficient for large constant pools.
917 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
918 if (!Constants[i].isMachineConstantPoolEntry() &&
919 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
920 if ((unsigned)Constants[i].getAlignment() < Alignment)
921 Constants[i].Alignment = Alignment;
925 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
926 return Constants.size()-1;
929 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
930 unsigned Alignment) {
931 assert(Alignment && "Alignment must be specified!");
932 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
934 // Check to see if we already have this constant.
936 // FIXME, this could be made much more efficient for large constant pools.
937 int Idx = V->getExistingMachineCPValue(this, Alignment);
939 MachineCPVsSharingEntries.insert(V);
940 return (unsigned)Idx;
943 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
944 return Constants.size()-1;
947 void MachineConstantPool::print(raw_ostream &OS) const {
948 if (Constants.empty()) return;
950 OS << "Constant Pool:\n";
951 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
952 OS << " cp#" << i << ": ";
953 if (Constants[i].isMachineConstantPoolEntry())
954 Constants[i].Val.MachineCPVal->print(OS);
956 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
957 OS << ", align=" << Constants[i].getAlignment();
962 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
963 void MachineConstantPool::dump() const { print(dbgs()); }