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/Analysis/LibCallSemantics.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionInitializer.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/CodeGen/WinEHFuncInfo.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ModuleSlotTracker.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
48 #define DEBUG_TYPE "codegen"
50 void MachineFunctionInitializer::anchor() {}
52 //===----------------------------------------------------------------------===//
53 // MachineFunction implementation
54 //===----------------------------------------------------------------------===//
56 // Out-of-line virtual method.
57 MachineFunctionInfo::~MachineFunctionInfo() {}
59 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
60 MBB->getParent()->DeleteMachineBasicBlock(MBB);
63 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
64 unsigned FunctionNum, MachineModuleInfo &mmi)
65 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
67 if (STI->getRegisterInfo())
68 RegInfo = new (Allocator) MachineRegisterInfo(this);
73 FrameInfo = new (Allocator)
74 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
75 STI->getFrameLowering()->isStackRealignable(),
76 !F->hasFnAttribute("no-realign-stack"));
78 if (Fn->hasFnAttribute(Attribute::StackAlignment))
79 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
81 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
82 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
84 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
85 // FIXME: Use Function::optForSize().
86 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
87 Alignment = std::max(Alignment,
88 STI->getTargetLowering()->getPrefFunctionAlignment());
90 FunctionNumber = FunctionNum;
91 JumpTableInfo = nullptr;
93 if (isFuncletEHPersonality(classifyEHPersonality(
94 F->hasPersonalityFn() ? F->getPersonalityFn() : nullptr))) {
95 WinEHInfo = new (Allocator) WinEHFuncInfo();
98 assert(TM.isCompatibleDataLayout(getDataLayout()) &&
99 "Can't create a MachineFunction using a Module with a "
100 "Target-incompatible DataLayout attached\n");
102 PSVManager = llvm::make_unique<PseudoSourceValueManager>();
105 MachineFunction::~MachineFunction() {
106 // Don't call destructors on MachineInstr and MachineOperand. All of their
107 // memory comes from the BumpPtrAllocator which is about to be purged.
109 // Do call MachineBasicBlock destructors, it contains std::vectors.
110 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
111 I->Insts.clearAndLeakNodesUnsafely();
113 InstructionRecycler.clear(Allocator);
114 OperandRecycler.clear(Allocator);
115 BasicBlockRecycler.clear(Allocator);
117 RegInfo->~MachineRegisterInfo();
118 Allocator.Deallocate(RegInfo);
121 MFInfo->~MachineFunctionInfo();
122 Allocator.Deallocate(MFInfo);
125 FrameInfo->~MachineFrameInfo();
126 Allocator.Deallocate(FrameInfo);
128 ConstantPool->~MachineConstantPool();
129 Allocator.Deallocate(ConstantPool);
132 JumpTableInfo->~MachineJumpTableInfo();
133 Allocator.Deallocate(JumpTableInfo);
137 WinEHInfo->~WinEHFuncInfo();
138 Allocator.Deallocate(WinEHInfo);
142 const DataLayout &MachineFunction::getDataLayout() const {
143 return Fn->getParent()->getDataLayout();
146 /// Get the JumpTableInfo for this function.
147 /// If it does not already exist, allocate one.
148 MachineJumpTableInfo *MachineFunction::
149 getOrCreateJumpTableInfo(unsigned EntryKind) {
150 if (JumpTableInfo) return JumpTableInfo;
152 JumpTableInfo = new (Allocator)
153 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
154 return JumpTableInfo;
157 /// Should we be emitting segmented stack stuff for the function
158 bool MachineFunction::shouldSplitStack() {
159 return getFunction()->hasFnAttribute("split-stack");
162 /// This discards all of the MachineBasicBlock numbers and recomputes them.
163 /// This guarantees that the MBB numbers are sequential, dense, and match the
164 /// ordering of the blocks within the function. If a specific MachineBasicBlock
165 /// is specified, only that block and those after it are renumbered.
166 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
167 if (empty()) { MBBNumbering.clear(); return; }
168 MachineFunction::iterator MBBI, E = end();
172 MBBI = MBB->getIterator();
174 // Figure out the block number this should have.
175 unsigned BlockNo = 0;
177 BlockNo = std::prev(MBBI)->getNumber() + 1;
179 for (; MBBI != E; ++MBBI, ++BlockNo) {
180 if (MBBI->getNumber() != (int)BlockNo) {
181 // Remove use of the old number.
182 if (MBBI->getNumber() != -1) {
183 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
184 "MBB number mismatch!");
185 MBBNumbering[MBBI->getNumber()] = nullptr;
188 // If BlockNo is already taken, set that block's number to -1.
189 if (MBBNumbering[BlockNo])
190 MBBNumbering[BlockNo]->setNumber(-1);
192 MBBNumbering[BlockNo] = &*MBBI;
193 MBBI->setNumber(BlockNo);
197 // Okay, all the blocks are renumbered. If we have compactified the block
198 // numbering, shrink MBBNumbering now.
199 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
200 MBBNumbering.resize(BlockNo);
203 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
205 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
206 DebugLoc DL, bool NoImp) {
207 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
208 MachineInstr(*this, MCID, DL, NoImp);
211 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
212 /// identical in all ways except the instruction has no parent, prev, or next.
214 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
215 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
216 MachineInstr(*this, *Orig);
219 /// Delete the given MachineInstr.
221 /// This function also serves as the MachineInstr destructor - the real
222 /// ~MachineInstr() destructor must be empty.
224 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
225 // Strip it for parts. The operand array and the MI object itself are
226 // independently recyclable.
228 deallocateOperandArray(MI->CapOperands, MI->Operands);
229 // Don't call ~MachineInstr() which must be trivial anyway because
230 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
232 InstructionRecycler.Deallocate(Allocator, MI);
235 /// Allocate a new MachineBasicBlock. Use this instead of
236 /// `new MachineBasicBlock'.
238 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
239 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
240 MachineBasicBlock(*this, bb);
243 /// Delete the given MachineBasicBlock.
245 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
246 assert(MBB->getParent() == this && "MBB parent mismatch!");
247 MBB->~MachineBasicBlock();
248 BasicBlockRecycler.Deallocate(Allocator, MBB);
252 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
253 uint64_t s, unsigned base_alignment,
254 const AAMDNodes &AAInfo,
255 const MDNode *Ranges) {
256 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
261 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
262 int64_t Offset, uint64_t Size) {
264 return new (Allocator)
265 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
266 MMO->getOffset()+Offset),
267 MMO->getFlags(), Size,
268 MMO->getBaseAlignment());
269 return new (Allocator)
270 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
271 MMO->getOffset()+Offset),
272 MMO->getFlags(), Size,
273 MMO->getBaseAlignment());
276 MachineInstr::mmo_iterator
277 MachineFunction::allocateMemRefsArray(unsigned long Num) {
278 return Allocator.Allocate<MachineMemOperand *>(Num);
281 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
282 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
283 MachineInstr::mmo_iterator End) {
284 // Count the number of load mem refs.
286 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
290 // Allocate a new array and populate it with the load information.
291 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
293 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
294 if ((*I)->isLoad()) {
295 if (!(*I)->isStore())
299 // Clone the MMO and unset the store flag.
300 MachineMemOperand *JustLoad =
301 getMachineMemOperand((*I)->getPointerInfo(),
302 (*I)->getFlags() & ~MachineMemOperand::MOStore,
303 (*I)->getSize(), (*I)->getBaseAlignment(),
305 Result[Index] = JustLoad;
310 return std::make_pair(Result, Result + Num);
313 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
314 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
315 MachineInstr::mmo_iterator End) {
316 // Count the number of load mem refs.
318 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
322 // Allocate a new array and populate it with the store information.
323 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
325 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
326 if ((*I)->isStore()) {
331 // Clone the MMO and unset the load flag.
332 MachineMemOperand *JustStore =
333 getMachineMemOperand((*I)->getPointerInfo(),
334 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
335 (*I)->getSize(), (*I)->getBaseAlignment(),
337 Result[Index] = JustStore;
342 return std::make_pair(Result, Result + Num);
345 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
346 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
347 std::copy(Name.begin(), Name.end(), Dest);
348 Dest[Name.size()] = 0;
352 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
353 void MachineFunction::dump() const {
358 StringRef MachineFunction::getName() const {
359 assert(getFunction() && "No function!");
360 return getFunction()->getName();
363 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
364 OS << "# Machine code for function " << getName() << ": ";
366 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
367 if (!RegInfo->tracksLiveness())
368 OS << ", not tracking liveness";
372 // Print Frame Information
373 FrameInfo->print(*this, OS);
375 // Print JumpTable Information
377 JumpTableInfo->print(OS);
379 // Print Constant Pool
380 ConstantPool->print(OS);
382 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
384 if (RegInfo && !RegInfo->livein_empty()) {
385 OS << "Function Live Ins: ";
386 for (MachineRegisterInfo::livein_iterator
387 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
388 OS << PrintReg(I->first, TRI);
390 OS << " in " << PrintReg(I->second, TRI);
391 if (std::next(I) != E)
397 ModuleSlotTracker MST(getFunction()->getParent());
398 MST.incorporateFunction(*getFunction());
399 for (const auto &BB : *this) {
401 BB.print(OS, MST, Indexes);
404 OS << "\n# End machine code for function " << getName() << ".\n\n";
409 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
411 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
413 static std::string getGraphName(const MachineFunction *F) {
414 return ("CFG for '" + F->getName() + "' function").str();
417 std::string getNodeLabel(const MachineBasicBlock *Node,
418 const MachineFunction *Graph) {
421 raw_string_ostream OSS(OutStr);
424 OSS << "BB#" << Node->getNumber();
425 if (const BasicBlock *BB = Node->getBasicBlock())
426 OSS << ": " << BB->getName();
431 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
433 // Process string output to make it nicer...
434 for (unsigned i = 0; i != OutStr.length(); ++i)
435 if (OutStr[i] == '\n') { // Left justify
437 OutStr.insert(OutStr.begin()+i+1, 'l');
444 void MachineFunction::viewCFG() const
447 ViewGraph(this, "mf" + getName());
449 errs() << "MachineFunction::viewCFG is only available in debug builds on "
450 << "systems with Graphviz or gv!\n";
454 void MachineFunction::viewCFGOnly() const
457 ViewGraph(this, "mf" + getName(), true);
459 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
460 << "systems with Graphviz or gv!\n";
464 /// Add the specified physical register as a live-in value and
465 /// create a corresponding virtual register for it.
466 unsigned MachineFunction::addLiveIn(unsigned PReg,
467 const TargetRegisterClass *RC) {
468 MachineRegisterInfo &MRI = getRegInfo();
469 unsigned VReg = MRI.getLiveInVirtReg(PReg);
471 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
473 // A physical register can be added several times.
474 // Between two calls, the register class of the related virtual register
475 // may have been constrained to match some operation constraints.
476 // In that case, check that the current register class includes the
477 // physical register and is a sub class of the specified RC.
478 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
479 RC->hasSubClassEq(VRegRC))) &&
480 "Register class mismatch!");
483 VReg = MRI.createVirtualRegister(RC);
484 MRI.addLiveIn(PReg, VReg);
488 /// Return the MCSymbol for the specified non-empty jump table.
489 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
490 /// normal 'L' label is returned.
491 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
492 bool isLinkerPrivate) const {
493 const DataLayout &DL = getDataLayout();
494 assert(JumpTableInfo && "No jump tables");
495 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
497 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
498 : DL.getPrivateGlobalPrefix();
499 SmallString<60> Name;
500 raw_svector_ostream(Name)
501 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
502 return Ctx.getOrCreateSymbol(Name);
505 /// Return a function-local symbol to represent the PIC base.
506 MCSymbol *MachineFunction::getPICBaseSymbol() const {
507 const DataLayout &DL = getDataLayout();
508 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
509 Twine(getFunctionNumber()) + "$pb");
512 //===----------------------------------------------------------------------===//
513 // MachineFrameInfo implementation
514 //===----------------------------------------------------------------------===//
516 /// Make sure the function is at least Align bytes aligned.
517 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
518 if (!StackRealignable || !RealignOption)
519 assert(Align <= StackAlignment &&
520 "For targets without stack realignment, Align is out of limit!");
521 if (MaxAlignment < Align) MaxAlignment = Align;
524 /// Clamp the alignment if requested and emit a warning.
525 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
526 unsigned StackAlign) {
527 if (!ShouldClamp || Align <= StackAlign)
529 DEBUG(dbgs() << "Warning: requested alignment " << Align
530 << " exceeds the stack alignment " << StackAlign
531 << " when stack realignment is off" << '\n');
535 /// Create a new statically sized stack object, returning a nonnegative
536 /// identifier to represent it.
537 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
538 bool isSS, const AllocaInst *Alloca) {
539 assert(Size != 0 && "Cannot allocate zero size stack objects!");
540 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
541 Alignment, StackAlignment);
542 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
544 int Index = (int)Objects.size() - NumFixedObjects - 1;
545 assert(Index >= 0 && "Bad frame index!");
546 ensureMaxAlignment(Alignment);
550 /// Create a new statically sized stack object that represents a spill slot,
551 /// returning a nonnegative identifier to represent it.
552 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
553 unsigned Alignment) {
554 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
555 Alignment, StackAlignment);
556 CreateStackObject(Size, Alignment, true);
557 int Index = (int)Objects.size() - NumFixedObjects - 1;
558 ensureMaxAlignment(Alignment);
562 /// Notify the MachineFrameInfo object that a variable sized object has been
563 /// created. This must be created whenever a variable sized object is created,
564 /// whether or not the index returned is actually used.
565 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
566 const AllocaInst *Alloca) {
567 HasVarSizedObjects = true;
568 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
569 Alignment, StackAlignment);
570 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
571 ensureMaxAlignment(Alignment);
572 return (int)Objects.size()-NumFixedObjects-1;
575 /// Create a new object at a fixed location on the stack.
576 /// All fixed objects should be created before other objects are created for
577 /// efficiency. By default, fixed objects are immutable. This returns an
578 /// index with a negative value.
579 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
580 bool Immutable, bool isAliased) {
581 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
582 // The alignment of the frame index can be determined from its offset from
583 // the incoming frame position. If the frame object is at offset 32 and
584 // the stack is guaranteed to be 16-byte aligned, then we know that the
585 // object is 16-byte aligned.
586 unsigned Align = MinAlign(SPOffset, StackAlignment);
587 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
589 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
591 /*Alloca*/ nullptr, isAliased));
592 return -++NumFixedObjects;
595 /// Create a spill slot at a fixed location on the stack.
596 /// Returns an index with a negative value.
597 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
599 unsigned Align = MinAlign(SPOffset, StackAlignment);
600 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
602 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
606 /*isAliased*/ false));
607 return -++NumFixedObjects;
610 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
611 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
612 BitVector BV(TRI->getNumRegs());
614 // Before CSI is calculated, no registers are considered pristine. They can be
615 // freely used and PEI will make sure they are saved.
616 if (!isCalleeSavedInfoValid())
619 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
622 // Saved CSRs are not pristine.
623 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
624 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
625 E = CSI.end(); I != E; ++I)
626 BV.reset(I->getReg());
631 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
632 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
633 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
634 unsigned MaxAlign = getMaxAlignment();
637 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
638 // It really should be refactored to share code. Until then, changes
639 // should keep in mind that there's tight coupling between the two.
641 for (int i = getObjectIndexBegin(); i != 0; ++i) {
642 int FixedOff = -getObjectOffset(i);
643 if (FixedOff > Offset) Offset = FixedOff;
645 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
646 if (isDeadObjectIndex(i))
648 Offset += getObjectSize(i);
649 unsigned Align = getObjectAlignment(i);
650 // Adjust to alignment boundary
651 Offset = (Offset+Align-1)/Align*Align;
653 MaxAlign = std::max(Align, MaxAlign);
656 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
657 Offset += getMaxCallFrameSize();
659 // Round up the size to a multiple of the alignment. If the function has
660 // any calls or alloca's, align to the target's StackAlignment value to
661 // ensure that the callee's frame or the alloca data is suitably aligned;
662 // otherwise, for leaf functions, align to the TransientStackAlignment
665 if (adjustsStack() || hasVarSizedObjects() ||
666 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
667 StackAlign = TFI->getStackAlignment();
669 StackAlign = TFI->getTransientStackAlignment();
671 // If the frame pointer is eliminated, all frame offsets will be relative to
672 // SP not FP. Align to MaxAlign so this works.
673 StackAlign = std::max(StackAlign, MaxAlign);
674 unsigned AlignMask = StackAlign - 1;
675 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
677 return (unsigned)Offset;
680 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
681 if (Objects.empty()) return;
683 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
684 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
686 OS << "Frame Objects:\n";
688 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
689 const StackObject &SO = Objects[i];
690 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
691 if (SO.Size == ~0ULL) {
696 OS << "variable sized";
698 OS << "size=" << SO.Size;
699 OS << ", align=" << SO.Alignment;
701 if (i < NumFixedObjects)
703 if (i < NumFixedObjects || SO.SPOffset != -1) {
704 int64_t Off = SO.SPOffset - ValOffset;
705 OS << ", at location [SP";
716 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
717 void MachineFrameInfo::dump(const MachineFunction &MF) const {
722 //===----------------------------------------------------------------------===//
723 // MachineJumpTableInfo implementation
724 //===----------------------------------------------------------------------===//
726 /// Return the size of each entry in the jump table.
727 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
728 // The size of a jump table entry is 4 bytes unless the entry is just the
729 // address of a block, in which case it is the pointer size.
730 switch (getEntryKind()) {
731 case MachineJumpTableInfo::EK_BlockAddress:
732 return TD.getPointerSize();
733 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
735 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
736 case MachineJumpTableInfo::EK_LabelDifference32:
737 case MachineJumpTableInfo::EK_Custom32:
739 case MachineJumpTableInfo::EK_Inline:
742 llvm_unreachable("Unknown jump table encoding!");
745 /// Return the alignment of each entry in the jump table.
746 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
747 // The alignment of a jump table entry is the alignment of int32 unless the
748 // entry is just the address of a block, in which case it is the pointer
750 switch (getEntryKind()) {
751 case MachineJumpTableInfo::EK_BlockAddress:
752 return TD.getPointerABIAlignment();
753 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
754 return TD.getABIIntegerTypeAlignment(64);
755 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
756 case MachineJumpTableInfo::EK_LabelDifference32:
757 case MachineJumpTableInfo::EK_Custom32:
758 return TD.getABIIntegerTypeAlignment(32);
759 case MachineJumpTableInfo::EK_Inline:
762 llvm_unreachable("Unknown jump table encoding!");
765 /// Create a new jump table entry in the jump table info.
766 unsigned MachineJumpTableInfo::createJumpTableIndex(
767 const std::vector<MachineBasicBlock*> &DestBBs) {
768 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
769 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
770 return JumpTables.size()-1;
773 /// If Old is the target of any jump tables, update the jump tables to branch
775 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
776 MachineBasicBlock *New) {
777 assert(Old != New && "Not making a change?");
778 bool MadeChange = false;
779 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
780 ReplaceMBBInJumpTable(i, Old, New);
784 /// If Old is a target of the jump tables, update the jump table to branch to
786 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
787 MachineBasicBlock *Old,
788 MachineBasicBlock *New) {
789 assert(Old != New && "Not making a change?");
790 bool MadeChange = false;
791 MachineJumpTableEntry &JTE = JumpTables[Idx];
792 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
793 if (JTE.MBBs[j] == Old) {
800 void MachineJumpTableInfo::print(raw_ostream &OS) const {
801 if (JumpTables.empty()) return;
803 OS << "Jump Tables:\n";
805 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
806 OS << " jt#" << i << ": ";
807 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
808 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
814 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
815 void MachineJumpTableInfo::dump() const { print(dbgs()); }
819 //===----------------------------------------------------------------------===//
820 // MachineConstantPool implementation
821 //===----------------------------------------------------------------------===//
823 void MachineConstantPoolValue::anchor() { }
825 Type *MachineConstantPoolEntry::getType() const {
826 if (isMachineConstantPoolEntry())
827 return Val.MachineCPVal->getType();
828 return Val.ConstVal->getType();
831 bool MachineConstantPoolEntry::needsRelocation() const {
832 if (isMachineConstantPoolEntry())
834 return Val.ConstVal->needsRelocation();
838 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
839 if (needsRelocation())
840 return SectionKind::getReadOnlyWithRel();
841 switch (DL->getTypeAllocSize(getType())) {
843 return SectionKind::getMergeableConst4();
845 return SectionKind::getMergeableConst8();
847 return SectionKind::getMergeableConst16();
849 return SectionKind::getReadOnly();
853 MachineConstantPool::~MachineConstantPool() {
854 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
855 if (Constants[i].isMachineConstantPoolEntry())
856 delete Constants[i].Val.MachineCPVal;
857 for (DenseSet<MachineConstantPoolValue*>::iterator I =
858 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
863 /// Test whether the given two constants can be allocated the same constant pool
865 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
866 const DataLayout &DL) {
867 // Handle the trivial case quickly.
868 if (A == B) return true;
870 // If they have the same type but weren't the same constant, quickly
872 if (A->getType() == B->getType()) return false;
874 // We can't handle structs or arrays.
875 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
876 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
879 // For now, only support constants with the same size.
880 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
881 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
884 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
886 // Try constant folding a bitcast of both instructions to an integer. If we
887 // get two identical ConstantInt's, then we are good to share them. We use
888 // the constant folding APIs to do this so that we get the benefit of
890 if (isa<PointerType>(A->getType()))
891 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
892 const_cast<Constant *>(A), DL);
893 else if (A->getType() != IntTy)
894 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
895 const_cast<Constant *>(A), DL);
896 if (isa<PointerType>(B->getType()))
897 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
898 const_cast<Constant *>(B), DL);
899 else if (B->getType() != IntTy)
900 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
901 const_cast<Constant *>(B), DL);
906 /// Create a new entry in the constant pool or return an existing one.
907 /// User must specify the log2 of the minimum required alignment for the object.
908 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
909 unsigned Alignment) {
910 assert(Alignment && "Alignment must be specified!");
911 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
913 // Check to see if we already have this constant.
915 // FIXME, this could be made much more efficient for large constant pools.
916 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
917 if (!Constants[i].isMachineConstantPoolEntry() &&
918 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
919 if ((unsigned)Constants[i].getAlignment() < Alignment)
920 Constants[i].Alignment = Alignment;
924 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
925 return Constants.size()-1;
928 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
929 unsigned Alignment) {
930 assert(Alignment && "Alignment must be specified!");
931 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
933 // Check to see if we already have this constant.
935 // FIXME, this could be made much more efficient for large constant pools.
936 int Idx = V->getExistingMachineCPValue(this, Alignment);
938 MachineCPVsSharingEntries.insert(V);
939 return (unsigned)Idx;
942 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
943 return Constants.size()-1;
946 void MachineConstantPool::print(raw_ostream &OS) const {
947 if (Constants.empty()) return;
949 OS << "Constant Pool:\n";
950 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
951 OS << " cp#" << i << ": ";
952 if (Constants[i].isMachineConstantPoolEntry())
953 Constants[i].Val.MachineCPVal->print(OS);
955 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
956 OS << ", align=" << Constants[i].getAlignment();
961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
962 void MachineConstantPool::dump() const { print(dbgs()); }