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 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
83 Alignment = std::max(Alignment,
84 STI->getTargetLowering()->getPrefFunctionAlignment());
86 FunctionNumber = FunctionNum;
87 JumpTableInfo = nullptr;
89 assert(TM.isCompatibleDataLayout(getDataLayout()) &&
90 "Can't create a MachineFunction using a Module with a "
91 "Target-incompatible DataLayout attached\n");
94 MachineFunction::~MachineFunction() {
95 // Don't call destructors on MachineInstr and MachineOperand. All of their
96 // memory comes from the BumpPtrAllocator which is about to be purged.
98 // Do call MachineBasicBlock destructors, it contains std::vectors.
99 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
100 I->Insts.clearAndLeakNodesUnsafely();
102 InstructionRecycler.clear(Allocator);
103 OperandRecycler.clear(Allocator);
104 BasicBlockRecycler.clear(Allocator);
106 RegInfo->~MachineRegisterInfo();
107 Allocator.Deallocate(RegInfo);
110 MFInfo->~MachineFunctionInfo();
111 Allocator.Deallocate(MFInfo);
114 FrameInfo->~MachineFrameInfo();
115 Allocator.Deallocate(FrameInfo);
117 ConstantPool->~MachineConstantPool();
118 Allocator.Deallocate(ConstantPool);
121 JumpTableInfo->~MachineJumpTableInfo();
122 Allocator.Deallocate(JumpTableInfo);
126 const DataLayout &MachineFunction::getDataLayout() const {
127 return Fn->getParent()->getDataLayout();
130 /// Get the JumpTableInfo for this function.
131 /// If it does not already exist, allocate one.
132 MachineJumpTableInfo *MachineFunction::
133 getOrCreateJumpTableInfo(unsigned EntryKind) {
134 if (JumpTableInfo) return JumpTableInfo;
136 JumpTableInfo = new (Allocator)
137 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
138 return JumpTableInfo;
141 /// Should we be emitting segmented stack stuff for the function
142 bool MachineFunction::shouldSplitStack() {
143 return getFunction()->hasFnAttribute("split-stack");
146 /// This discards all of the MachineBasicBlock numbers and recomputes them.
147 /// This guarantees that the MBB numbers are sequential, dense, and match the
148 /// ordering of the blocks within the function. If a specific MachineBasicBlock
149 /// is specified, only that block and those after it are renumbered.
150 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
151 if (empty()) { MBBNumbering.clear(); return; }
152 MachineFunction::iterator MBBI, E = end();
158 // Figure out the block number this should have.
159 unsigned BlockNo = 0;
161 BlockNo = std::prev(MBBI)->getNumber() + 1;
163 for (; MBBI != E; ++MBBI, ++BlockNo) {
164 if (MBBI->getNumber() != (int)BlockNo) {
165 // Remove use of the old number.
166 if (MBBI->getNumber() != -1) {
167 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
168 "MBB number mismatch!");
169 MBBNumbering[MBBI->getNumber()] = nullptr;
172 // If BlockNo is already taken, set that block's number to -1.
173 if (MBBNumbering[BlockNo])
174 MBBNumbering[BlockNo]->setNumber(-1);
176 MBBNumbering[BlockNo] = MBBI;
177 MBBI->setNumber(BlockNo);
181 // Okay, all the blocks are renumbered. If we have compactified the block
182 // numbering, shrink MBBNumbering now.
183 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
184 MBBNumbering.resize(BlockNo);
187 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
189 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
190 DebugLoc DL, bool NoImp) {
191 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
192 MachineInstr(*this, MCID, DL, NoImp);
195 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
196 /// identical in all ways except the instruction has no parent, prev, or next.
198 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
199 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
200 MachineInstr(*this, *Orig);
203 /// Delete the given MachineInstr.
205 /// This function also serves as the MachineInstr destructor - the real
206 /// ~MachineInstr() destructor must be empty.
208 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
209 // Strip it for parts. The operand array and the MI object itself are
210 // independently recyclable.
212 deallocateOperandArray(MI->CapOperands, MI->Operands);
213 // Don't call ~MachineInstr() which must be trivial anyway because
214 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
216 InstructionRecycler.Deallocate(Allocator, MI);
219 /// Allocate a new MachineBasicBlock. Use this instead of
220 /// `new MachineBasicBlock'.
222 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
223 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
224 MachineBasicBlock(*this, bb);
227 /// Delete the given MachineBasicBlock.
229 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
230 assert(MBB->getParent() == this && "MBB parent mismatch!");
231 MBB->~MachineBasicBlock();
232 BasicBlockRecycler.Deallocate(Allocator, MBB);
236 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
237 uint64_t s, unsigned base_alignment,
238 const AAMDNodes &AAInfo,
239 const MDNode *Ranges) {
240 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
245 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
246 int64_t Offset, uint64_t Size) {
248 return new (Allocator)
249 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
250 MMO->getOffset()+Offset),
251 MMO->getFlags(), Size,
252 MMO->getBaseAlignment());
253 return new (Allocator)
254 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
255 MMO->getOffset()+Offset),
256 MMO->getFlags(), Size,
257 MMO->getBaseAlignment());
260 MachineInstr::mmo_iterator
261 MachineFunction::allocateMemRefsArray(unsigned long Num) {
262 return Allocator.Allocate<MachineMemOperand *>(Num);
265 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
266 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
267 MachineInstr::mmo_iterator End) {
268 // Count the number of load mem refs.
270 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
274 // Allocate a new array and populate it with the load information.
275 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
277 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
278 if ((*I)->isLoad()) {
279 if (!(*I)->isStore())
283 // Clone the MMO and unset the store flag.
284 MachineMemOperand *JustLoad =
285 getMachineMemOperand((*I)->getPointerInfo(),
286 (*I)->getFlags() & ~MachineMemOperand::MOStore,
287 (*I)->getSize(), (*I)->getBaseAlignment(),
289 Result[Index] = JustLoad;
294 return std::make_pair(Result, Result + Num);
297 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
298 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
299 MachineInstr::mmo_iterator End) {
300 // Count the number of load mem refs.
302 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
306 // Allocate a new array and populate it with the store information.
307 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
309 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
310 if ((*I)->isStore()) {
315 // Clone the MMO and unset the load flag.
316 MachineMemOperand *JustStore =
317 getMachineMemOperand((*I)->getPointerInfo(),
318 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
319 (*I)->getSize(), (*I)->getBaseAlignment(),
321 Result[Index] = JustStore;
326 return std::make_pair(Result, Result + Num);
329 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
330 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
331 std::copy(Name.begin(), Name.end(), Dest);
332 Dest[Name.size()] = 0;
336 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
337 void MachineFunction::dump() const {
342 StringRef MachineFunction::getName() const {
343 assert(getFunction() && "No function!");
344 return getFunction()->getName();
347 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
348 OS << "# Machine code for function " << getName() << ": ";
350 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
351 if (!RegInfo->tracksLiveness())
352 OS << ", not tracking liveness";
356 // Print Frame Information
357 FrameInfo->print(*this, OS);
359 // Print JumpTable Information
361 JumpTableInfo->print(OS);
363 // Print Constant Pool
364 ConstantPool->print(OS);
366 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
368 if (RegInfo && !RegInfo->livein_empty()) {
369 OS << "Function Live Ins: ";
370 for (MachineRegisterInfo::livein_iterator
371 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
372 OS << PrintReg(I->first, TRI);
374 OS << " in " << PrintReg(I->second, TRI);
375 if (std::next(I) != E)
381 ModuleSlotTracker MST(getFunction()->getParent());
382 MST.incorporateFunction(*getFunction());
383 for (const auto &BB : *this) {
385 BB.print(OS, MST, Indexes);
388 OS << "\n# End machine code for function " << getName() << ".\n\n";
393 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
395 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
397 static std::string getGraphName(const MachineFunction *F) {
398 return ("CFG for '" + F->getName() + "' function").str();
401 std::string getNodeLabel(const MachineBasicBlock *Node,
402 const MachineFunction *Graph) {
405 raw_string_ostream OSS(OutStr);
408 OSS << "BB#" << Node->getNumber();
409 if (const BasicBlock *BB = Node->getBasicBlock())
410 OSS << ": " << BB->getName();
415 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
417 // Process string output to make it nicer...
418 for (unsigned i = 0; i != OutStr.length(); ++i)
419 if (OutStr[i] == '\n') { // Left justify
421 OutStr.insert(OutStr.begin()+i+1, 'l');
428 void MachineFunction::viewCFG() const
431 ViewGraph(this, "mf" + getName());
433 errs() << "MachineFunction::viewCFG is only available in debug builds on "
434 << "systems with Graphviz or gv!\n";
438 void MachineFunction::viewCFGOnly() const
441 ViewGraph(this, "mf" + getName(), true);
443 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
444 << "systems with Graphviz or gv!\n";
448 /// Add the specified physical register as a live-in value and
449 /// create a corresponding virtual register for it.
450 unsigned MachineFunction::addLiveIn(unsigned PReg,
451 const TargetRegisterClass *RC) {
452 MachineRegisterInfo &MRI = getRegInfo();
453 unsigned VReg = MRI.getLiveInVirtReg(PReg);
455 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
457 // A physical register can be added several times.
458 // Between two calls, the register class of the related virtual register
459 // may have been constrained to match some operation constraints.
460 // In that case, check that the current register class includes the
461 // physical register and is a sub class of the specified RC.
462 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
463 RC->hasSubClassEq(VRegRC))) &&
464 "Register class mismatch!");
467 VReg = MRI.createVirtualRegister(RC);
468 MRI.addLiveIn(PReg, VReg);
472 /// Return the MCSymbol for the specified non-empty jump table.
473 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
474 /// normal 'L' label is returned.
475 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
476 bool isLinkerPrivate) const {
477 const DataLayout &DL = getDataLayout();
478 assert(JumpTableInfo && "No jump tables");
479 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
481 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
482 : DL.getPrivateGlobalPrefix();
483 SmallString<60> Name;
484 raw_svector_ostream(Name)
485 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
486 return Ctx.getOrCreateSymbol(Name);
489 /// Return a function-local symbol to represent the PIC base.
490 MCSymbol *MachineFunction::getPICBaseSymbol() const {
491 const DataLayout &DL = getDataLayout();
492 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
493 Twine(getFunctionNumber()) + "$pb");
496 //===----------------------------------------------------------------------===//
497 // MachineFrameInfo implementation
498 //===----------------------------------------------------------------------===//
500 /// Make sure the function is at least Align bytes aligned.
501 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
502 if (!StackRealignable || !RealignOption)
503 assert(Align <= StackAlignment &&
504 "For targets without stack realignment, Align is out of limit!");
505 if (MaxAlignment < Align) MaxAlignment = Align;
508 /// Clamp the alignment if requested and emit a warning.
509 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
510 unsigned StackAlign) {
511 if (!ShouldClamp || Align <= StackAlign)
513 DEBUG(dbgs() << "Warning: requested alignment " << Align
514 << " exceeds the stack alignment " << StackAlign
515 << " when stack realignment is off" << '\n');
519 /// Create a new statically sized stack object, returning a nonnegative
520 /// identifier to represent it.
521 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
522 bool isSS, const AllocaInst *Alloca) {
523 assert(Size != 0 && "Cannot allocate zero size stack objects!");
524 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
525 Alignment, StackAlignment);
526 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
528 int Index = (int)Objects.size() - NumFixedObjects - 1;
529 assert(Index >= 0 && "Bad frame index!");
530 ensureMaxAlignment(Alignment);
534 /// Create a new statically sized stack object that represents a spill slot,
535 /// returning a nonnegative identifier to represent it.
536 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
537 unsigned Alignment) {
538 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
539 Alignment, StackAlignment);
540 CreateStackObject(Size, Alignment, true);
541 int Index = (int)Objects.size() - NumFixedObjects - 1;
542 ensureMaxAlignment(Alignment);
546 /// Notify the MachineFrameInfo object that a variable sized object has been
547 /// created. This must be created whenever a variable sized object is created,
548 /// whether or not the index returned is actually used.
549 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
550 const AllocaInst *Alloca) {
551 HasVarSizedObjects = true;
552 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
553 Alignment, StackAlignment);
554 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
555 ensureMaxAlignment(Alignment);
556 return (int)Objects.size()-NumFixedObjects-1;
559 /// Create a new object at a fixed location on the stack.
560 /// All fixed objects should be created before other objects are created for
561 /// efficiency. By default, fixed objects are immutable. This returns an
562 /// index with a negative value.
563 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
564 bool Immutable, bool isAliased) {
565 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
566 // The alignment of the frame index can be determined from its offset from
567 // the incoming frame position. If the frame object is at offset 32 and
568 // the stack is guaranteed to be 16-byte aligned, then we know that the
569 // object is 16-byte aligned.
570 unsigned Align = MinAlign(SPOffset, StackAlignment);
571 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
573 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
575 /*Alloca*/ nullptr, isAliased));
576 return -++NumFixedObjects;
579 /// Create a spill slot at a fixed location on the stack.
580 /// Returns an index with a negative value.
581 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
583 unsigned Align = MinAlign(SPOffset, StackAlignment);
584 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
586 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
590 /*isAliased*/ false));
591 return -++NumFixedObjects;
594 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
595 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
596 BitVector BV(TRI->getNumRegs());
598 // Before CSI is calculated, no registers are considered pristine. They can be
599 // freely used and PEI will make sure they are saved.
600 if (!isCalleeSavedInfoValid())
603 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
606 // Saved CSRs are not pristine.
607 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
608 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
609 E = CSI.end(); I != E; ++I)
610 BV.reset(I->getReg());
615 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
616 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
617 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
618 unsigned MaxAlign = getMaxAlignment();
621 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
622 // It really should be refactored to share code. Until then, changes
623 // should keep in mind that there's tight coupling between the two.
625 for (int i = getObjectIndexBegin(); i != 0; ++i) {
626 int FixedOff = -getObjectOffset(i);
627 if (FixedOff > Offset) Offset = FixedOff;
629 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
630 if (isDeadObjectIndex(i))
632 Offset += getObjectSize(i);
633 unsigned Align = getObjectAlignment(i);
634 // Adjust to alignment boundary
635 Offset = (Offset+Align-1)/Align*Align;
637 MaxAlign = std::max(Align, MaxAlign);
640 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
641 Offset += getMaxCallFrameSize();
643 // Round up the size to a multiple of the alignment. If the function has
644 // any calls or alloca's, align to the target's StackAlignment value to
645 // ensure that the callee's frame or the alloca data is suitably aligned;
646 // otherwise, for leaf functions, align to the TransientStackAlignment
649 if (adjustsStack() || hasVarSizedObjects() ||
650 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
651 StackAlign = TFI->getStackAlignment();
653 StackAlign = TFI->getTransientStackAlignment();
655 // If the frame pointer is eliminated, all frame offsets will be relative to
656 // SP not FP. Align to MaxAlign so this works.
657 StackAlign = std::max(StackAlign, MaxAlign);
658 unsigned AlignMask = StackAlign - 1;
659 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
661 return (unsigned)Offset;
664 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
665 if (Objects.empty()) return;
667 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
668 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
670 OS << "Frame Objects:\n";
672 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
673 const StackObject &SO = Objects[i];
674 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
675 if (SO.Size == ~0ULL) {
680 OS << "variable sized";
682 OS << "size=" << SO.Size;
683 OS << ", align=" << SO.Alignment;
685 if (i < NumFixedObjects)
687 if (i < NumFixedObjects || SO.SPOffset != -1) {
688 int64_t Off = SO.SPOffset - ValOffset;
689 OS << ", at location [SP";
700 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
701 void MachineFrameInfo::dump(const MachineFunction &MF) const {
706 //===----------------------------------------------------------------------===//
707 // MachineJumpTableInfo implementation
708 //===----------------------------------------------------------------------===//
710 /// Return the size of each entry in the jump table.
711 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
712 // The size of a jump table entry is 4 bytes unless the entry is just the
713 // address of a block, in which case it is the pointer size.
714 switch (getEntryKind()) {
715 case MachineJumpTableInfo::EK_BlockAddress:
716 return TD.getPointerSize();
717 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
719 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
720 case MachineJumpTableInfo::EK_LabelDifference32:
721 case MachineJumpTableInfo::EK_Custom32:
723 case MachineJumpTableInfo::EK_Inline:
726 llvm_unreachable("Unknown jump table encoding!");
729 /// Return the alignment of each entry in the jump table.
730 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
731 // The alignment of a jump table entry is the alignment of int32 unless the
732 // entry is just the address of a block, in which case it is the pointer
734 switch (getEntryKind()) {
735 case MachineJumpTableInfo::EK_BlockAddress:
736 return TD.getPointerABIAlignment();
737 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
738 return TD.getABIIntegerTypeAlignment(64);
739 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
740 case MachineJumpTableInfo::EK_LabelDifference32:
741 case MachineJumpTableInfo::EK_Custom32:
742 return TD.getABIIntegerTypeAlignment(32);
743 case MachineJumpTableInfo::EK_Inline:
746 llvm_unreachable("Unknown jump table encoding!");
749 /// Create a new jump table entry in the jump table info.
750 unsigned MachineJumpTableInfo::createJumpTableIndex(
751 const std::vector<MachineBasicBlock*> &DestBBs) {
752 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
753 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
754 return JumpTables.size()-1;
757 /// If Old is the target of any jump tables, update the jump tables to branch
759 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
760 MachineBasicBlock *New) {
761 assert(Old != New && "Not making a change?");
762 bool MadeChange = false;
763 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
764 ReplaceMBBInJumpTable(i, Old, New);
768 /// If Old is a target of the jump tables, update the jump table to branch to
770 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
771 MachineBasicBlock *Old,
772 MachineBasicBlock *New) {
773 assert(Old != New && "Not making a change?");
774 bool MadeChange = false;
775 MachineJumpTableEntry &JTE = JumpTables[Idx];
776 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
777 if (JTE.MBBs[j] == Old) {
784 void MachineJumpTableInfo::print(raw_ostream &OS) const {
785 if (JumpTables.empty()) return;
787 OS << "Jump Tables:\n";
789 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
790 OS << " jt#" << i << ": ";
791 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
792 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
798 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
799 void MachineJumpTableInfo::dump() const { print(dbgs()); }
803 //===----------------------------------------------------------------------===//
804 // MachineConstantPool implementation
805 //===----------------------------------------------------------------------===//
807 void MachineConstantPoolValue::anchor() { }
809 Type *MachineConstantPoolEntry::getType() const {
810 if (isMachineConstantPoolEntry())
811 return Val.MachineCPVal->getType();
812 return Val.ConstVal->getType();
816 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
817 if (isMachineConstantPoolEntry())
818 return Val.MachineCPVal->getRelocationInfo();
819 return Val.ConstVal->getRelocationInfo();
823 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
825 switch (getRelocationInfo()) {
827 llvm_unreachable("Unknown section kind");
828 case Constant::GlobalRelocations:
829 Kind = SectionKind::getReadOnlyWithRel();
831 case Constant::LocalRelocation:
832 Kind = SectionKind::getReadOnlyWithRelLocal();
834 case Constant::NoRelocation:
835 switch (DL->getTypeAllocSize(getType())) {
837 Kind = SectionKind::getMergeableConst4();
840 Kind = SectionKind::getMergeableConst8();
843 Kind = SectionKind::getMergeableConst16();
846 Kind = SectionKind::getReadOnly();
853 MachineConstantPool::~MachineConstantPool() {
854 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
855 if (Constants[i].isMachineConstantPoolEntry())
856 delete Constants[i].Val.MachineCPVal;
857 for (DenseSet<MachineConstantPoolValue*>::iterator I =
858 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
863 /// Test whether the given two constants can be allocated the same constant pool
865 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
866 const DataLayout &DL) {
867 // Handle the trivial case quickly.
868 if (A == B) return true;
870 // If they have the same type but weren't the same constant, quickly
872 if (A->getType() == B->getType()) return false;
874 // We can't handle structs or arrays.
875 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
876 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
879 // For now, only support constants with the same size.
880 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
881 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
884 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
886 // Try constant folding a bitcast of both instructions to an integer. If we
887 // get two identical ConstantInt's, then we are good to share them. We use
888 // the constant folding APIs to do this so that we get the benefit of
890 if (isa<PointerType>(A->getType()))
891 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
892 const_cast<Constant *>(A), DL);
893 else if (A->getType() != IntTy)
894 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
895 const_cast<Constant *>(A), DL);
896 if (isa<PointerType>(B->getType()))
897 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
898 const_cast<Constant *>(B), DL);
899 else if (B->getType() != IntTy)
900 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
901 const_cast<Constant *>(B), DL);
906 /// Create a new entry in the constant pool or return an existing one.
907 /// User must specify the log2 of the minimum required alignment for the object.
908 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
909 unsigned Alignment) {
910 assert(Alignment && "Alignment must be specified!");
911 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
913 // Check to see if we already have this constant.
915 // FIXME, this could be made much more efficient for large constant pools.
916 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
917 if (!Constants[i].isMachineConstantPoolEntry() &&
918 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
919 if ((unsigned)Constants[i].getAlignment() < Alignment)
920 Constants[i].Alignment = Alignment;
924 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
925 return Constants.size()-1;
928 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
929 unsigned Alignment) {
930 assert(Alignment && "Alignment must be specified!");
931 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
933 // Check to see if we already have this constant.
935 // FIXME, this could be made much more efficient for large constant pools.
936 int Idx = V->getExistingMachineCPValue(this, Alignment);
938 MachineCPVsSharingEntries.insert(V);
939 return (unsigned)Idx;
942 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
943 return Constants.size()-1;
946 void MachineConstantPool::print(raw_ostream &OS) const {
947 if (Constants.empty()) return;
949 OS << "Constant Pool:\n";
950 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
951 OS << " cp#" << i << ": ";
952 if (Constants[i].isMachineConstantPoolEntry())
953 Constants[i].Val.MachineCPVal->print(OS);
955 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
956 OS << ", align=" << Constants[i].getAlignment();
961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
962 void MachineConstantPool::dump() const { print(dbgs()); }