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/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GraphWriter.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "codegen"
44 //===----------------------------------------------------------------------===//
45 // MachineFunction implementation
46 //===----------------------------------------------------------------------===//
48 // Out-of-line virtual method.
49 MachineFunctionInfo::~MachineFunctionInfo() {}
51 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
52 MBB->getParent()->DeleteMachineBasicBlock(MBB);
55 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
56 unsigned FunctionNum, MachineModuleInfo &mmi)
57 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
59 if (STI->getRegisterInfo())
60 RegInfo = new (Allocator) MachineRegisterInfo(this);
65 FrameInfo = new (Allocator)
66 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
67 STI->getFrameLowering()->isStackRealignable(),
68 !F->hasFnAttribute("no-realign-stack"));
70 if (Fn->hasFnAttribute(Attribute::StackAlignment))
71 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
73 ConstantPool = new (Allocator) MachineConstantPool(TM);
74 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
76 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
77 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
78 Alignment = std::max(Alignment,
79 STI->getTargetLowering()->getPrefFunctionAlignment());
81 FunctionNumber = FunctionNum;
82 JumpTableInfo = nullptr;
85 MachineFunction::~MachineFunction() {
86 // Don't call destructors on MachineInstr and MachineOperand. All of their
87 // memory comes from the BumpPtrAllocator which is about to be purged.
89 // Do call MachineBasicBlock destructors, it contains std::vectors.
90 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
91 I->Insts.clearAndLeakNodesUnsafely();
93 InstructionRecycler.clear(Allocator);
94 OperandRecycler.clear(Allocator);
95 BasicBlockRecycler.clear(Allocator);
97 RegInfo->~MachineRegisterInfo();
98 Allocator.Deallocate(RegInfo);
101 MFInfo->~MachineFunctionInfo();
102 Allocator.Deallocate(MFInfo);
105 FrameInfo->~MachineFrameInfo();
106 Allocator.Deallocate(FrameInfo);
108 ConstantPool->~MachineConstantPool();
109 Allocator.Deallocate(ConstantPool);
112 JumpTableInfo->~MachineJumpTableInfo();
113 Allocator.Deallocate(JumpTableInfo);
117 /// Get the JumpTableInfo for this function.
118 /// If it does not already exist, allocate one.
119 MachineJumpTableInfo *MachineFunction::
120 getOrCreateJumpTableInfo(unsigned EntryKind) {
121 if (JumpTableInfo) return JumpTableInfo;
123 JumpTableInfo = new (Allocator)
124 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
125 return JumpTableInfo;
128 /// Should we be emitting segmented stack stuff for the function
129 bool MachineFunction::shouldSplitStack() {
130 return getFunction()->hasFnAttribute("split-stack");
133 /// This discards all of the MachineBasicBlock numbers and recomputes them.
134 /// This guarantees that the MBB numbers are sequential, dense, and match the
135 /// ordering of the blocks within the function. If a specific MachineBasicBlock
136 /// is specified, only that block and those after it are renumbered.
137 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
138 if (empty()) { MBBNumbering.clear(); return; }
139 MachineFunction::iterator MBBI, E = end();
145 // Figure out the block number this should have.
146 unsigned BlockNo = 0;
148 BlockNo = std::prev(MBBI)->getNumber() + 1;
150 for (; MBBI != E; ++MBBI, ++BlockNo) {
151 if (MBBI->getNumber() != (int)BlockNo) {
152 // Remove use of the old number.
153 if (MBBI->getNumber() != -1) {
154 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
155 "MBB number mismatch!");
156 MBBNumbering[MBBI->getNumber()] = nullptr;
159 // If BlockNo is already taken, set that block's number to -1.
160 if (MBBNumbering[BlockNo])
161 MBBNumbering[BlockNo]->setNumber(-1);
163 MBBNumbering[BlockNo] = MBBI;
164 MBBI->setNumber(BlockNo);
168 // Okay, all the blocks are renumbered. If we have compactified the block
169 // numbering, shrink MBBNumbering now.
170 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
171 MBBNumbering.resize(BlockNo);
174 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
176 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
177 DebugLoc DL, bool NoImp) {
178 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
179 MachineInstr(*this, MCID, DL, NoImp);
182 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
183 /// identical in all ways except the instruction has no parent, prev, or next.
185 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
186 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
187 MachineInstr(*this, *Orig);
190 /// Delete the given MachineInstr.
192 /// This function also serves as the MachineInstr destructor - the real
193 /// ~MachineInstr() destructor must be empty.
195 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
196 // Strip it for parts. The operand array and the MI object itself are
197 // independently recyclable.
199 deallocateOperandArray(MI->CapOperands, MI->Operands);
200 // Don't call ~MachineInstr() which must be trivial anyway because
201 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
203 InstructionRecycler.Deallocate(Allocator, MI);
206 /// Allocate a new MachineBasicBlock. Use this instead of
207 /// `new MachineBasicBlock'.
209 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
210 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
211 MachineBasicBlock(*this, bb);
214 /// Delete the given MachineBasicBlock.
216 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
217 assert(MBB->getParent() == this && "MBB parent mismatch!");
218 MBB->~MachineBasicBlock();
219 BasicBlockRecycler.Deallocate(Allocator, MBB);
223 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
224 uint64_t s, unsigned base_alignment,
225 const AAMDNodes &AAInfo,
226 const MDNode *Ranges) {
227 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
232 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
233 int64_t Offset, uint64_t Size) {
235 return new (Allocator)
236 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
237 MMO->getOffset()+Offset),
238 MMO->getFlags(), Size,
239 MMO->getBaseAlignment());
240 return new (Allocator)
241 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
242 MMO->getOffset()+Offset),
243 MMO->getFlags(), Size,
244 MMO->getBaseAlignment());
247 MachineInstr::mmo_iterator
248 MachineFunction::allocateMemRefsArray(unsigned long Num) {
249 return Allocator.Allocate<MachineMemOperand *>(Num);
252 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
253 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
254 MachineInstr::mmo_iterator End) {
255 // Count the number of load mem refs.
257 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
261 // Allocate a new array and populate it with the load information.
262 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
264 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
265 if ((*I)->isLoad()) {
266 if (!(*I)->isStore())
270 // Clone the MMO and unset the store flag.
271 MachineMemOperand *JustLoad =
272 getMachineMemOperand((*I)->getPointerInfo(),
273 (*I)->getFlags() & ~MachineMemOperand::MOStore,
274 (*I)->getSize(), (*I)->getBaseAlignment(),
276 Result[Index] = JustLoad;
281 return std::make_pair(Result, Result + Num);
284 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
285 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
286 MachineInstr::mmo_iterator End) {
287 // Count the number of load mem refs.
289 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
293 // Allocate a new array and populate it with the store information.
294 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
296 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
297 if ((*I)->isStore()) {
302 // Clone the MMO and unset the load flag.
303 MachineMemOperand *JustStore =
304 getMachineMemOperand((*I)->getPointerInfo(),
305 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
306 (*I)->getSize(), (*I)->getBaseAlignment(),
308 Result[Index] = JustStore;
313 return std::make_pair(Result, Result + Num);
316 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
317 void MachineFunction::dump() const {
322 StringRef MachineFunction::getName() const {
323 assert(getFunction() && "No function!");
324 return getFunction()->getName();
327 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
328 OS << "# Machine code for function " << getName() << ": ";
330 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
331 if (!RegInfo->tracksLiveness())
332 OS << ", not tracking liveness";
336 // Print Frame Information
337 FrameInfo->print(*this, OS);
339 // Print JumpTable Information
341 JumpTableInfo->print(OS);
343 // Print Constant Pool
344 ConstantPool->print(OS);
346 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
348 if (RegInfo && !RegInfo->livein_empty()) {
349 OS << "Function Live Ins: ";
350 for (MachineRegisterInfo::livein_iterator
351 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
352 OS << PrintReg(I->first, TRI);
354 OS << " in " << PrintReg(I->second, TRI);
355 if (std::next(I) != E)
361 for (const auto &BB : *this) {
363 BB.print(OS, Indexes);
366 OS << "\n# End machine code for function " << getName() << ".\n\n";
371 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
373 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
375 static std::string getGraphName(const MachineFunction *F) {
376 return ("CFG for '" + F->getName() + "' function").str();
379 std::string getNodeLabel(const MachineBasicBlock *Node,
380 const MachineFunction *Graph) {
383 raw_string_ostream OSS(OutStr);
386 OSS << "BB#" << Node->getNumber();
387 if (const BasicBlock *BB = Node->getBasicBlock())
388 OSS << ": " << BB->getName();
393 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
395 // Process string output to make it nicer...
396 for (unsigned i = 0; i != OutStr.length(); ++i)
397 if (OutStr[i] == '\n') { // Left justify
399 OutStr.insert(OutStr.begin()+i+1, 'l');
406 void MachineFunction::viewCFG() const
409 ViewGraph(this, "mf" + getName());
411 errs() << "MachineFunction::viewCFG is only available in debug builds on "
412 << "systems with Graphviz or gv!\n";
416 void MachineFunction::viewCFGOnly() const
419 ViewGraph(this, "mf" + getName(), true);
421 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
422 << "systems with Graphviz or gv!\n";
426 /// Add the specified physical register as a live-in value and
427 /// create a corresponding virtual register for it.
428 unsigned MachineFunction::addLiveIn(unsigned PReg,
429 const TargetRegisterClass *RC) {
430 MachineRegisterInfo &MRI = getRegInfo();
431 unsigned VReg = MRI.getLiveInVirtReg(PReg);
433 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
435 // A physical register can be added several times.
436 // Between two calls, the register class of the related virtual register
437 // may have been constrained to match some operation constraints.
438 // In that case, check that the current register class includes the
439 // physical register and is a sub class of the specified RC.
440 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
441 RC->hasSubClassEq(VRegRC))) &&
442 "Register class mismatch!");
445 VReg = MRI.createVirtualRegister(RC);
446 MRI.addLiveIn(PReg, VReg);
450 /// Return the MCSymbol for the specified non-empty jump table.
451 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
452 /// normal 'L' label is returned.
453 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
454 bool isLinkerPrivate) const {
455 const DataLayout *DL = getTarget().getDataLayout();
456 assert(JumpTableInfo && "No jump tables");
457 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
459 const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
460 DL->getPrivateGlobalPrefix();
461 SmallString<60> Name;
462 raw_svector_ostream(Name)
463 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
464 return Ctx.getOrCreateSymbol(Name);
467 /// Return a function-local symbol to represent the PIC base.
468 MCSymbol *MachineFunction::getPICBaseSymbol() const {
469 const DataLayout *DL = getTarget().getDataLayout();
470 return Ctx.getOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
471 Twine(getFunctionNumber())+"$pb");
474 //===----------------------------------------------------------------------===//
475 // MachineFrameInfo implementation
476 //===----------------------------------------------------------------------===//
478 /// Make sure the function is at least Align bytes aligned.
479 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
480 if (!StackRealignable || !RealignOption)
481 assert(Align <= StackAlignment &&
482 "For targets without stack realignment, Align is out of limit!");
483 if (MaxAlignment < Align) MaxAlignment = Align;
486 /// Clamp the alignment if requested and emit a warning.
487 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
488 unsigned StackAlign) {
489 if (!ShouldClamp || Align <= StackAlign)
491 DEBUG(dbgs() << "Warning: requested alignment " << Align
492 << " exceeds the stack alignment " << StackAlign
493 << " when stack realignment is off" << '\n');
497 /// Create a new statically sized stack object, returning a nonnegative
498 /// identifier to represent it.
499 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
500 bool isSS, const AllocaInst *Alloca) {
501 assert(Size != 0 && "Cannot allocate zero size stack objects!");
502 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
503 Alignment, StackAlignment);
504 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
506 int Index = (int)Objects.size() - NumFixedObjects - 1;
507 assert(Index >= 0 && "Bad frame index!");
508 ensureMaxAlignment(Alignment);
512 /// Create a new statically sized stack object that represents a spill slot,
513 /// returning a nonnegative identifier to represent it.
514 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
515 unsigned Alignment) {
516 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
517 Alignment, StackAlignment);
518 CreateStackObject(Size, Alignment, true);
519 int Index = (int)Objects.size() - NumFixedObjects - 1;
520 ensureMaxAlignment(Alignment);
524 /// Notify the MachineFrameInfo object that a variable sized object has been
525 /// created. This must be created whenever a variable sized object is created,
526 /// whether or not the index returned is actually used.
527 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
528 const AllocaInst *Alloca) {
529 HasVarSizedObjects = true;
530 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
531 Alignment, StackAlignment);
532 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
533 ensureMaxAlignment(Alignment);
534 return (int)Objects.size()-NumFixedObjects-1;
537 /// Create a new object at a fixed location on the stack.
538 /// All fixed objects should be created before other objects are created for
539 /// efficiency. By default, fixed objects are immutable. This returns an
540 /// index with a negative value.
541 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
542 bool Immutable, bool isAliased) {
543 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
544 // The alignment of the frame index can be determined from its offset from
545 // the incoming frame position. If the frame object is at offset 32 and
546 // the stack is guaranteed to be 16-byte aligned, then we know that the
547 // object is 16-byte aligned.
548 unsigned Align = MinAlign(SPOffset, StackAlignment);
549 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
551 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
553 /*Alloca*/ nullptr, isAliased));
554 return -++NumFixedObjects;
557 /// Create a spill slot at a fixed location on the stack.
558 /// Returns an index with a negative value.
559 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
561 unsigned Align = MinAlign(SPOffset, StackAlignment);
562 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
564 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
568 /*isAliased*/ false));
569 return -++NumFixedObjects;
572 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
573 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
574 BitVector BV(TRI->getNumRegs());
576 // Before CSI is calculated, no registers are considered pristine. They can be
577 // freely used and PEI will make sure they are saved.
578 if (!isCalleeSavedInfoValid())
581 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
584 // Saved CSRs are not pristine.
585 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
586 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
587 E = CSI.end(); I != E; ++I)
588 BV.reset(I->getReg());
593 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
594 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
595 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
596 unsigned MaxAlign = getMaxAlignment();
599 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
600 // It really should be refactored to share code. Until then, changes
601 // should keep in mind that there's tight coupling between the two.
603 for (int i = getObjectIndexBegin(); i != 0; ++i) {
604 int FixedOff = -getObjectOffset(i);
605 if (FixedOff > Offset) Offset = FixedOff;
607 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
608 if (isDeadObjectIndex(i))
610 Offset += getObjectSize(i);
611 unsigned Align = getObjectAlignment(i);
612 // Adjust to alignment boundary
613 Offset = (Offset+Align-1)/Align*Align;
615 MaxAlign = std::max(Align, MaxAlign);
618 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
619 Offset += getMaxCallFrameSize();
621 // Round up the size to a multiple of the alignment. If the function has
622 // any calls or alloca's, align to the target's StackAlignment value to
623 // ensure that the callee's frame or the alloca data is suitably aligned;
624 // otherwise, for leaf functions, align to the TransientStackAlignment
627 if (adjustsStack() || hasVarSizedObjects() ||
628 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
629 StackAlign = TFI->getStackAlignment();
631 StackAlign = TFI->getTransientStackAlignment();
633 // If the frame pointer is eliminated, all frame offsets will be relative to
634 // SP not FP. Align to MaxAlign so this works.
635 StackAlign = std::max(StackAlign, MaxAlign);
636 unsigned AlignMask = StackAlign - 1;
637 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
639 return (unsigned)Offset;
642 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
643 if (Objects.empty()) return;
645 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
646 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
648 OS << "Frame Objects:\n";
650 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
651 const StackObject &SO = Objects[i];
652 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
653 if (SO.Size == ~0ULL) {
658 OS << "variable sized";
660 OS << "size=" << SO.Size;
661 OS << ", align=" << SO.Alignment;
663 if (i < NumFixedObjects)
665 if (i < NumFixedObjects || SO.SPOffset != -1) {
666 int64_t Off = SO.SPOffset - ValOffset;
667 OS << ", at location [SP";
678 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
679 void MachineFrameInfo::dump(const MachineFunction &MF) const {
684 //===----------------------------------------------------------------------===//
685 // MachineJumpTableInfo implementation
686 //===----------------------------------------------------------------------===//
688 /// Return the size of each entry in the jump table.
689 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
690 // The size of a jump table entry is 4 bytes unless the entry is just the
691 // address of a block, in which case it is the pointer size.
692 switch (getEntryKind()) {
693 case MachineJumpTableInfo::EK_BlockAddress:
694 return TD.getPointerSize();
695 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
697 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
698 case MachineJumpTableInfo::EK_LabelDifference32:
699 case MachineJumpTableInfo::EK_Custom32:
701 case MachineJumpTableInfo::EK_Inline:
704 llvm_unreachable("Unknown jump table encoding!");
707 /// Return the alignment of each entry in the jump table.
708 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
709 // The alignment of a jump table entry is the alignment of int32 unless the
710 // entry is just the address of a block, in which case it is the pointer
712 switch (getEntryKind()) {
713 case MachineJumpTableInfo::EK_BlockAddress:
714 return TD.getPointerABIAlignment();
715 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
716 return TD.getABIIntegerTypeAlignment(64);
717 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
718 case MachineJumpTableInfo::EK_LabelDifference32:
719 case MachineJumpTableInfo::EK_Custom32:
720 return TD.getABIIntegerTypeAlignment(32);
721 case MachineJumpTableInfo::EK_Inline:
724 llvm_unreachable("Unknown jump table encoding!");
727 /// Create a new jump table entry in the jump table info.
728 unsigned MachineJumpTableInfo::createJumpTableIndex(
729 const std::vector<MachineBasicBlock*> &DestBBs) {
730 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
731 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
732 return JumpTables.size()-1;
735 /// If Old is the target of any jump tables, update the jump tables to branch
737 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
738 MachineBasicBlock *New) {
739 assert(Old != New && "Not making a change?");
740 bool MadeChange = false;
741 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
742 ReplaceMBBInJumpTable(i, Old, New);
746 /// If Old is a target of the jump tables, update the jump table to branch to
748 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
749 MachineBasicBlock *Old,
750 MachineBasicBlock *New) {
751 assert(Old != New && "Not making a change?");
752 bool MadeChange = false;
753 MachineJumpTableEntry &JTE = JumpTables[Idx];
754 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
755 if (JTE.MBBs[j] == Old) {
762 void MachineJumpTableInfo::print(raw_ostream &OS) const {
763 if (JumpTables.empty()) return;
765 OS << "Jump Tables:\n";
767 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
768 OS << " jt#" << i << ": ";
769 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
770 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
776 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
777 void MachineJumpTableInfo::dump() const { print(dbgs()); }
781 //===----------------------------------------------------------------------===//
782 // MachineConstantPool implementation
783 //===----------------------------------------------------------------------===//
785 void MachineConstantPoolValue::anchor() { }
787 const DataLayout *MachineConstantPool::getDataLayout() const {
788 return TM.getDataLayout();
791 Type *MachineConstantPoolEntry::getType() const {
792 if (isMachineConstantPoolEntry())
793 return Val.MachineCPVal->getType();
794 return Val.ConstVal->getType();
798 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
799 if (isMachineConstantPoolEntry())
800 return Val.MachineCPVal->getRelocationInfo();
801 return Val.ConstVal->getRelocationInfo();
805 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
807 switch (getRelocationInfo()) {
809 llvm_unreachable("Unknown section kind");
810 case Constant::GlobalRelocations:
811 Kind = SectionKind::getReadOnlyWithRel();
813 case Constant::LocalRelocation:
814 Kind = SectionKind::getReadOnlyWithRelLocal();
816 case Constant::NoRelocation:
817 switch (DL->getTypeAllocSize(getType())) {
819 Kind = SectionKind::getMergeableConst4();
822 Kind = SectionKind::getMergeableConst8();
825 Kind = SectionKind::getMergeableConst16();
828 Kind = SectionKind::getReadOnly();
835 MachineConstantPool::~MachineConstantPool() {
836 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
837 if (Constants[i].isMachineConstantPoolEntry())
838 delete Constants[i].Val.MachineCPVal;
839 for (DenseSet<MachineConstantPoolValue*>::iterator I =
840 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
845 /// Test whether the given two constants can be allocated the same constant pool
847 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
848 const DataLayout *TD) {
849 // Handle the trivial case quickly.
850 if (A == B) return true;
852 // If they have the same type but weren't the same constant, quickly
854 if (A->getType() == B->getType()) return false;
856 // We can't handle structs or arrays.
857 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
858 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
861 // For now, only support constants with the same size.
862 uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
863 if (StoreSize != TD->getTypeStoreSize(B->getType()) || StoreSize > 128)
866 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
868 // Try constant folding a bitcast of both instructions to an integer. If we
869 // get two identical ConstantInt's, then we are good to share them. We use
870 // the constant folding APIs to do this so that we get the benefit of
872 if (isa<PointerType>(A->getType()))
873 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
874 const_cast<Constant *>(A), *TD);
875 else if (A->getType() != IntTy)
876 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
877 const_cast<Constant *>(A), *TD);
878 if (isa<PointerType>(B->getType()))
879 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
880 const_cast<Constant *>(B), *TD);
881 else if (B->getType() != IntTy)
882 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
883 const_cast<Constant *>(B), *TD);
888 /// Create a new entry in the constant pool or return an existing one.
889 /// User must specify the log2 of the minimum required alignment for the object.
890 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
891 unsigned Alignment) {
892 assert(Alignment && "Alignment must be specified!");
893 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
895 // Check to see if we already have this constant.
897 // FIXME, this could be made much more efficient for large constant pools.
898 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
899 if (!Constants[i].isMachineConstantPoolEntry() &&
900 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
902 if ((unsigned)Constants[i].getAlignment() < Alignment)
903 Constants[i].Alignment = Alignment;
907 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
908 return Constants.size()-1;
911 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
912 unsigned Alignment) {
913 assert(Alignment && "Alignment must be specified!");
914 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
916 // Check to see if we already have this constant.
918 // FIXME, this could be made much more efficient for large constant pools.
919 int Idx = V->getExistingMachineCPValue(this, Alignment);
921 MachineCPVsSharingEntries.insert(V);
922 return (unsigned)Idx;
925 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
926 return Constants.size()-1;
929 void MachineConstantPool::print(raw_ostream &OS) const {
930 if (Constants.empty()) return;
932 OS << "Constant Pool:\n";
933 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
934 OS << " cp#" << i << ": ";
935 if (Constants[i].isMachineConstantPoolEntry())
936 Constants[i].Val.MachineCPVal->print(OS);
938 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
939 OS << ", align=" << Constants[i].getAlignment();
944 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
945 void MachineConstantPool::dump() const { print(dbgs()); }