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/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GraphWriter.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetFrameLowering.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "codegen"
45 void MachineFunctionInitializer::anchor() {}
47 //===----------------------------------------------------------------------===//
48 // MachineFunction implementation
49 //===----------------------------------------------------------------------===//
51 // Out-of-line virtual method.
52 MachineFunctionInfo::~MachineFunctionInfo() {}
54 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
55 MBB->getParent()->DeleteMachineBasicBlock(MBB);
58 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
59 unsigned FunctionNum, MachineModuleInfo &mmi)
60 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
62 if (STI->getRegisterInfo())
63 RegInfo = new (Allocator) MachineRegisterInfo(this);
68 FrameInfo = new (Allocator)
69 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
70 STI->getFrameLowering()->isStackRealignable(),
71 !F->hasFnAttribute("no-realign-stack"));
73 if (Fn->hasFnAttribute(Attribute::StackAlignment))
74 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
76 ConstantPool = new (Allocator) MachineConstantPool(TM);
77 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
79 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
80 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
81 Alignment = std::max(Alignment,
82 STI->getTargetLowering()->getPrefFunctionAlignment());
84 FunctionNumber = FunctionNum;
85 JumpTableInfo = nullptr;
88 MachineFunction::~MachineFunction() {
89 // Don't call destructors on MachineInstr and MachineOperand. All of their
90 // memory comes from the BumpPtrAllocator which is about to be purged.
92 // Do call MachineBasicBlock destructors, it contains std::vectors.
93 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
94 I->Insts.clearAndLeakNodesUnsafely();
96 InstructionRecycler.clear(Allocator);
97 OperandRecycler.clear(Allocator);
98 BasicBlockRecycler.clear(Allocator);
100 RegInfo->~MachineRegisterInfo();
101 Allocator.Deallocate(RegInfo);
104 MFInfo->~MachineFunctionInfo();
105 Allocator.Deallocate(MFInfo);
108 FrameInfo->~MachineFrameInfo();
109 Allocator.Deallocate(FrameInfo);
111 ConstantPool->~MachineConstantPool();
112 Allocator.Deallocate(ConstantPool);
115 JumpTableInfo->~MachineJumpTableInfo();
116 Allocator.Deallocate(JumpTableInfo);
120 /// Get the JumpTableInfo for this function.
121 /// If it does not already exist, allocate one.
122 MachineJumpTableInfo *MachineFunction::
123 getOrCreateJumpTableInfo(unsigned EntryKind) {
124 if (JumpTableInfo) return JumpTableInfo;
126 JumpTableInfo = new (Allocator)
127 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
128 return JumpTableInfo;
131 /// Should we be emitting segmented stack stuff for the function
132 bool MachineFunction::shouldSplitStack() {
133 return getFunction()->hasFnAttribute("split-stack");
136 /// This discards all of the MachineBasicBlock numbers and recomputes them.
137 /// This guarantees that the MBB numbers are sequential, dense, and match the
138 /// ordering of the blocks within the function. If a specific MachineBasicBlock
139 /// is specified, only that block and those after it are renumbered.
140 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
141 if (empty()) { MBBNumbering.clear(); return; }
142 MachineFunction::iterator MBBI, E = end();
148 // Figure out the block number this should have.
149 unsigned BlockNo = 0;
151 BlockNo = std::prev(MBBI)->getNumber() + 1;
153 for (; MBBI != E; ++MBBI, ++BlockNo) {
154 if (MBBI->getNumber() != (int)BlockNo) {
155 // Remove use of the old number.
156 if (MBBI->getNumber() != -1) {
157 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
158 "MBB number mismatch!");
159 MBBNumbering[MBBI->getNumber()] = nullptr;
162 // If BlockNo is already taken, set that block's number to -1.
163 if (MBBNumbering[BlockNo])
164 MBBNumbering[BlockNo]->setNumber(-1);
166 MBBNumbering[BlockNo] = MBBI;
167 MBBI->setNumber(BlockNo);
171 // Okay, all the blocks are renumbered. If we have compactified the block
172 // numbering, shrink MBBNumbering now.
173 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
174 MBBNumbering.resize(BlockNo);
177 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
179 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
180 DebugLoc DL, bool NoImp) {
181 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
182 MachineInstr(*this, MCID, DL, NoImp);
185 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
186 /// identical in all ways except the instruction has no parent, prev, or next.
188 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
189 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
190 MachineInstr(*this, *Orig);
193 /// Delete the given MachineInstr.
195 /// This function also serves as the MachineInstr destructor - the real
196 /// ~MachineInstr() destructor must be empty.
198 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
199 // Strip it for parts. The operand array and the MI object itself are
200 // independently recyclable.
202 deallocateOperandArray(MI->CapOperands, MI->Operands);
203 // Don't call ~MachineInstr() which must be trivial anyway because
204 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
206 InstructionRecycler.Deallocate(Allocator, MI);
209 /// Allocate a new MachineBasicBlock. Use this instead of
210 /// `new MachineBasicBlock'.
212 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
213 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
214 MachineBasicBlock(*this, bb);
217 /// Delete the given MachineBasicBlock.
219 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
220 assert(MBB->getParent() == this && "MBB parent mismatch!");
221 MBB->~MachineBasicBlock();
222 BasicBlockRecycler.Deallocate(Allocator, MBB);
226 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
227 uint64_t s, unsigned base_alignment,
228 const AAMDNodes &AAInfo,
229 const MDNode *Ranges) {
230 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
235 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
236 int64_t Offset, uint64_t Size) {
238 return new (Allocator)
239 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
240 MMO->getOffset()+Offset),
241 MMO->getFlags(), Size,
242 MMO->getBaseAlignment());
243 return new (Allocator)
244 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
245 MMO->getOffset()+Offset),
246 MMO->getFlags(), Size,
247 MMO->getBaseAlignment());
250 MachineInstr::mmo_iterator
251 MachineFunction::allocateMemRefsArray(unsigned long Num) {
252 return Allocator.Allocate<MachineMemOperand *>(Num);
255 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
256 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
257 MachineInstr::mmo_iterator End) {
258 // Count the number of load mem refs.
260 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
264 // Allocate a new array and populate it with the load information.
265 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
267 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
268 if ((*I)->isLoad()) {
269 if (!(*I)->isStore())
273 // Clone the MMO and unset the store flag.
274 MachineMemOperand *JustLoad =
275 getMachineMemOperand((*I)->getPointerInfo(),
276 (*I)->getFlags() & ~MachineMemOperand::MOStore,
277 (*I)->getSize(), (*I)->getBaseAlignment(),
279 Result[Index] = JustLoad;
284 return std::make_pair(Result, Result + Num);
287 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
288 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
289 MachineInstr::mmo_iterator End) {
290 // Count the number of load mem refs.
292 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
296 // Allocate a new array and populate it with the store information.
297 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
299 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
300 if ((*I)->isStore()) {
305 // Clone the MMO and unset the load flag.
306 MachineMemOperand *JustStore =
307 getMachineMemOperand((*I)->getPointerInfo(),
308 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
309 (*I)->getSize(), (*I)->getBaseAlignment(),
311 Result[Index] = JustStore;
316 return std::make_pair(Result, Result + Num);
319 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
320 void MachineFunction::dump() const {
325 StringRef MachineFunction::getName() const {
326 assert(getFunction() && "No function!");
327 return getFunction()->getName();
330 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
331 OS << "# Machine code for function " << getName() << ": ";
333 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
334 if (!RegInfo->tracksLiveness())
335 OS << ", not tracking liveness";
339 // Print Frame Information
340 FrameInfo->print(*this, OS);
342 // Print JumpTable Information
344 JumpTableInfo->print(OS);
346 // Print Constant Pool
347 ConstantPool->print(OS);
349 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
351 if (RegInfo && !RegInfo->livein_empty()) {
352 OS << "Function Live Ins: ";
353 for (MachineRegisterInfo::livein_iterator
354 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
355 OS << PrintReg(I->first, TRI);
357 OS << " in " << PrintReg(I->second, TRI);
358 if (std::next(I) != E)
364 for (const auto &BB : *this) {
366 BB.print(OS, Indexes);
369 OS << "\n# End machine code for function " << getName() << ".\n\n";
374 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
376 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
378 static std::string getGraphName(const MachineFunction *F) {
379 return ("CFG for '" + F->getName() + "' function").str();
382 std::string getNodeLabel(const MachineBasicBlock *Node,
383 const MachineFunction *Graph) {
386 raw_string_ostream OSS(OutStr);
389 OSS << "BB#" << Node->getNumber();
390 if (const BasicBlock *BB = Node->getBasicBlock())
391 OSS << ": " << BB->getName();
396 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
398 // Process string output to make it nicer...
399 for (unsigned i = 0; i != OutStr.length(); ++i)
400 if (OutStr[i] == '\n') { // Left justify
402 OutStr.insert(OutStr.begin()+i+1, 'l');
409 void MachineFunction::viewCFG() const
412 ViewGraph(this, "mf" + getName());
414 errs() << "MachineFunction::viewCFG is only available in debug builds on "
415 << "systems with Graphviz or gv!\n";
419 void MachineFunction::viewCFGOnly() const
422 ViewGraph(this, "mf" + getName(), true);
424 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
425 << "systems with Graphviz or gv!\n";
429 /// Add the specified physical register as a live-in value and
430 /// create a corresponding virtual register for it.
431 unsigned MachineFunction::addLiveIn(unsigned PReg,
432 const TargetRegisterClass *RC) {
433 MachineRegisterInfo &MRI = getRegInfo();
434 unsigned VReg = MRI.getLiveInVirtReg(PReg);
436 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
438 // A physical register can be added several times.
439 // Between two calls, the register class of the related virtual register
440 // may have been constrained to match some operation constraints.
441 // In that case, check that the current register class includes the
442 // physical register and is a sub class of the specified RC.
443 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
444 RC->hasSubClassEq(VRegRC))) &&
445 "Register class mismatch!");
448 VReg = MRI.createVirtualRegister(RC);
449 MRI.addLiveIn(PReg, VReg);
453 /// Return the MCSymbol for the specified non-empty jump table.
454 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
455 /// normal 'L' label is returned.
456 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
457 bool isLinkerPrivate) const {
458 const DataLayout *DL = getTarget().getDataLayout();
459 assert(JumpTableInfo && "No jump tables");
460 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
462 const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
463 DL->getPrivateGlobalPrefix();
464 SmallString<60> Name;
465 raw_svector_ostream(Name)
466 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
467 return Ctx.getOrCreateSymbol(Name);
470 /// Return a function-local symbol to represent the PIC base.
471 MCSymbol *MachineFunction::getPICBaseSymbol() const {
472 const DataLayout *DL = getTarget().getDataLayout();
473 return Ctx.getOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
474 Twine(getFunctionNumber())+"$pb");
477 //===----------------------------------------------------------------------===//
478 // MachineFrameInfo implementation
479 //===----------------------------------------------------------------------===//
481 /// Make sure the function is at least Align bytes aligned.
482 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
483 if (!StackRealignable || !RealignOption)
484 assert(Align <= StackAlignment &&
485 "For targets without stack realignment, Align is out of limit!");
486 if (MaxAlignment < Align) MaxAlignment = Align;
489 /// Clamp the alignment if requested and emit a warning.
490 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
491 unsigned StackAlign) {
492 if (!ShouldClamp || Align <= StackAlign)
494 DEBUG(dbgs() << "Warning: requested alignment " << Align
495 << " exceeds the stack alignment " << StackAlign
496 << " when stack realignment is off" << '\n');
500 /// Create a new statically sized stack object, returning a nonnegative
501 /// identifier to represent it.
502 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
503 bool isSS, const AllocaInst *Alloca) {
504 assert(Size != 0 && "Cannot allocate zero size stack objects!");
505 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
506 Alignment, StackAlignment);
507 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
509 int Index = (int)Objects.size() - NumFixedObjects - 1;
510 assert(Index >= 0 && "Bad frame index!");
511 ensureMaxAlignment(Alignment);
515 /// Create a new statically sized stack object that represents a spill slot,
516 /// returning a nonnegative identifier to represent it.
517 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
518 unsigned Alignment) {
519 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
520 Alignment, StackAlignment);
521 CreateStackObject(Size, Alignment, true);
522 int Index = (int)Objects.size() - NumFixedObjects - 1;
523 ensureMaxAlignment(Alignment);
527 /// Notify the MachineFrameInfo object that a variable sized object has been
528 /// created. This must be created whenever a variable sized object is created,
529 /// whether or not the index returned is actually used.
530 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
531 const AllocaInst *Alloca) {
532 HasVarSizedObjects = true;
533 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
534 Alignment, StackAlignment);
535 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
536 ensureMaxAlignment(Alignment);
537 return (int)Objects.size()-NumFixedObjects-1;
540 /// Create a new object at a fixed location on the stack.
541 /// All fixed objects should be created before other objects are created for
542 /// efficiency. By default, fixed objects are immutable. This returns an
543 /// index with a negative value.
544 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
545 bool Immutable, bool isAliased) {
546 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
547 // The alignment of the frame index can be determined from its offset from
548 // the incoming frame position. If the frame object is at offset 32 and
549 // the stack is guaranteed to be 16-byte aligned, then we know that the
550 // object is 16-byte aligned.
551 unsigned Align = MinAlign(SPOffset, StackAlignment);
552 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
554 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
556 /*Alloca*/ nullptr, isAliased));
557 return -++NumFixedObjects;
560 /// Create a spill slot at a fixed location on the stack.
561 /// Returns an index with a negative value.
562 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
564 unsigned Align = MinAlign(SPOffset, StackAlignment);
565 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
567 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
571 /*isAliased*/ false));
572 return -++NumFixedObjects;
575 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
576 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
577 BitVector BV(TRI->getNumRegs());
579 // Before CSI is calculated, no registers are considered pristine. They can be
580 // freely used and PEI will make sure they are saved.
581 if (!isCalleeSavedInfoValid())
584 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
587 // Saved CSRs are not pristine.
588 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
589 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
590 E = CSI.end(); I != E; ++I)
591 BV.reset(I->getReg());
596 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
597 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
598 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
599 unsigned MaxAlign = getMaxAlignment();
602 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
603 // It really should be refactored to share code. Until then, changes
604 // should keep in mind that there's tight coupling between the two.
606 for (int i = getObjectIndexBegin(); i != 0; ++i) {
607 int FixedOff = -getObjectOffset(i);
608 if (FixedOff > Offset) Offset = FixedOff;
610 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
611 if (isDeadObjectIndex(i))
613 Offset += getObjectSize(i);
614 unsigned Align = getObjectAlignment(i);
615 // Adjust to alignment boundary
616 Offset = (Offset+Align-1)/Align*Align;
618 MaxAlign = std::max(Align, MaxAlign);
621 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
622 Offset += getMaxCallFrameSize();
624 // Round up the size to a multiple of the alignment. If the function has
625 // any calls or alloca's, align to the target's StackAlignment value to
626 // ensure that the callee's frame or the alloca data is suitably aligned;
627 // otherwise, for leaf functions, align to the TransientStackAlignment
630 if (adjustsStack() || hasVarSizedObjects() ||
631 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
632 StackAlign = TFI->getStackAlignment();
634 StackAlign = TFI->getTransientStackAlignment();
636 // If the frame pointer is eliminated, all frame offsets will be relative to
637 // SP not FP. Align to MaxAlign so this works.
638 StackAlign = std::max(StackAlign, MaxAlign);
639 unsigned AlignMask = StackAlign - 1;
640 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
642 return (unsigned)Offset;
645 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
646 if (Objects.empty()) return;
648 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
649 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
651 OS << "Frame Objects:\n";
653 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
654 const StackObject &SO = Objects[i];
655 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
656 if (SO.Size == ~0ULL) {
661 OS << "variable sized";
663 OS << "size=" << SO.Size;
664 OS << ", align=" << SO.Alignment;
666 if (i < NumFixedObjects)
668 if (i < NumFixedObjects || SO.SPOffset != -1) {
669 int64_t Off = SO.SPOffset - ValOffset;
670 OS << ", at location [SP";
681 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
682 void MachineFrameInfo::dump(const MachineFunction &MF) const {
687 //===----------------------------------------------------------------------===//
688 // MachineJumpTableInfo implementation
689 //===----------------------------------------------------------------------===//
691 /// Return the size of each entry in the jump table.
692 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
693 // The size of a jump table entry is 4 bytes unless the entry is just the
694 // address of a block, in which case it is the pointer size.
695 switch (getEntryKind()) {
696 case MachineJumpTableInfo::EK_BlockAddress:
697 return TD.getPointerSize();
698 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
700 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
701 case MachineJumpTableInfo::EK_LabelDifference32:
702 case MachineJumpTableInfo::EK_Custom32:
704 case MachineJumpTableInfo::EK_Inline:
707 llvm_unreachable("Unknown jump table encoding!");
710 /// Return the alignment of each entry in the jump table.
711 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
712 // The alignment of a jump table entry is the alignment of int32 unless the
713 // entry is just the address of a block, in which case it is the pointer
715 switch (getEntryKind()) {
716 case MachineJumpTableInfo::EK_BlockAddress:
717 return TD.getPointerABIAlignment();
718 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
719 return TD.getABIIntegerTypeAlignment(64);
720 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
721 case MachineJumpTableInfo::EK_LabelDifference32:
722 case MachineJumpTableInfo::EK_Custom32:
723 return TD.getABIIntegerTypeAlignment(32);
724 case MachineJumpTableInfo::EK_Inline:
727 llvm_unreachable("Unknown jump table encoding!");
730 /// Create a new jump table entry in the jump table info.
731 unsigned MachineJumpTableInfo::createJumpTableIndex(
732 const std::vector<MachineBasicBlock*> &DestBBs) {
733 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
734 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
735 return JumpTables.size()-1;
738 /// If Old is the target of any jump tables, update the jump tables to branch
740 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
741 MachineBasicBlock *New) {
742 assert(Old != New && "Not making a change?");
743 bool MadeChange = false;
744 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
745 ReplaceMBBInJumpTable(i, Old, New);
749 /// If Old is a target of the jump tables, update the jump table to branch to
751 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
752 MachineBasicBlock *Old,
753 MachineBasicBlock *New) {
754 assert(Old != New && "Not making a change?");
755 bool MadeChange = false;
756 MachineJumpTableEntry &JTE = JumpTables[Idx];
757 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
758 if (JTE.MBBs[j] == Old) {
765 void MachineJumpTableInfo::print(raw_ostream &OS) const {
766 if (JumpTables.empty()) return;
768 OS << "Jump Tables:\n";
770 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
771 OS << " jt#" << i << ": ";
772 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
773 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
779 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
780 void MachineJumpTableInfo::dump() const { print(dbgs()); }
784 //===----------------------------------------------------------------------===//
785 // MachineConstantPool implementation
786 //===----------------------------------------------------------------------===//
788 void MachineConstantPoolValue::anchor() { }
790 const DataLayout *MachineConstantPool::getDataLayout() const {
791 return TM.getDataLayout();
794 Type *MachineConstantPoolEntry::getType() const {
795 if (isMachineConstantPoolEntry())
796 return Val.MachineCPVal->getType();
797 return Val.ConstVal->getType();
801 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
802 if (isMachineConstantPoolEntry())
803 return Val.MachineCPVal->getRelocationInfo();
804 return Val.ConstVal->getRelocationInfo();
808 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
810 switch (getRelocationInfo()) {
812 llvm_unreachable("Unknown section kind");
813 case Constant::GlobalRelocations:
814 Kind = SectionKind::getReadOnlyWithRel();
816 case Constant::LocalRelocation:
817 Kind = SectionKind::getReadOnlyWithRelLocal();
819 case Constant::NoRelocation:
820 switch (DL->getTypeAllocSize(getType())) {
822 Kind = SectionKind::getMergeableConst4();
825 Kind = SectionKind::getMergeableConst8();
828 Kind = SectionKind::getMergeableConst16();
831 Kind = SectionKind::getReadOnly();
838 MachineConstantPool::~MachineConstantPool() {
839 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
840 if (Constants[i].isMachineConstantPoolEntry())
841 delete Constants[i].Val.MachineCPVal;
842 for (DenseSet<MachineConstantPoolValue*>::iterator I =
843 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
848 /// Test whether the given two constants can be allocated the same constant pool
850 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
851 const DataLayout *TD) {
852 // Handle the trivial case quickly.
853 if (A == B) return true;
855 // If they have the same type but weren't the same constant, quickly
857 if (A->getType() == B->getType()) return false;
859 // We can't handle structs or arrays.
860 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
861 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
864 // For now, only support constants with the same size.
865 uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
866 if (StoreSize != TD->getTypeStoreSize(B->getType()) || StoreSize > 128)
869 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
871 // Try constant folding a bitcast of both instructions to an integer. If we
872 // get two identical ConstantInt's, then we are good to share them. We use
873 // the constant folding APIs to do this so that we get the benefit of
875 if (isa<PointerType>(A->getType()))
876 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
877 const_cast<Constant *>(A), *TD);
878 else if (A->getType() != IntTy)
879 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
880 const_cast<Constant *>(A), *TD);
881 if (isa<PointerType>(B->getType()))
882 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
883 const_cast<Constant *>(B), *TD);
884 else if (B->getType() != IntTy)
885 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
886 const_cast<Constant *>(B), *TD);
891 /// Create a new entry in the constant pool or return an existing one.
892 /// User must specify the log2 of the minimum required alignment for the object.
893 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
894 unsigned Alignment) {
895 assert(Alignment && "Alignment must be specified!");
896 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
898 // Check to see if we already have this constant.
900 // FIXME, this could be made much more efficient for large constant pools.
901 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
902 if (!Constants[i].isMachineConstantPoolEntry() &&
903 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
905 if ((unsigned)Constants[i].getAlignment() < Alignment)
906 Constants[i].Alignment = Alignment;
910 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
911 return Constants.size()-1;
914 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
915 unsigned Alignment) {
916 assert(Alignment && "Alignment must be specified!");
917 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
919 // Check to see if we already have this constant.
921 // FIXME, this could be made much more efficient for large constant pools.
922 int Idx = V->getExistingMachineCPValue(this, Alignment);
924 MachineCPVsSharingEntries.insert(V);
925 return (unsigned)Idx;
928 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
929 return Constants.size()-1;
932 void MachineConstantPool::print(raw_ostream &OS) const {
933 if (Constants.empty()) return;
935 OS << "Constant Pool:\n";
936 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
937 OS << " cp#" << i << ": ";
938 if (Constants[i].isMachineConstantPoolEntry())
939 Constants[i].Val.MachineCPVal->print(OS);
941 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
942 OS << ", align=" << Constants[i].getAlignment();
947 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
948 void MachineConstantPool::dump() const { print(dbgs()); }