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"
41 //===----------------------------------------------------------------------===//
42 // MachineFunction implementation
43 //===----------------------------------------------------------------------===//
45 // Out of line virtual method.
46 MachineFunctionInfo::~MachineFunctionInfo() {}
48 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
49 MBB->getParent()->DeleteMachineBasicBlock(MBB);
52 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
53 unsigned FunctionNum, MachineModuleInfo &mmi,
55 : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
56 if (TM.getRegisterInfo())
57 RegInfo = new (Allocator) MachineRegisterInfo(TM);
63 new (Allocator) MachineFrameInfo(TM,!F->hasFnAttribute("no-realign-stack"));
65 if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
66 Attribute::StackAlignment))
67 FrameInfo->ensureMaxAlignment(Fn->getAttributes().
68 getStackAlignment(AttributeSet::FunctionIndex));
70 ConstantPool = new (Allocator) MachineConstantPool(TM);
71 Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
73 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
74 if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
75 Attribute::OptimizeForSize))
76 Alignment = std::max(Alignment,
77 TM.getTargetLowering()->getPrefFunctionAlignment());
79 FunctionNumber = FunctionNum;
83 MachineFunction::~MachineFunction() {
84 // Don't call destructors on MachineInstr and MachineOperand. All of their
85 // memory comes from the BumpPtrAllocator which is about to be purged.
87 // Do call MachineBasicBlock destructors, it contains std::vectors.
88 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
89 I->Insts.clearAndLeakNodesUnsafely();
91 InstructionRecycler.clear(Allocator);
92 OperandRecycler.clear(Allocator);
93 BasicBlockRecycler.clear(Allocator);
95 RegInfo->~MachineRegisterInfo();
96 Allocator.Deallocate(RegInfo);
99 MFInfo->~MachineFunctionInfo();
100 Allocator.Deallocate(MFInfo);
103 FrameInfo->~MachineFrameInfo();
104 Allocator.Deallocate(FrameInfo);
106 ConstantPool->~MachineConstantPool();
107 Allocator.Deallocate(ConstantPool);
110 JumpTableInfo->~MachineJumpTableInfo();
111 Allocator.Deallocate(JumpTableInfo);
115 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
116 /// does already exist, allocate one.
117 MachineJumpTableInfo *MachineFunction::
118 getOrCreateJumpTableInfo(unsigned EntryKind) {
119 if (JumpTableInfo) return JumpTableInfo;
121 JumpTableInfo = new (Allocator)
122 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
123 return JumpTableInfo;
126 /// Should we be emitting segmented stack stuff for the function
127 bool MachineFunction::shouldSplitStack() {
128 return getFunction()->hasFnAttribute("split-stack");
131 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
132 /// recomputes them. This guarantees that the MBB numbers are sequential,
133 /// dense, and match the ordering of the blocks within the function. If a
134 /// specific MachineBasicBlock is specified, only that block and those after
135 /// it are renumbered.
136 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
137 if (empty()) { MBBNumbering.clear(); return; }
138 MachineFunction::iterator MBBI, E = end();
144 // Figure out the block number this should have.
145 unsigned BlockNo = 0;
147 BlockNo = std::prev(MBBI)->getNumber() + 1;
149 for (; MBBI != E; ++MBBI, ++BlockNo) {
150 if (MBBI->getNumber() != (int)BlockNo) {
151 // Remove use of the old number.
152 if (MBBI->getNumber() != -1) {
153 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
154 "MBB number mismatch!");
155 MBBNumbering[MBBI->getNumber()] = 0;
158 // If BlockNo is already taken, set that block's number to -1.
159 if (MBBNumbering[BlockNo])
160 MBBNumbering[BlockNo]->setNumber(-1);
162 MBBNumbering[BlockNo] = MBBI;
163 MBBI->setNumber(BlockNo);
167 // Okay, all the blocks are renumbered. If we have compactified the block
168 // numbering, shrink MBBNumbering now.
169 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
170 MBBNumbering.resize(BlockNo);
173 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
174 /// of `new MachineInstr'.
177 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
178 DebugLoc DL, bool NoImp) {
179 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
180 MachineInstr(*this, MCID, DL, NoImp);
183 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
184 /// 'Orig' instruction, identical in all ways except the instruction
185 /// has no parent, prev, or next.
188 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
189 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
190 MachineInstr(*this, *Orig);
193 /// DeleteMachineInstr - 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 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
210 /// instead of `new MachineBasicBlock'.
213 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
214 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
215 MachineBasicBlock(*this, bb);
218 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
221 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
222 assert(MBB->getParent() == this && "MBB parent mismatch!");
223 MBB->~MachineBasicBlock();
224 BasicBlockRecycler.Deallocate(Allocator, MBB);
228 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
229 uint64_t s, unsigned base_alignment,
230 const MDNode *TBAAInfo,
231 const MDNode *Ranges) {
232 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
237 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
238 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(), 0);
246 MachineInstr::mmo_iterator
247 MachineFunction::allocateMemRefsArray(unsigned long Num) {
248 return Allocator.Allocate<MachineMemOperand *>(Num);
251 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
252 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
253 MachineInstr::mmo_iterator End) {
254 // Count the number of load mem refs.
256 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
260 // Allocate a new array and populate it with the load information.
261 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
263 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
264 if ((*I)->isLoad()) {
265 if (!(*I)->isStore())
269 // Clone the MMO and unset the store flag.
270 MachineMemOperand *JustLoad =
271 getMachineMemOperand((*I)->getPointerInfo(),
272 (*I)->getFlags() & ~MachineMemOperand::MOStore,
273 (*I)->getSize(), (*I)->getBaseAlignment(),
274 (*I)->getTBAAInfo());
275 Result[Index] = JustLoad;
280 return std::make_pair(Result, Result + Num);
283 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
284 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
285 MachineInstr::mmo_iterator End) {
286 // Count the number of load mem refs.
288 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
292 // Allocate a new array and populate it with the store information.
293 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
295 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
296 if ((*I)->isStore()) {
301 // Clone the MMO and unset the load flag.
302 MachineMemOperand *JustStore =
303 getMachineMemOperand((*I)->getPointerInfo(),
304 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
305 (*I)->getSize(), (*I)->getBaseAlignment(),
306 (*I)->getTBAAInfo());
307 Result[Index] = JustStore;
312 return std::make_pair(Result, Result + Num);
315 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
316 void MachineFunction::dump() const {
321 StringRef MachineFunction::getName() const {
322 assert(getFunction() && "No function!");
323 return getFunction()->getName();
326 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
327 OS << "# Machine code for function " << getName() << ": ";
329 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
330 if (!RegInfo->tracksLiveness())
331 OS << ", not tracking liveness";
335 // Print Frame Information
336 FrameInfo->print(*this, OS);
338 // Print JumpTable Information
340 JumpTableInfo->print(OS);
342 // Print Constant Pool
343 ConstantPool->print(OS);
345 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
347 if (RegInfo && !RegInfo->livein_empty()) {
348 OS << "Function Live Ins: ";
349 for (MachineRegisterInfo::livein_iterator
350 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
351 OS << PrintReg(I->first, TRI);
353 OS << " in " << PrintReg(I->second, TRI);
354 if (std::next(I) != E)
360 for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
362 BB->print(OS, Indexes);
365 OS << "\n# End machine code for function " << getName() << ".\n\n";
370 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
372 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
374 static std::string getGraphName(const MachineFunction *F) {
375 return "CFG for '" + F->getName().str() + "' function";
378 std::string getNodeLabel(const MachineBasicBlock *Node,
379 const MachineFunction *Graph) {
382 raw_string_ostream OSS(OutStr);
385 OSS << "BB#" << Node->getNumber();
386 if (const BasicBlock *BB = Node->getBasicBlock())
387 OSS << ": " << BB->getName();
392 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
394 // Process string output to make it nicer...
395 for (unsigned i = 0; i != OutStr.length(); ++i)
396 if (OutStr[i] == '\n') { // Left justify
398 OutStr.insert(OutStr.begin()+i+1, 'l');
405 void MachineFunction::viewCFG() const
408 ViewGraph(this, "mf" + getName());
410 errs() << "MachineFunction::viewCFG is only available in debug builds on "
411 << "systems with Graphviz or gv!\n";
415 void MachineFunction::viewCFGOnly() const
418 ViewGraph(this, "mf" + getName(), true);
420 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
421 << "systems with Graphviz or gv!\n";
425 /// addLiveIn - Add the specified physical register as a live-in value and
426 /// create a corresponding virtual register for it.
427 unsigned MachineFunction::addLiveIn(unsigned PReg,
428 const TargetRegisterClass *RC) {
429 MachineRegisterInfo &MRI = getRegInfo();
430 unsigned VReg = MRI.getLiveInVirtReg(PReg);
432 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
434 // A physical register can be added several times.
435 // Between two calls, the register class of the related virtual register
436 // may have been constrained to match some operation constraints.
437 // In that case, check that the current register class includes the
438 // physical register and is a sub class of the specified RC.
439 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
440 RC->hasSubClassEq(VRegRC))) &&
441 "Register class mismatch!");
444 VReg = MRI.createVirtualRegister(RC);
445 MRI.addLiveIn(PReg, VReg);
449 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
450 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
451 /// normal 'L' label is returned.
452 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
453 bool isLinkerPrivate) const {
454 const DataLayout *DL = getTarget().getDataLayout();
455 assert(JumpTableInfo && "No jump tables");
456 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
458 const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
459 DL->getPrivateGlobalPrefix();
460 SmallString<60> Name;
461 raw_svector_ostream(Name)
462 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
463 return Ctx.GetOrCreateSymbol(Name.str());
466 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
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 const TargetFrameLowering *MachineFrameInfo::getFrameLowering() const {
479 return TM.getFrameLowering();
482 /// ensureMaxAlignment - Make sure the function is at least Align bytes
484 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
485 if (!getFrameLowering()->isStackRealignable() || !RealignOption)
486 assert(Align <= getFrameLowering()->getStackAlignment() &&
487 "For targets without stack realignment, Align is out of limit!");
488 if (MaxAlignment < Align) MaxAlignment = Align;
491 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
492 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
493 unsigned StackAlign) {
494 if (!ShouldClamp || Align <= StackAlign)
496 DEBUG(dbgs() << "Warning: requested alignment " << Align
497 << " exceeds the stack alignment " << StackAlign
498 << " when stack realignment is off" << '\n');
502 /// CreateStackObject - Create a new statically sized stack object, returning
503 /// a nonnegative 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!");
509 clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
511 Alignment, getFrameLowering()->getStackAlignment());
512 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca));
513 int Index = (int)Objects.size() - NumFixedObjects - 1;
514 assert(Index >= 0 && "Bad frame index!");
515 ensureMaxAlignment(Alignment);
519 /// CreateSpillStackObject - Create a new statically sized stack object that
520 /// represents a spill slot, returning a nonnegative identifier to represent
523 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
524 unsigned Alignment) {
526 clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
528 Alignment, getFrameLowering()->getStackAlignment());
529 CreateStackObject(Size, Alignment, true);
530 int Index = (int)Objects.size() - NumFixedObjects - 1;
531 ensureMaxAlignment(Alignment);
535 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
536 /// variable sized object has been created. This must be created whenever a
537 /// variable sized object is created, whether or not the index returned is
540 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
541 const AllocaInst *Alloca) {
542 HasVarSizedObjects = true;
544 clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
546 Alignment, getFrameLowering()->getStackAlignment());
547 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca));
548 ensureMaxAlignment(Alignment);
549 return (int)Objects.size()-NumFixedObjects-1;
552 /// CreateFixedObject - Create a new object at a fixed location on the stack.
553 /// All fixed objects should be created before other objects are created for
554 /// efficiency. By default, fixed objects are immutable. This returns an
555 /// index with a negative value.
557 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
559 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
560 // The alignment of the frame index can be determined from its offset from
561 // the incoming frame position. If the frame object is at offset 32 and
562 // the stack is guaranteed to be 16-byte aligned, then we know that the
563 // object is 16-byte aligned.
564 unsigned StackAlign = getFrameLowering()->getStackAlignment();
565 unsigned Align = MinAlign(SPOffset, StackAlign);
567 clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
569 Align, getFrameLowering()->getStackAlignment());
570 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
573 return -++NumFixedObjects;
578 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
579 assert(MBB && "MBB must be valid");
580 const MachineFunction *MF = MBB->getParent();
581 assert(MF && "MBB must be part of a MachineFunction");
582 const TargetMachine &TM = MF->getTarget();
583 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
584 BitVector BV(TRI->getNumRegs());
586 // Before CSI is calculated, no registers are considered pristine. They can be
587 // freely used and PEI will make sure they are saved.
588 if (!isCalleeSavedInfoValid())
591 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
594 // The entry MBB always has all CSRs pristine.
595 if (MBB == &MF->front())
598 // On other MBBs the saved CSRs are not pristine.
599 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
600 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
601 E = CSI.end(); I != E; ++I)
602 BV.reset(I->getReg());
607 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
608 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
609 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
610 unsigned MaxAlign = getMaxAlignment();
613 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
614 // It really should be refactored to share code. Until then, changes
615 // should keep in mind that there's tight coupling between the two.
617 for (int i = getObjectIndexBegin(); i != 0; ++i) {
618 int FixedOff = -getObjectOffset(i);
619 if (FixedOff > Offset) Offset = FixedOff;
621 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
622 if (isDeadObjectIndex(i))
624 Offset += getObjectSize(i);
625 unsigned Align = getObjectAlignment(i);
626 // Adjust to alignment boundary
627 Offset = (Offset+Align-1)/Align*Align;
629 MaxAlign = std::max(Align, MaxAlign);
632 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
633 Offset += getMaxCallFrameSize();
635 // Round up the size to a multiple of the alignment. If the function has
636 // any calls or alloca's, align to the target's StackAlignment value to
637 // ensure that the callee's frame or the alloca data is suitably aligned;
638 // otherwise, for leaf functions, align to the TransientStackAlignment
641 if (adjustsStack() || hasVarSizedObjects() ||
642 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
643 StackAlign = TFI->getStackAlignment();
645 StackAlign = TFI->getTransientStackAlignment();
647 // If the frame pointer is eliminated, all frame offsets will be relative to
648 // SP not FP. Align to MaxAlign so this works.
649 StackAlign = std::max(StackAlign, MaxAlign);
650 unsigned AlignMask = StackAlign - 1;
651 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
653 return (unsigned)Offset;
656 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
657 if (Objects.empty()) return;
659 const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
660 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
662 OS << "Frame Objects:\n";
664 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
665 const StackObject &SO = Objects[i];
666 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
667 if (SO.Size == ~0ULL) {
672 OS << "variable sized";
674 OS << "size=" << SO.Size;
675 OS << ", align=" << SO.Alignment;
677 if (i < NumFixedObjects)
679 if (i < NumFixedObjects || SO.SPOffset != -1) {
680 int64_t Off = SO.SPOffset - ValOffset;
681 OS << ", at location [SP";
692 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
693 void MachineFrameInfo::dump(const MachineFunction &MF) const {
698 //===----------------------------------------------------------------------===//
699 // MachineJumpTableInfo implementation
700 //===----------------------------------------------------------------------===//
702 /// getEntrySize - Return the size of each entry in the jump table.
703 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
704 // The size of a jump table entry is 4 bytes unless the entry is just the
705 // address of a block, in which case it is the pointer size.
706 switch (getEntryKind()) {
707 case MachineJumpTableInfo::EK_BlockAddress:
708 return TD.getPointerSize();
709 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
711 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
712 case MachineJumpTableInfo::EK_LabelDifference32:
713 case MachineJumpTableInfo::EK_Custom32:
715 case MachineJumpTableInfo::EK_Inline:
718 llvm_unreachable("Unknown jump table encoding!");
721 /// getEntryAlignment - Return the alignment of each entry in the jump table.
722 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
723 // The alignment of a jump table entry is the alignment of int32 unless the
724 // entry is just the address of a block, in which case it is the pointer
726 switch (getEntryKind()) {
727 case MachineJumpTableInfo::EK_BlockAddress:
728 return TD.getPointerABIAlignment();
729 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
730 return TD.getABIIntegerTypeAlignment(64);
731 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
732 case MachineJumpTableInfo::EK_LabelDifference32:
733 case MachineJumpTableInfo::EK_Custom32:
734 return TD.getABIIntegerTypeAlignment(32);
735 case MachineJumpTableInfo::EK_Inline:
738 llvm_unreachable("Unknown jump table encoding!");
741 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
743 unsigned MachineJumpTableInfo::createJumpTableIndex(
744 const std::vector<MachineBasicBlock*> &DestBBs) {
745 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
746 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
747 return JumpTables.size()-1;
750 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
751 /// the jump tables to branch to New instead.
752 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
753 MachineBasicBlock *New) {
754 assert(Old != New && "Not making a change?");
755 bool MadeChange = false;
756 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
757 ReplaceMBBInJumpTable(i, Old, New);
761 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
762 /// the jump table to branch to New instead.
763 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
764 MachineBasicBlock *Old,
765 MachineBasicBlock *New) {
766 assert(Old != New && "Not making a change?");
767 bool MadeChange = false;
768 MachineJumpTableEntry &JTE = JumpTables[Idx];
769 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
770 if (JTE.MBBs[j] == Old) {
777 void MachineJumpTableInfo::print(raw_ostream &OS) const {
778 if (JumpTables.empty()) return;
780 OS << "Jump Tables:\n";
782 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
783 OS << " jt#" << i << ": ";
784 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
785 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
791 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
792 void MachineJumpTableInfo::dump() const { print(dbgs()); }
796 //===----------------------------------------------------------------------===//
797 // MachineConstantPool implementation
798 //===----------------------------------------------------------------------===//
800 void MachineConstantPoolValue::anchor() { }
802 const DataLayout *MachineConstantPool::getDataLayout() const {
803 return TM.getDataLayout();
806 Type *MachineConstantPoolEntry::getType() const {
807 if (isMachineConstantPoolEntry())
808 return Val.MachineCPVal->getType();
809 return Val.ConstVal->getType();
813 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
814 if (isMachineConstantPoolEntry())
815 return Val.MachineCPVal->getRelocationInfo();
816 return Val.ConstVal->getRelocationInfo();
819 MachineConstantPool::~MachineConstantPool() {
820 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
821 if (Constants[i].isMachineConstantPoolEntry())
822 delete Constants[i].Val.MachineCPVal;
823 for (DenseSet<MachineConstantPoolValue*>::iterator I =
824 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
829 /// CanShareConstantPoolEntry - Test whether the given two constants
830 /// can be allocated the same constant pool entry.
831 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
832 const DataLayout *TD) {
833 // Handle the trivial case quickly.
834 if (A == B) return true;
836 // If they have the same type but weren't the same constant, quickly
838 if (A->getType() == B->getType()) return false;
840 // We can't handle structs or arrays.
841 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
842 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
845 // For now, only support constants with the same size.
846 uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
847 if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
851 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
853 // Try constant folding a bitcast of both instructions to an integer. If we
854 // get two identical ConstantInt's, then we are good to share them. We use
855 // the constant folding APIs to do this so that we get the benefit of
857 if (isa<PointerType>(A->getType()))
858 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
859 const_cast<Constant*>(A), TD);
860 else if (A->getType() != IntTy)
861 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
862 const_cast<Constant*>(A), TD);
863 if (isa<PointerType>(B->getType()))
864 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
865 const_cast<Constant*>(B), TD);
866 else if (B->getType() != IntTy)
867 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
868 const_cast<Constant*>(B), TD);
873 /// getConstantPoolIndex - Create a new entry in the constant pool or return
874 /// an existing one. User must specify the log2 of the minimum required
875 /// alignment for the object.
877 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
878 unsigned Alignment) {
879 assert(Alignment && "Alignment must be specified!");
880 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
882 // Check to see if we already have this constant.
884 // FIXME, this could be made much more efficient for large constant pools.
885 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
886 if (!Constants[i].isMachineConstantPoolEntry() &&
887 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
889 if ((unsigned)Constants[i].getAlignment() < Alignment)
890 Constants[i].Alignment = Alignment;
894 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
895 return Constants.size()-1;
898 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
899 unsigned Alignment) {
900 assert(Alignment && "Alignment must be specified!");
901 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
903 // Check to see if we already have this constant.
905 // FIXME, this could be made much more efficient for large constant pools.
906 int Idx = V->getExistingMachineCPValue(this, Alignment);
908 MachineCPVsSharingEntries.insert(V);
909 return (unsigned)Idx;
912 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
913 return Constants.size()-1;
916 void MachineConstantPool::print(raw_ostream &OS) const {
917 if (Constants.empty()) return;
919 OS << "Constant Pool:\n";
920 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
921 OS << " cp#" << i << ": ";
922 if (Constants[i].isMachineConstantPoolEntry())
923 Constants[i].Val.MachineCPVal->print(OS);
925 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
926 OS << ", align=" << Constants[i].getAlignment();
931 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
932 void MachineConstantPool::dump() const { print(dbgs()); }