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/DebugInfo.h"
29 #include "llvm/IR/DataLayout.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.getRegisterInfo());
61 FrameInfo = new (Allocator) MachineFrameInfo(*TM.getFrameLowering(),
62 TM.Options.RealignStack);
63 if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
64 Attribute::StackAlignment))
65 FrameInfo->ensureMaxAlignment(Fn->getAttributes().
66 getStackAlignment(AttributeSet::FunctionIndex));
67 ConstantPool = new (Allocator) MachineConstantPool(TM.getDataLayout());
68 Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
69 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
70 if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
71 Attribute::OptimizeForSize))
72 Alignment = std::max(Alignment,
73 TM.getTargetLowering()->getPrefFunctionAlignment());
74 FunctionNumber = FunctionNum;
78 MachineFunction::~MachineFunction() {
80 InstructionRecycler.clear(Allocator);
81 BasicBlockRecycler.clear(Allocator);
83 RegInfo->~MachineRegisterInfo();
84 Allocator.Deallocate(RegInfo);
87 MFInfo->~MachineFunctionInfo();
88 Allocator.Deallocate(MFInfo);
91 FrameInfo->~MachineFrameInfo();
92 Allocator.Deallocate(FrameInfo);
94 ConstantPool->~MachineConstantPool();
95 Allocator.Deallocate(ConstantPool);
98 JumpTableInfo->~MachineJumpTableInfo();
99 Allocator.Deallocate(JumpTableInfo);
103 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
104 /// does already exist, allocate one.
105 MachineJumpTableInfo *MachineFunction::
106 getOrCreateJumpTableInfo(unsigned EntryKind) {
107 if (JumpTableInfo) return JumpTableInfo;
109 JumpTableInfo = new (Allocator)
110 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
111 return JumpTableInfo;
114 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
115 /// recomputes them. This guarantees that the MBB numbers are sequential,
116 /// dense, and match the ordering of the blocks within the function. If a
117 /// specific MachineBasicBlock is specified, only that block and those after
118 /// it are renumbered.
119 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
120 if (empty()) { MBBNumbering.clear(); return; }
121 MachineFunction::iterator MBBI, E = end();
127 // Figure out the block number this should have.
128 unsigned BlockNo = 0;
130 BlockNo = prior(MBBI)->getNumber()+1;
132 for (; MBBI != E; ++MBBI, ++BlockNo) {
133 if (MBBI->getNumber() != (int)BlockNo) {
134 // Remove use of the old number.
135 if (MBBI->getNumber() != -1) {
136 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
137 "MBB number mismatch!");
138 MBBNumbering[MBBI->getNumber()] = 0;
141 // If BlockNo is already taken, set that block's number to -1.
142 if (MBBNumbering[BlockNo])
143 MBBNumbering[BlockNo]->setNumber(-1);
145 MBBNumbering[BlockNo] = MBBI;
146 MBBI->setNumber(BlockNo);
150 // Okay, all the blocks are renumbered. If we have compactified the block
151 // numbering, shrink MBBNumbering now.
152 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
153 MBBNumbering.resize(BlockNo);
156 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
157 /// of `new MachineInstr'.
160 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
161 DebugLoc DL, bool NoImp) {
162 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
163 MachineInstr(*this, MCID, DL, NoImp);
166 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
167 /// 'Orig' instruction, identical in all ways except the instruction
168 /// has no parent, prev, or next.
171 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
172 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
173 MachineInstr(*this, *Orig);
176 /// DeleteMachineInstr - Delete the given MachineInstr.
179 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
181 InstructionRecycler.Deallocate(Allocator, MI);
184 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
185 /// instead of `new MachineBasicBlock'.
188 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
189 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
190 MachineBasicBlock(*this, bb);
193 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
196 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
197 assert(MBB->getParent() == this && "MBB parent mismatch!");
198 MBB->~MachineBasicBlock();
199 BasicBlockRecycler.Deallocate(Allocator, MBB);
203 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
204 uint64_t s, unsigned base_alignment,
205 const MDNode *TBAAInfo,
206 const MDNode *Ranges) {
207 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
212 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
213 int64_t Offset, uint64_t Size) {
214 return new (Allocator)
215 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
216 MMO->getOffset()+Offset),
217 MMO->getFlags(), Size,
218 MMO->getBaseAlignment(), 0);
221 MachineInstr::mmo_iterator
222 MachineFunction::allocateMemRefsArray(unsigned long Num) {
223 return Allocator.Allocate<MachineMemOperand *>(Num);
226 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
227 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
228 MachineInstr::mmo_iterator End) {
229 // Count the number of load mem refs.
231 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
235 // Allocate a new array and populate it with the load information.
236 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
238 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
239 if ((*I)->isLoad()) {
240 if (!(*I)->isStore())
244 // Clone the MMO and unset the store flag.
245 MachineMemOperand *JustLoad =
246 getMachineMemOperand((*I)->getPointerInfo(),
247 (*I)->getFlags() & ~MachineMemOperand::MOStore,
248 (*I)->getSize(), (*I)->getBaseAlignment(),
249 (*I)->getTBAAInfo());
250 Result[Index] = JustLoad;
255 return std::make_pair(Result, Result + Num);
258 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
259 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
260 MachineInstr::mmo_iterator End) {
261 // Count the number of load mem refs.
263 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
267 // Allocate a new array and populate it with the store information.
268 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
270 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
271 if ((*I)->isStore()) {
276 // Clone the MMO and unset the load flag.
277 MachineMemOperand *JustStore =
278 getMachineMemOperand((*I)->getPointerInfo(),
279 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
280 (*I)->getSize(), (*I)->getBaseAlignment(),
281 (*I)->getTBAAInfo());
282 Result[Index] = JustStore;
287 return std::make_pair(Result, Result + Num);
290 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
291 void MachineFunction::dump() const {
296 StringRef MachineFunction::getName() const {
297 assert(getFunction() && "No function!");
298 return getFunction()->getName();
301 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
302 OS << "# Machine code for function " << getName() << ": ";
304 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
305 if (!RegInfo->tracksLiveness())
306 OS << ", not tracking liveness";
310 // Print Frame Information
311 FrameInfo->print(*this, OS);
313 // Print JumpTable Information
315 JumpTableInfo->print(OS);
317 // Print Constant Pool
318 ConstantPool->print(OS);
320 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
322 if (RegInfo && !RegInfo->livein_empty()) {
323 OS << "Function Live Ins: ";
324 for (MachineRegisterInfo::livein_iterator
325 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
326 OS << PrintReg(I->first, TRI);
328 OS << " in " << PrintReg(I->second, TRI);
329 if (llvm::next(I) != E)
334 if (RegInfo && !RegInfo->liveout_empty()) {
335 OS << "Function Live Outs:";
336 for (MachineRegisterInfo::liveout_iterator
337 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
338 OS << ' ' << PrintReg(*I, TRI);
342 for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
344 BB->print(OS, Indexes);
347 OS << "\n# End machine code for function " << getName() << ".\n\n";
352 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
354 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
356 static std::string getGraphName(const MachineFunction *F) {
357 return "CFG for '" + F->getName().str() + "' function";
360 std::string getNodeLabel(const MachineBasicBlock *Node,
361 const MachineFunction *Graph) {
364 raw_string_ostream OSS(OutStr);
367 OSS << "BB#" << Node->getNumber();
368 if (const BasicBlock *BB = Node->getBasicBlock())
369 OSS << ": " << BB->getName();
374 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
376 // Process string output to make it nicer...
377 for (unsigned i = 0; i != OutStr.length(); ++i)
378 if (OutStr[i] == '\n') { // Left justify
380 OutStr.insert(OutStr.begin()+i+1, 'l');
387 void MachineFunction::viewCFG() const
390 ViewGraph(this, "mf" + getName());
392 errs() << "MachineFunction::viewCFG is only available in debug builds on "
393 << "systems with Graphviz or gv!\n";
397 void MachineFunction::viewCFGOnly() const
400 ViewGraph(this, "mf" + getName(), true);
402 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
403 << "systems with Graphviz or gv!\n";
407 /// addLiveIn - Add the specified physical register as a live-in value and
408 /// create a corresponding virtual register for it.
409 unsigned MachineFunction::addLiveIn(unsigned PReg,
410 const TargetRegisterClass *RC) {
411 MachineRegisterInfo &MRI = getRegInfo();
412 unsigned VReg = MRI.getLiveInVirtReg(PReg);
414 assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
417 VReg = MRI.createVirtualRegister(RC);
418 MRI.addLiveIn(PReg, VReg);
422 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
423 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
424 /// normal 'L' label is returned.
425 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
426 bool isLinkerPrivate) const {
427 assert(JumpTableInfo && "No jump tables");
428 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
429 const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
431 const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
432 MAI.getPrivateGlobalPrefix();
433 SmallString<60> Name;
434 raw_svector_ostream(Name)
435 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
436 return Ctx.GetOrCreateSymbol(Name.str());
439 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
441 MCSymbol *MachineFunction::getPICBaseSymbol() const {
442 const MCAsmInfo &MAI = *Target.getMCAsmInfo();
443 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
444 Twine(getFunctionNumber())+"$pb");
447 //===----------------------------------------------------------------------===//
448 // MachineFrameInfo implementation
449 //===----------------------------------------------------------------------===//
451 /// ensureMaxAlignment - Make sure the function is at least Align bytes
453 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
454 if (!TFI.isStackRealignable() || !RealignOption)
455 assert(Align <= TFI.getStackAlignment() &&
456 "For targets without stack realignment, Align is out of limit!");
457 if (MaxAlignment < Align) MaxAlignment = Align;
460 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
461 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
462 unsigned StackAlign) {
463 if (!ShouldClamp || Align <= StackAlign)
465 DEBUG(dbgs() << "Warning: requested alignment " << Align
466 << " exceeds the stack alignment " << StackAlign
467 << " when stack realignment is off" << '\n');
471 /// CreateStackObject - Create a new statically sized stack object, returning
472 /// a nonnegative identifier to represent it.
474 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
475 bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
476 assert(Size != 0 && "Cannot allocate zero size stack objects!");
477 Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
478 Alignment, TFI.getStackAlignment());
479 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
481 int Index = (int)Objects.size() - NumFixedObjects - 1;
482 assert(Index >= 0 && "Bad frame index!");
483 ensureMaxAlignment(Alignment);
487 /// CreateSpillStackObject - Create a new statically sized stack object that
488 /// represents a spill slot, returning a nonnegative identifier to represent
491 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
492 unsigned Alignment) {
493 Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
494 Alignment, TFI.getStackAlignment());
495 CreateStackObject(Size, Alignment, true, false);
496 int Index = (int)Objects.size() - NumFixedObjects - 1;
497 ensureMaxAlignment(Alignment);
501 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
502 /// variable sized object has been created. This must be created whenever a
503 /// variable sized object is created, whether or not the index returned is
506 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment) {
507 HasVarSizedObjects = true;
508 Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
509 Alignment, TFI.getStackAlignment());
510 Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
511 ensureMaxAlignment(Alignment);
512 return (int)Objects.size()-NumFixedObjects-1;
515 /// CreateFixedObject - Create a new object at a fixed location on the stack.
516 /// All fixed objects should be created before other objects are created for
517 /// efficiency. By default, fixed objects are immutable. This returns an
518 /// index with a negative value.
520 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
522 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
523 // The alignment of the frame index can be determined from its offset from
524 // the incoming frame position. If the frame object is at offset 32 and
525 // the stack is guaranteed to be 16-byte aligned, then we know that the
526 // object is 16-byte aligned.
527 unsigned StackAlign = TFI.getStackAlignment();
528 unsigned Align = MinAlign(SPOffset, StackAlign);
529 Align = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
530 Align, TFI.getStackAlignment());
531 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
535 return -++NumFixedObjects;
540 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
541 assert(MBB && "MBB must be valid");
542 const MachineFunction *MF = MBB->getParent();
543 assert(MF && "MBB must be part of a MachineFunction");
544 const TargetMachine &TM = MF->getTarget();
545 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
546 BitVector BV(TRI->getNumRegs());
548 // Before CSI is calculated, no registers are considered pristine. They can be
549 // freely used and PEI will make sure they are saved.
550 if (!isCalleeSavedInfoValid())
553 for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
556 // The entry MBB always has all CSRs pristine.
557 if (MBB == &MF->front())
560 // On other MBBs the saved CSRs are not pristine.
561 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
562 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
563 E = CSI.end(); I != E; ++I)
564 BV.reset(I->getReg());
570 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
571 if (Objects.empty()) return;
573 const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
574 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
576 OS << "Frame Objects:\n";
578 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
579 const StackObject &SO = Objects[i];
580 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
581 if (SO.Size == ~0ULL) {
586 OS << "variable sized";
588 OS << "size=" << SO.Size;
589 OS << ", align=" << SO.Alignment;
591 if (i < NumFixedObjects)
593 if (i < NumFixedObjects || SO.SPOffset != -1) {
594 int64_t Off = SO.SPOffset - ValOffset;
595 OS << ", at location [SP";
606 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
607 void MachineFrameInfo::dump(const MachineFunction &MF) const {
612 //===----------------------------------------------------------------------===//
613 // MachineJumpTableInfo implementation
614 //===----------------------------------------------------------------------===//
616 /// getEntrySize - Return the size of each entry in the jump table.
617 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
618 // The size of a jump table entry is 4 bytes unless the entry is just the
619 // address of a block, in which case it is the pointer size.
620 switch (getEntryKind()) {
621 case MachineJumpTableInfo::EK_BlockAddress:
622 return TD.getPointerSize();
623 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
625 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
626 case MachineJumpTableInfo::EK_LabelDifference32:
627 case MachineJumpTableInfo::EK_Custom32:
629 case MachineJumpTableInfo::EK_Inline:
632 llvm_unreachable("Unknown jump table encoding!");
635 /// getEntryAlignment - Return the alignment of each entry in the jump table.
636 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
637 // The alignment of a jump table entry is the alignment of int32 unless the
638 // entry is just the address of a block, in which case it is the pointer
640 switch (getEntryKind()) {
641 case MachineJumpTableInfo::EK_BlockAddress:
642 return TD.getPointerABIAlignment();
643 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
644 return TD.getABIIntegerTypeAlignment(64);
645 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
646 case MachineJumpTableInfo::EK_LabelDifference32:
647 case MachineJumpTableInfo::EK_Custom32:
648 return TD.getABIIntegerTypeAlignment(32);
649 case MachineJumpTableInfo::EK_Inline:
652 llvm_unreachable("Unknown jump table encoding!");
655 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
657 unsigned MachineJumpTableInfo::createJumpTableIndex(
658 const std::vector<MachineBasicBlock*> &DestBBs) {
659 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
660 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
661 return JumpTables.size()-1;
664 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
665 /// the jump tables to branch to New instead.
666 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
667 MachineBasicBlock *New) {
668 assert(Old != New && "Not making a change?");
669 bool MadeChange = false;
670 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
671 ReplaceMBBInJumpTable(i, Old, New);
675 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
676 /// the jump table to branch to New instead.
677 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
678 MachineBasicBlock *Old,
679 MachineBasicBlock *New) {
680 assert(Old != New && "Not making a change?");
681 bool MadeChange = false;
682 MachineJumpTableEntry &JTE = JumpTables[Idx];
683 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
684 if (JTE.MBBs[j] == Old) {
691 void MachineJumpTableInfo::print(raw_ostream &OS) const {
692 if (JumpTables.empty()) return;
694 OS << "Jump Tables:\n";
696 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
697 OS << " jt#" << i << ": ";
698 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
699 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
705 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
706 void MachineJumpTableInfo::dump() const { print(dbgs()); }
710 //===----------------------------------------------------------------------===//
711 // MachineConstantPool implementation
712 //===----------------------------------------------------------------------===//
714 void MachineConstantPoolValue::anchor() { }
716 Type *MachineConstantPoolEntry::getType() const {
717 if (isMachineConstantPoolEntry())
718 return Val.MachineCPVal->getType();
719 return Val.ConstVal->getType();
723 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
724 if (isMachineConstantPoolEntry())
725 return Val.MachineCPVal->getRelocationInfo();
726 return Val.ConstVal->getRelocationInfo();
729 MachineConstantPool::~MachineConstantPool() {
730 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
731 if (Constants[i].isMachineConstantPoolEntry())
732 delete Constants[i].Val.MachineCPVal;
733 for (DenseSet<MachineConstantPoolValue*>::iterator I =
734 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
739 /// CanShareConstantPoolEntry - Test whether the given two constants
740 /// can be allocated the same constant pool entry.
741 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
742 const DataLayout *TD) {
743 // Handle the trivial case quickly.
744 if (A == B) return true;
746 // If they have the same type but weren't the same constant, quickly
748 if (A->getType() == B->getType()) return false;
750 // We can't handle structs or arrays.
751 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
752 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
755 // For now, only support constants with the same size.
756 uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
757 if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
761 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
763 // Try constant folding a bitcast of both instructions to an integer. If we
764 // get two identical ConstantInt's, then we are good to share them. We use
765 // the constant folding APIs to do this so that we get the benefit of
767 if (isa<PointerType>(A->getType()))
768 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
769 const_cast<Constant*>(A), TD);
770 else if (A->getType() != IntTy)
771 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
772 const_cast<Constant*>(A), TD);
773 if (isa<PointerType>(B->getType()))
774 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
775 const_cast<Constant*>(B), TD);
776 else if (B->getType() != IntTy)
777 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
778 const_cast<Constant*>(B), TD);
783 /// getConstantPoolIndex - Create a new entry in the constant pool or return
784 /// an existing one. User must specify the log2 of the minimum required
785 /// alignment for the object.
787 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
788 unsigned Alignment) {
789 assert(Alignment && "Alignment must be specified!");
790 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
792 // Check to see if we already have this constant.
794 // FIXME, this could be made much more efficient for large constant pools.
795 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
796 if (!Constants[i].isMachineConstantPoolEntry() &&
797 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
798 if ((unsigned)Constants[i].getAlignment() < Alignment)
799 Constants[i].Alignment = Alignment;
803 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
804 return Constants.size()-1;
807 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
808 unsigned Alignment) {
809 assert(Alignment && "Alignment must be specified!");
810 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
812 // Check to see if we already have this constant.
814 // FIXME, this could be made much more efficient for large constant pools.
815 int Idx = V->getExistingMachineCPValue(this, Alignment);
817 MachineCPVsSharingEntries.insert(V);
818 return (unsigned)Idx;
821 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
822 return Constants.size()-1;
825 void MachineConstantPool::print(raw_ostream &OS) const {
826 if (Constants.empty()) return;
828 OS << "Constant Pool:\n";
829 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
830 OS << " cp#" << i << ": ";
831 if (Constants[i].isMachineConstantPoolEntry())
832 Constants[i].Val.MachineCPVal->print(OS);
834 OS << *(const Value*)Constants[i].Val.ConstVal;
835 OS << ", align=" << Constants[i].getAlignment();
840 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
841 void MachineConstantPool::dump() const { print(dbgs()); }