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/ModuleSlotTracker.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GraphWriter.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetFrameLowering.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "codegen"
46 void MachineFunctionInitializer::anchor() {}
48 //===----------------------------------------------------------------------===//
49 // MachineFunction implementation
50 //===----------------------------------------------------------------------===//
52 // Out-of-line virtual method.
53 MachineFunctionInfo::~MachineFunctionInfo() {}
55 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
56 MBB->getParent()->DeleteMachineBasicBlock(MBB);
59 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
60 unsigned FunctionNum, MachineModuleInfo &mmi)
61 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
63 if (STI->getRegisterInfo())
64 RegInfo = new (Allocator) MachineRegisterInfo(this);
69 FrameInfo = new (Allocator)
70 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
71 STI->getFrameLowering()->isStackRealignable(),
72 !F->hasFnAttribute("no-realign-stack"));
74 if (Fn->hasFnAttribute(Attribute::StackAlignment))
75 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
77 ConstantPool = new (Allocator) MachineConstantPool(TM);
78 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
80 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
81 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
82 Alignment = std::max(Alignment,
83 STI->getTargetLowering()->getPrefFunctionAlignment());
85 FunctionNumber = FunctionNum;
86 JumpTableInfo = nullptr;
89 MachineFunction::~MachineFunction() {
90 // Don't call destructors on MachineInstr and MachineOperand. All of their
91 // memory comes from the BumpPtrAllocator which is about to be purged.
93 // Do call MachineBasicBlock destructors, it contains std::vectors.
94 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
95 I->Insts.clearAndLeakNodesUnsafely();
97 InstructionRecycler.clear(Allocator);
98 OperandRecycler.clear(Allocator);
99 BasicBlockRecycler.clear(Allocator);
101 RegInfo->~MachineRegisterInfo();
102 Allocator.Deallocate(RegInfo);
105 MFInfo->~MachineFunctionInfo();
106 Allocator.Deallocate(MFInfo);
109 FrameInfo->~MachineFrameInfo();
110 Allocator.Deallocate(FrameInfo);
112 ConstantPool->~MachineConstantPool();
113 Allocator.Deallocate(ConstantPool);
116 JumpTableInfo->~MachineJumpTableInfo();
117 Allocator.Deallocate(JumpTableInfo);
121 /// Get the JumpTableInfo for this function.
122 /// If it does not already exist, allocate one.
123 MachineJumpTableInfo *MachineFunction::
124 getOrCreateJumpTableInfo(unsigned EntryKind) {
125 if (JumpTableInfo) return JumpTableInfo;
127 JumpTableInfo = new (Allocator)
128 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
129 return JumpTableInfo;
132 /// Should we be emitting segmented stack stuff for the function
133 bool MachineFunction::shouldSplitStack() {
134 return getFunction()->hasFnAttribute("split-stack");
137 /// This discards all of the MachineBasicBlock numbers and recomputes them.
138 /// This guarantees that the MBB numbers are sequential, dense, and match the
139 /// ordering of the blocks within the function. If a specific MachineBasicBlock
140 /// is specified, only that block and those after it are renumbered.
141 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
142 if (empty()) { MBBNumbering.clear(); return; }
143 MachineFunction::iterator MBBI, E = end();
149 // Figure out the block number this should have.
150 unsigned BlockNo = 0;
152 BlockNo = std::prev(MBBI)->getNumber() + 1;
154 for (; MBBI != E; ++MBBI, ++BlockNo) {
155 if (MBBI->getNumber() != (int)BlockNo) {
156 // Remove use of the old number.
157 if (MBBI->getNumber() != -1) {
158 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
159 "MBB number mismatch!");
160 MBBNumbering[MBBI->getNumber()] = nullptr;
163 // If BlockNo is already taken, set that block's number to -1.
164 if (MBBNumbering[BlockNo])
165 MBBNumbering[BlockNo]->setNumber(-1);
167 MBBNumbering[BlockNo] = MBBI;
168 MBBI->setNumber(BlockNo);
172 // Okay, all the blocks are renumbered. If we have compactified the block
173 // numbering, shrink MBBNumbering now.
174 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
175 MBBNumbering.resize(BlockNo);
178 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
180 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
181 DebugLoc DL, bool NoImp) {
182 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
183 MachineInstr(*this, MCID, DL, NoImp);
186 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
187 /// identical in all ways except the instruction has no parent, prev, or next.
189 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
190 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
191 MachineInstr(*this, *Orig);
194 /// Delete the given MachineInstr.
196 /// This function also serves as the MachineInstr destructor - the real
197 /// ~MachineInstr() destructor must be empty.
199 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
200 // Strip it for parts. The operand array and the MI object itself are
201 // independently recyclable.
203 deallocateOperandArray(MI->CapOperands, MI->Operands);
204 // Don't call ~MachineInstr() which must be trivial anyway because
205 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
207 InstructionRecycler.Deallocate(Allocator, MI);
210 /// Allocate a new MachineBasicBlock. Use this instead of
211 /// `new MachineBasicBlock'.
213 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
214 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
215 MachineBasicBlock(*this, bb);
218 /// Delete the given MachineBasicBlock.
220 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
221 assert(MBB->getParent() == this && "MBB parent mismatch!");
222 MBB->~MachineBasicBlock();
223 BasicBlockRecycler.Deallocate(Allocator, MBB);
227 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
228 uint64_t s, unsigned base_alignment,
229 const AAMDNodes &AAInfo,
230 const MDNode *Ranges) {
231 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
236 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
237 int64_t Offset, uint64_t Size) {
239 return new (Allocator)
240 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
241 MMO->getOffset()+Offset),
242 MMO->getFlags(), Size,
243 MMO->getBaseAlignment());
244 return new (Allocator)
245 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
246 MMO->getOffset()+Offset),
247 MMO->getFlags(), Size,
248 MMO->getBaseAlignment());
251 MachineInstr::mmo_iterator
252 MachineFunction::allocateMemRefsArray(unsigned long Num) {
253 return Allocator.Allocate<MachineMemOperand *>(Num);
256 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
257 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
258 MachineInstr::mmo_iterator End) {
259 // Count the number of load mem refs.
261 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
265 // Allocate a new array and populate it with the load information.
266 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
268 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
269 if ((*I)->isLoad()) {
270 if (!(*I)->isStore())
274 // Clone the MMO and unset the store flag.
275 MachineMemOperand *JustLoad =
276 getMachineMemOperand((*I)->getPointerInfo(),
277 (*I)->getFlags() & ~MachineMemOperand::MOStore,
278 (*I)->getSize(), (*I)->getBaseAlignment(),
280 Result[Index] = JustLoad;
285 return std::make_pair(Result, Result + Num);
288 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
289 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
290 MachineInstr::mmo_iterator End) {
291 // Count the number of load mem refs.
293 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
297 // Allocate a new array and populate it with the store information.
298 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
300 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
301 if ((*I)->isStore()) {
306 // Clone the MMO and unset the load flag.
307 MachineMemOperand *JustStore =
308 getMachineMemOperand((*I)->getPointerInfo(),
309 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
310 (*I)->getSize(), (*I)->getBaseAlignment(),
312 Result[Index] = JustStore;
317 return std::make_pair(Result, Result + Num);
320 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
321 void MachineFunction::dump() const {
326 StringRef MachineFunction::getName() const {
327 assert(getFunction() && "No function!");
328 return getFunction()->getName();
331 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
332 OS << "# Machine code for function " << getName() << ": ";
334 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
335 if (!RegInfo->tracksLiveness())
336 OS << ", not tracking liveness";
340 // Print Frame Information
341 FrameInfo->print(*this, OS);
343 // Print JumpTable Information
345 JumpTableInfo->print(OS);
347 // Print Constant Pool
348 ConstantPool->print(OS);
350 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
352 if (RegInfo && !RegInfo->livein_empty()) {
353 OS << "Function Live Ins: ";
354 for (MachineRegisterInfo::livein_iterator
355 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
356 OS << PrintReg(I->first, TRI);
358 OS << " in " << PrintReg(I->second, TRI);
359 if (std::next(I) != E)
365 ModuleSlotTracker MST(getFunction()->getParent());
366 MST.incorporateFunction(*getFunction());
367 for (const auto &BB : *this) {
369 BB.print(OS, MST, Indexes);
372 OS << "\n# End machine code for function " << getName() << ".\n\n";
377 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
379 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
381 static std::string getGraphName(const MachineFunction *F) {
382 return ("CFG for '" + F->getName() + "' function").str();
385 std::string getNodeLabel(const MachineBasicBlock *Node,
386 const MachineFunction *Graph) {
389 raw_string_ostream OSS(OutStr);
392 OSS << "BB#" << Node->getNumber();
393 if (const BasicBlock *BB = Node->getBasicBlock())
394 OSS << ": " << BB->getName();
399 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
401 // Process string output to make it nicer...
402 for (unsigned i = 0; i != OutStr.length(); ++i)
403 if (OutStr[i] == '\n') { // Left justify
405 OutStr.insert(OutStr.begin()+i+1, 'l');
412 void MachineFunction::viewCFG() const
415 ViewGraph(this, "mf" + getName());
417 errs() << "MachineFunction::viewCFG is only available in debug builds on "
418 << "systems with Graphviz or gv!\n";
422 void MachineFunction::viewCFGOnly() const
425 ViewGraph(this, "mf" + getName(), true);
427 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
428 << "systems with Graphviz or gv!\n";
432 /// Add the specified physical register as a live-in value and
433 /// create a corresponding virtual register for it.
434 unsigned MachineFunction::addLiveIn(unsigned PReg,
435 const TargetRegisterClass *RC) {
436 MachineRegisterInfo &MRI = getRegInfo();
437 unsigned VReg = MRI.getLiveInVirtReg(PReg);
439 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
441 // A physical register can be added several times.
442 // Between two calls, the register class of the related virtual register
443 // may have been constrained to match some operation constraints.
444 // In that case, check that the current register class includes the
445 // physical register and is a sub class of the specified RC.
446 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
447 RC->hasSubClassEq(VRegRC))) &&
448 "Register class mismatch!");
451 VReg = MRI.createVirtualRegister(RC);
452 MRI.addLiveIn(PReg, VReg);
456 /// Return the MCSymbol for the specified non-empty jump table.
457 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
458 /// normal 'L' label is returned.
459 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
460 bool isLinkerPrivate) const {
461 const DataLayout *DL = getTarget().getDataLayout();
462 assert(JumpTableInfo && "No jump tables");
463 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
465 const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
466 DL->getPrivateGlobalPrefix();
467 SmallString<60> Name;
468 raw_svector_ostream(Name)
469 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
470 return Ctx.getOrCreateSymbol(Name);
473 /// Return a function-local symbol to represent the PIC base.
474 MCSymbol *MachineFunction::getPICBaseSymbol() const {
475 const DataLayout *DL = getTarget().getDataLayout();
476 return Ctx.getOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
477 Twine(getFunctionNumber())+"$pb");
480 //===----------------------------------------------------------------------===//
481 // MachineFrameInfo implementation
482 //===----------------------------------------------------------------------===//
484 /// Make sure the function is at least Align bytes aligned.
485 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
486 if (!StackRealignable || !RealignOption)
487 assert(Align <= StackAlignment &&
488 "For targets without stack realignment, Align is out of limit!");
489 if (MaxAlignment < Align) MaxAlignment = Align;
492 /// Clamp the alignment if requested and emit a warning.
493 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
494 unsigned StackAlign) {
495 if (!ShouldClamp || Align <= StackAlign)
497 DEBUG(dbgs() << "Warning: requested alignment " << Align
498 << " exceeds the stack alignment " << StackAlign
499 << " when stack realignment is off" << '\n');
503 /// Create a new statically sized stack object, returning a nonnegative
504 /// identifier to represent it.
505 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
506 bool isSS, const AllocaInst *Alloca) {
507 assert(Size != 0 && "Cannot allocate zero size stack objects!");
508 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
509 Alignment, StackAlignment);
510 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
512 int Index = (int)Objects.size() - NumFixedObjects - 1;
513 assert(Index >= 0 && "Bad frame index!");
514 ensureMaxAlignment(Alignment);
518 /// Create a new statically sized stack object that represents a spill slot,
519 /// returning a nonnegative identifier to represent it.
520 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
521 unsigned Alignment) {
522 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
523 Alignment, StackAlignment);
524 CreateStackObject(Size, Alignment, true);
525 int Index = (int)Objects.size() - NumFixedObjects - 1;
526 ensureMaxAlignment(Alignment);
530 /// Notify the MachineFrameInfo object that a variable sized object has been
531 /// created. This must be created whenever a variable sized object is created,
532 /// whether or not the index returned is actually used.
533 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
534 const AllocaInst *Alloca) {
535 HasVarSizedObjects = true;
536 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
537 Alignment, StackAlignment);
538 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
539 ensureMaxAlignment(Alignment);
540 return (int)Objects.size()-NumFixedObjects-1;
543 /// Create a new object at a fixed location on the stack.
544 /// All fixed objects should be created before other objects are created for
545 /// efficiency. By default, fixed objects are immutable. This returns an
546 /// index with a negative value.
547 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
548 bool Immutable, bool isAliased) {
549 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
550 // The alignment of the frame index can be determined from its offset from
551 // the incoming frame position. If the frame object is at offset 32 and
552 // the stack is guaranteed to be 16-byte aligned, then we know that the
553 // object is 16-byte aligned.
554 unsigned Align = MinAlign(SPOffset, StackAlignment);
555 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
557 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
559 /*Alloca*/ nullptr, isAliased));
560 return -++NumFixedObjects;
563 /// Create a spill slot at a fixed location on the stack.
564 /// Returns an index with a negative value.
565 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
567 unsigned Align = MinAlign(SPOffset, StackAlignment);
568 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
570 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
574 /*isAliased*/ false));
575 return -++NumFixedObjects;
578 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
579 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
580 BitVector BV(TRI->getNumRegs());
582 // Before CSI is calculated, no registers are considered pristine. They can be
583 // freely used and PEI will make sure they are saved.
584 if (!isCalleeSavedInfoValid())
587 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
590 // Saved CSRs are not pristine.
591 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
592 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
593 E = CSI.end(); I != E; ++I)
594 BV.reset(I->getReg());
599 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
600 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
601 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
602 unsigned MaxAlign = getMaxAlignment();
605 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
606 // It really should be refactored to share code. Until then, changes
607 // should keep in mind that there's tight coupling between the two.
609 for (int i = getObjectIndexBegin(); i != 0; ++i) {
610 int FixedOff = -getObjectOffset(i);
611 if (FixedOff > Offset) Offset = FixedOff;
613 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
614 if (isDeadObjectIndex(i))
616 Offset += getObjectSize(i);
617 unsigned Align = getObjectAlignment(i);
618 // Adjust to alignment boundary
619 Offset = (Offset+Align-1)/Align*Align;
621 MaxAlign = std::max(Align, MaxAlign);
624 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
625 Offset += getMaxCallFrameSize();
627 // Round up the size to a multiple of the alignment. If the function has
628 // any calls or alloca's, align to the target's StackAlignment value to
629 // ensure that the callee's frame or the alloca data is suitably aligned;
630 // otherwise, for leaf functions, align to the TransientStackAlignment
633 if (adjustsStack() || hasVarSizedObjects() ||
634 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
635 StackAlign = TFI->getStackAlignment();
637 StackAlign = TFI->getTransientStackAlignment();
639 // If the frame pointer is eliminated, all frame offsets will be relative to
640 // SP not FP. Align to MaxAlign so this works.
641 StackAlign = std::max(StackAlign, MaxAlign);
642 unsigned AlignMask = StackAlign - 1;
643 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
645 return (unsigned)Offset;
648 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
649 if (Objects.empty()) return;
651 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
652 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
654 OS << "Frame Objects:\n";
656 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
657 const StackObject &SO = Objects[i];
658 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
659 if (SO.Size == ~0ULL) {
664 OS << "variable sized";
666 OS << "size=" << SO.Size;
667 OS << ", align=" << SO.Alignment;
669 if (i < NumFixedObjects)
671 if (i < NumFixedObjects || SO.SPOffset != -1) {
672 int64_t Off = SO.SPOffset - ValOffset;
673 OS << ", at location [SP";
684 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
685 void MachineFrameInfo::dump(const MachineFunction &MF) const {
690 //===----------------------------------------------------------------------===//
691 // MachineJumpTableInfo implementation
692 //===----------------------------------------------------------------------===//
694 /// Return the size of each entry in the jump table.
695 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
696 // The size of a jump table entry is 4 bytes unless the entry is just the
697 // address of a block, in which case it is the pointer size.
698 switch (getEntryKind()) {
699 case MachineJumpTableInfo::EK_BlockAddress:
700 return TD.getPointerSize();
701 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
703 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
704 case MachineJumpTableInfo::EK_LabelDifference32:
705 case MachineJumpTableInfo::EK_Custom32:
707 case MachineJumpTableInfo::EK_Inline:
710 llvm_unreachable("Unknown jump table encoding!");
713 /// Return the alignment of each entry in the jump table.
714 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
715 // The alignment of a jump table entry is the alignment of int32 unless the
716 // entry is just the address of a block, in which case it is the pointer
718 switch (getEntryKind()) {
719 case MachineJumpTableInfo::EK_BlockAddress:
720 return TD.getPointerABIAlignment();
721 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
722 return TD.getABIIntegerTypeAlignment(64);
723 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
724 case MachineJumpTableInfo::EK_LabelDifference32:
725 case MachineJumpTableInfo::EK_Custom32:
726 return TD.getABIIntegerTypeAlignment(32);
727 case MachineJumpTableInfo::EK_Inline:
730 llvm_unreachable("Unknown jump table encoding!");
733 /// Create a new jump table entry in the jump table info.
734 unsigned MachineJumpTableInfo::createJumpTableIndex(
735 const std::vector<MachineBasicBlock*> &DestBBs) {
736 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
737 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
738 return JumpTables.size()-1;
741 /// If Old is the target of any jump tables, update the jump tables to branch
743 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
744 MachineBasicBlock *New) {
745 assert(Old != New && "Not making a change?");
746 bool MadeChange = false;
747 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
748 ReplaceMBBInJumpTable(i, Old, New);
752 /// If Old is a target of the jump tables, update the jump table to branch to
754 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
755 MachineBasicBlock *Old,
756 MachineBasicBlock *New) {
757 assert(Old != New && "Not making a change?");
758 bool MadeChange = false;
759 MachineJumpTableEntry &JTE = JumpTables[Idx];
760 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
761 if (JTE.MBBs[j] == Old) {
768 void MachineJumpTableInfo::print(raw_ostream &OS) const {
769 if (JumpTables.empty()) return;
771 OS << "Jump Tables:\n";
773 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
774 OS << " jt#" << i << ": ";
775 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
776 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
782 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
783 void MachineJumpTableInfo::dump() const { print(dbgs()); }
787 //===----------------------------------------------------------------------===//
788 // MachineConstantPool implementation
789 //===----------------------------------------------------------------------===//
791 void MachineConstantPoolValue::anchor() { }
793 const DataLayout *MachineConstantPool::getDataLayout() const {
794 return TM.getDataLayout();
797 Type *MachineConstantPoolEntry::getType() const {
798 if (isMachineConstantPoolEntry())
799 return Val.MachineCPVal->getType();
800 return Val.ConstVal->getType();
804 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
805 if (isMachineConstantPoolEntry())
806 return Val.MachineCPVal->getRelocationInfo();
807 return Val.ConstVal->getRelocationInfo();
811 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
813 switch (getRelocationInfo()) {
815 llvm_unreachable("Unknown section kind");
816 case Constant::GlobalRelocations:
817 Kind = SectionKind::getReadOnlyWithRel();
819 case Constant::LocalRelocation:
820 Kind = SectionKind::getReadOnlyWithRelLocal();
822 case Constant::NoRelocation:
823 switch (DL->getTypeAllocSize(getType())) {
825 Kind = SectionKind::getMergeableConst4();
828 Kind = SectionKind::getMergeableConst8();
831 Kind = SectionKind::getMergeableConst16();
834 Kind = SectionKind::getReadOnly();
841 MachineConstantPool::~MachineConstantPool() {
842 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
843 if (Constants[i].isMachineConstantPoolEntry())
844 delete Constants[i].Val.MachineCPVal;
845 for (DenseSet<MachineConstantPoolValue*>::iterator I =
846 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
851 /// Test whether the given two constants can be allocated the same constant pool
853 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
854 const DataLayout *TD) {
855 // Handle the trivial case quickly.
856 if (A == B) return true;
858 // If they have the same type but weren't the same constant, quickly
860 if (A->getType() == B->getType()) return false;
862 // We can't handle structs or arrays.
863 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
864 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
867 // For now, only support constants with the same size.
868 uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
869 if (StoreSize != TD->getTypeStoreSize(B->getType()) || StoreSize > 128)
872 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
874 // Try constant folding a bitcast of both instructions to an integer. If we
875 // get two identical ConstantInt's, then we are good to share them. We use
876 // the constant folding APIs to do this so that we get the benefit of
878 if (isa<PointerType>(A->getType()))
879 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
880 const_cast<Constant *>(A), *TD);
881 else if (A->getType() != IntTy)
882 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
883 const_cast<Constant *>(A), *TD);
884 if (isa<PointerType>(B->getType()))
885 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
886 const_cast<Constant *>(B), *TD);
887 else if (B->getType() != IntTy)
888 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
889 const_cast<Constant *>(B), *TD);
894 /// Create a new entry in the constant pool or return an existing one.
895 /// User must specify the log2 of the minimum required alignment for the object.
896 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
897 unsigned Alignment) {
898 assert(Alignment && "Alignment must be specified!");
899 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
901 // Check to see if we already have this constant.
903 // FIXME, this could be made much more efficient for large constant pools.
904 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
905 if (!Constants[i].isMachineConstantPoolEntry() &&
906 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
908 if ((unsigned)Constants[i].getAlignment() < Alignment)
909 Constants[i].Alignment = Alignment;
913 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
914 return Constants.size()-1;
917 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
918 unsigned Alignment) {
919 assert(Alignment && "Alignment must be specified!");
920 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
922 // Check to see if we already have this constant.
924 // FIXME, this could be made much more efficient for large constant pools.
925 int Idx = V->getExistingMachineCPValue(this, Alignment);
927 MachineCPVsSharingEntries.insert(V);
928 return (unsigned)Idx;
931 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
932 return Constants.size()-1;
935 void MachineConstantPool::print(raw_ostream &OS) const {
936 if (Constants.empty()) return;
938 OS << "Constant Pool:\n";
939 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
940 OS << " cp#" << i << ": ";
941 if (Constants[i].isMachineConstantPoolEntry())
942 Constants[i].Val.MachineCPVal->print(OS);
944 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
945 OS << ", align=" << Constants[i].getAlignment();
950 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
951 void MachineConstantPool::dump() const { print(dbgs()); }