97b86cb876dd929435ab1da7cf036dc336ac77bf
[oota-llvm.git] / lib / CodeGen / MachineFunction.cpp
1 //===-- MachineFunction.cpp -----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect native machine code information for a function.  This allows
11 // target-specific information about the generated code to be stored with each
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Analysis/DebugInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/raw_ostream.h"
40 using namespace llvm;
41
42 namespace {
43   struct Printer : public MachineFunctionPass {
44     static char ID;
45
46     raw_ostream &OS;
47     const std::string Banner;
48
49     Printer(raw_ostream &os, const std::string &banner) 
50       : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
51
52     const char *getPassName() const { return "MachineFunction Printer"; }
53
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.setPreservesAll();
56       MachineFunctionPass::getAnalysisUsage(AU);
57     }
58
59     bool runOnMachineFunction(MachineFunction &MF) {
60       OS << "# " << Banner << ":\n";
61       MF.print(OS);
62       return false;
63     }
64   };
65   char Printer::ID = 0;
66 }
67
68 /// Returns a newly-created MachineFunction Printer pass. The default banner is
69 /// empty.
70 ///
71 FunctionPass *llvm::createMachineFunctionPrinterPass(raw_ostream &OS,
72                                                      const std::string &Banner){
73   return new Printer(OS, Banner);
74 }
75
76 //===----------------------------------------------------------------------===//
77 // MachineFunction implementation
78 //===----------------------------------------------------------------------===//
79
80 // Out of line virtual method.
81 MachineFunctionInfo::~MachineFunctionInfo() {}
82
83 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
84   MBB->getParent()->DeleteMachineBasicBlock(MBB);
85 }
86
87 MachineFunction::MachineFunction(Function *F, const TargetMachine &TM,
88                                  unsigned FunctionNum)
89   : Fn(F), Target(TM) {
90   if (TM.getRegisterInfo())
91     RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
92                   MachineRegisterInfo(*TM.getRegisterInfo());
93   else
94     RegInfo = 0;
95   MFInfo = 0;
96   FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
97                   MachineFrameInfo(*TM.getFrameInfo());
98   ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
99                      MachineConstantPool(TM.getTargetData());
100   Alignment = TM.getTargetLowering()->getFunctionAlignment(F);
101   FunctionNumber = FunctionNum;
102   JumpTableInfo = 0;
103 }
104
105 MachineFunction::~MachineFunction() {
106   BasicBlocks.clear();
107   InstructionRecycler.clear(Allocator);
108   BasicBlockRecycler.clear(Allocator);
109   if (RegInfo) {
110     RegInfo->~MachineRegisterInfo();
111     Allocator.Deallocate(RegInfo);
112   }
113   if (MFInfo) {
114     MFInfo->~MachineFunctionInfo();
115     Allocator.Deallocate(MFInfo);
116   }
117   FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
118   ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
119   
120   if (JumpTableInfo) {
121     JumpTableInfo->~MachineJumpTableInfo();
122     Allocator.Deallocate(JumpTableInfo);
123   }
124 }
125
126 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
127 /// does already exist, allocate one.
128 MachineJumpTableInfo *MachineFunction::
129 getOrCreateJumpTableInfo(unsigned EntryKind) {
130   if (JumpTableInfo) return JumpTableInfo;
131   
132   JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
133     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
134   return JumpTableInfo;
135 }
136
137 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
138 /// recomputes them.  This guarantees that the MBB numbers are sequential,
139 /// dense, and match the ordering of the blocks within the function.  If a
140 /// specific MachineBasicBlock is specified, only that block and those after
141 /// it are renumbered.
142 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
143   if (empty()) { MBBNumbering.clear(); return; }
144   MachineFunction::iterator MBBI, E = end();
145   if (MBB == 0)
146     MBBI = begin();
147   else
148     MBBI = MBB;
149   
150   // Figure out the block number this should have.
151   unsigned BlockNo = 0;
152   if (MBBI != begin())
153     BlockNo = prior(MBBI)->getNumber()+1;
154   
155   for (; MBBI != E; ++MBBI, ++BlockNo) {
156     if (MBBI->getNumber() != (int)BlockNo) {
157       // Remove use of the old number.
158       if (MBBI->getNumber() != -1) {
159         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
160                "MBB number mismatch!");
161         MBBNumbering[MBBI->getNumber()] = 0;
162       }
163       
164       // If BlockNo is already taken, set that block's number to -1.
165       if (MBBNumbering[BlockNo])
166         MBBNumbering[BlockNo]->setNumber(-1);
167
168       MBBNumbering[BlockNo] = MBBI;
169       MBBI->setNumber(BlockNo);
170     }
171   }    
172
173   // Okay, all the blocks are renumbered.  If we have compactified the block
174   // numbering, shrink MBBNumbering now.
175   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
176   MBBNumbering.resize(BlockNo);
177 }
178
179 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
180 /// of `new MachineInstr'.
181 ///
182 MachineInstr *
183 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
184                                     DebugLoc DL, bool NoImp) {
185   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
186     MachineInstr(TID, DL, NoImp);
187 }
188
189 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
190 /// 'Orig' instruction, identical in all ways except the the instruction
191 /// has no parent, prev, or next.
192 ///
193 MachineInstr *
194 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
195   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
196              MachineInstr(*this, *Orig);
197 }
198
199 /// DeleteMachineInstr - Delete the given MachineInstr.
200 ///
201 void
202 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
203   MI->~MachineInstr();
204   InstructionRecycler.Deallocate(Allocator, MI);
205 }
206
207 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
208 /// instead of `new MachineBasicBlock'.
209 ///
210 MachineBasicBlock *
211 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
212   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
213              MachineBasicBlock(*this, bb);
214 }
215
216 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
217 ///
218 void
219 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
220   assert(MBB->getParent() == this && "MBB parent mismatch!");
221   MBB->~MachineBasicBlock();
222   BasicBlockRecycler.Deallocate(Allocator, MBB);
223 }
224
225 MachineMemOperand *
226 MachineFunction::getMachineMemOperand(const Value *v, unsigned f,
227                                       int64_t o, uint64_t s,
228                                       unsigned base_alignment) {
229   return new (Allocator.Allocate<MachineMemOperand>())
230              MachineMemOperand(v, f, o, s, base_alignment);
231 }
232
233 MachineMemOperand *
234 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
235                                       int64_t Offset, uint64_t Size) {
236   return new (Allocator.Allocate<MachineMemOperand>())
237              MachineMemOperand(MMO->getValue(), MMO->getFlags(),
238                                int64_t(uint64_t(MMO->getOffset()) +
239                                        uint64_t(Offset)),
240                                Size, MMO->getBaseAlignment());
241 }
242
243 MachineInstr::mmo_iterator
244 MachineFunction::allocateMemRefsArray(unsigned long Num) {
245   return Allocator.Allocate<MachineMemOperand *>(Num);
246 }
247
248 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
249 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
250                                     MachineInstr::mmo_iterator End) {
251   // Count the number of load mem refs.
252   unsigned Num = 0;
253   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
254     if ((*I)->isLoad())
255       ++Num;
256
257   // Allocate a new array and populate it with the load information.
258   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
259   unsigned Index = 0;
260   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
261     if ((*I)->isLoad()) {
262       if (!(*I)->isStore())
263         // Reuse the MMO.
264         Result[Index] = *I;
265       else {
266         // Clone the MMO and unset the store flag.
267         MachineMemOperand *JustLoad =
268           getMachineMemOperand((*I)->getValue(),
269                                (*I)->getFlags() & ~MachineMemOperand::MOStore,
270                                (*I)->getOffset(), (*I)->getSize(),
271                                (*I)->getBaseAlignment());
272         Result[Index] = JustLoad;
273       }
274       ++Index;
275     }
276   }
277   return std::make_pair(Result, Result + Num);
278 }
279
280 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
281 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
282                                      MachineInstr::mmo_iterator End) {
283   // Count the number of load mem refs.
284   unsigned Num = 0;
285   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
286     if ((*I)->isStore())
287       ++Num;
288
289   // Allocate a new array and populate it with the store information.
290   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
291   unsigned Index = 0;
292   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
293     if ((*I)->isStore()) {
294       if (!(*I)->isLoad())
295         // Reuse the MMO.
296         Result[Index] = *I;
297       else {
298         // Clone the MMO and unset the load flag.
299         MachineMemOperand *JustStore =
300           getMachineMemOperand((*I)->getValue(),
301                                (*I)->getFlags() & ~MachineMemOperand::MOLoad,
302                                (*I)->getOffset(), (*I)->getSize(),
303                                (*I)->getBaseAlignment());
304         Result[Index] = JustStore;
305       }
306       ++Index;
307     }
308   }
309   return std::make_pair(Result, Result + Num);
310 }
311
312 void MachineFunction::dump() const {
313   print(dbgs());
314 }
315
316 void MachineFunction::print(raw_ostream &OS) const {
317   OS << "# Machine code for function " << Fn->getName() << ":\n";
318
319   // Print Frame Information
320   FrameInfo->print(*this, OS);
321   
322   // Print JumpTable Information
323   if (JumpTableInfo)
324     JumpTableInfo->print(OS);
325
326   // Print Constant Pool
327   ConstantPool->print(OS);
328   
329   const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
330   
331   if (RegInfo && !RegInfo->livein_empty()) {
332     OS << "Function Live Ins: ";
333     for (MachineRegisterInfo::livein_iterator
334          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
335       if (TRI)
336         OS << "%" << TRI->getName(I->first);
337       else
338         OS << " %physreg" << I->first;
339       
340       if (I->second)
341         OS << " in reg%" << I->second;
342
343       if (llvm::next(I) != E)
344         OS << ", ";
345     }
346     OS << '\n';
347   }
348   if (RegInfo && !RegInfo->liveout_empty()) {
349     OS << "Function Live Outs: ";
350     for (MachineRegisterInfo::liveout_iterator
351          I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I){
352       if (TRI)
353         OS << '%' << TRI->getName(*I);
354       else
355         OS << "%physreg" << *I;
356
357       if (llvm::next(I) != E)
358         OS << " ";
359     }
360     OS << '\n';
361   }
362   
363   for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
364     OS << '\n';
365     BB->print(OS);
366   }
367
368   OS << "\n# End machine code for function " << Fn->getName() << ".\n\n";
369 }
370
371 namespace llvm {
372   template<>
373   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
374
375   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
376
377     static std::string getGraphName(const MachineFunction *F) {
378       return "CFG for '" + F->getFunction()->getNameStr() + "' function";
379     }
380
381     std::string getNodeLabel(const MachineBasicBlock *Node,
382                              const MachineFunction *Graph) {
383       if (isSimple () && Node->getBasicBlock() &&
384           !Node->getBasicBlock()->getName().empty())
385         return Node->getBasicBlock()->getNameStr() + ":";
386
387       std::string OutStr;
388       {
389         raw_string_ostream OSS(OutStr);
390         
391         if (isSimple())
392           OSS << Node->getNumber() << ':';
393         else
394           Node->print(OSS);
395       }
396
397       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
398
399       // Process string output to make it nicer...
400       for (unsigned i = 0; i != OutStr.length(); ++i)
401         if (OutStr[i] == '\n') {                            // Left justify
402           OutStr[i] = '\\';
403           OutStr.insert(OutStr.begin()+i+1, 'l');
404         }
405       return OutStr;
406     }
407   };
408 }
409
410 void MachineFunction::viewCFG() const
411 {
412 #ifndef NDEBUG
413   ViewGraph(this, "mf" + getFunction()->getNameStr());
414 #else
415   errs() << "SelectionDAG::viewGraph is only available in debug builds on "
416          << "systems with Graphviz or gv!\n";
417 #endif // NDEBUG
418 }
419
420 void MachineFunction::viewCFGOnly() const
421 {
422 #ifndef NDEBUG
423   ViewGraph(this, "mf" + getFunction()->getNameStr(), true);
424 #else
425   errs() << "SelectionDAG::viewGraph is only available in debug builds on "
426          << "systems with Graphviz or gv!\n";
427 #endif // NDEBUG
428 }
429
430 /// addLiveIn - Add the specified physical register as a live-in value and
431 /// create a corresponding virtual register for it.
432 unsigned MachineFunction::addLiveIn(unsigned PReg,
433                                     const TargetRegisterClass *RC) {
434   assert(RC->contains(PReg) && "Not the correct regclass!");
435   unsigned VReg = getRegInfo().createVirtualRegister(RC);
436   getRegInfo().addLiveIn(PReg, VReg);
437   return VReg;
438 }
439
440 /// getDILocation - Get the DILocation for a given DebugLoc object.
441 DILocation MachineFunction::getDILocation(DebugLoc DL) const {
442   unsigned Idx = DL.getIndex();
443   assert(Idx < DebugLocInfo.DebugLocations.size() &&
444          "Invalid index into debug locations!");
445   return DILocation(DebugLocInfo.DebugLocations[Idx]);
446 }
447
448
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   assert(JumpTableInfo && "No jump tables");
455   
456   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
457   const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
458   
459   const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
460                                          MAI.getPrivateGlobalPrefix();
461   SmallString<60> Name;
462   raw_svector_ostream(Name)
463     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
464   return Ctx.GetOrCreateSymbol(Name.str());
465 }
466
467
468 //===----------------------------------------------------------------------===//
469 //  MachineFrameInfo implementation
470 //===----------------------------------------------------------------------===//
471
472 /// CreateFixedObject - Create a new object at a fixed location on the stack.
473 /// All fixed objects should be created before other objects are created for
474 /// efficiency. By default, fixed objects are immutable. This returns an
475 /// index with a negative value.
476 ///
477 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
478                                         bool Immutable, bool isSS) {
479   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
480   Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable,
481                                               isSS));
482   return -++NumFixedObjects;
483 }
484
485
486 BitVector
487 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
488   assert(MBB && "MBB must be valid");
489   const MachineFunction *MF = MBB->getParent();
490   assert(MF && "MBB must be part of a MachineFunction");
491   const TargetMachine &TM = MF->getTarget();
492   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
493   BitVector BV(TRI->getNumRegs());
494
495   // Before CSI is calculated, no registers are considered pristine. They can be
496   // freely used and PEI will make sure they are saved.
497   if (!isCalleeSavedInfoValid())
498     return BV;
499
500   for (const unsigned *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
501     BV.set(*CSR);
502
503   // The entry MBB always has all CSRs pristine.
504   if (MBB == &MF->front())
505     return BV;
506
507   // On other MBBs the saved CSRs are not pristine.
508   const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
509   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
510          E = CSI.end(); I != E; ++I)
511     BV.reset(I->getReg());
512
513   return BV;
514 }
515
516
517 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
518   if (Objects.empty()) return;
519
520   const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
521   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
522
523   OS << "Frame Objects:\n";
524
525   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
526     const StackObject &SO = Objects[i];
527     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
528     if (SO.Size == ~0ULL) {
529       OS << "dead\n";
530       continue;
531     }
532     if (SO.Size == 0)
533       OS << "variable sized";
534     else
535       OS << "size=" << SO.Size;
536     OS << ", align=" << SO.Alignment;
537
538     if (i < NumFixedObjects)
539       OS << ", fixed";
540     if (i < NumFixedObjects || SO.SPOffset != -1) {
541       int64_t Off = SO.SPOffset - ValOffset;
542       OS << ", at location [SP";
543       if (Off > 0)
544         OS << "+" << Off;
545       else if (Off < 0)
546         OS << Off;
547       OS << "]";
548     }
549     OS << "\n";
550   }
551 }
552
553 void MachineFrameInfo::dump(const MachineFunction &MF) const {
554   print(MF, dbgs());
555 }
556
557 //===----------------------------------------------------------------------===//
558 //  MachineJumpTableInfo implementation
559 //===----------------------------------------------------------------------===//
560
561 /// getEntrySize - Return the size of each entry in the jump table.
562 unsigned MachineJumpTableInfo::getEntrySize(const TargetData &TD) const {
563   // The size of a jump table entry is 4 bytes unless the entry is just the
564   // address of a block, in which case it is the pointer size.
565   switch (getEntryKind()) {
566   case MachineJumpTableInfo::EK_BlockAddress:
567     return TD.getPointerSize();
568   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
569   case MachineJumpTableInfo::EK_LabelDifference32:
570   case MachineJumpTableInfo::EK_Custom32:
571     return 4;
572   }
573   assert(0 && "Unknown jump table encoding!");
574   return ~0;
575 }
576
577 /// getEntryAlignment - Return the alignment of each entry in the jump table.
578 unsigned MachineJumpTableInfo::getEntryAlignment(const TargetData &TD) const {
579   // The alignment of a jump table entry is the alignment of int32 unless the
580   // entry is just the address of a block, in which case it is the pointer
581   // alignment.
582   switch (getEntryKind()) {
583   case MachineJumpTableInfo::EK_BlockAddress:
584     return TD.getPointerABIAlignment();
585   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
586   case MachineJumpTableInfo::EK_LabelDifference32:
587   case MachineJumpTableInfo::EK_Custom32:
588     return TD.getABIIntegerTypeAlignment(32);
589   }
590   assert(0 && "Unknown jump table encoding!");
591   return ~0;
592 }
593
594 /// getJumpTableIndex - Create a new jump table entry in the jump table info
595 /// or return an existing one.
596 ///
597 unsigned MachineJumpTableInfo::getJumpTableIndex(
598                                const std::vector<MachineBasicBlock*> &DestBBs) {
599   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
600   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
601   return JumpTables.size()-1;
602 }
603
604
605 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
606 /// the jump tables to branch to New instead.
607 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
608                                                   MachineBasicBlock *New) {
609   assert(Old != New && "Not making a change?");
610   bool MadeChange = false;
611   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
612     ReplaceMBBInJumpTable(i, Old, New);
613   return MadeChange;
614 }
615
616 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
617 /// the jump table to branch to New instead.
618 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
619                                                  MachineBasicBlock *Old,
620                                                  MachineBasicBlock *New) {
621   assert(Old != New && "Not making a change?");
622   bool MadeChange = false;
623   MachineJumpTableEntry &JTE = JumpTables[Idx];
624   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
625     if (JTE.MBBs[j] == Old) {
626       JTE.MBBs[j] = New;
627       MadeChange = true;
628     }
629   return MadeChange;
630 }
631
632 void MachineJumpTableInfo::print(raw_ostream &OS) const {
633   if (JumpTables.empty()) return;
634
635   OS << "Jump Tables:\n";
636
637   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
638     OS << "  jt#" << i << ": ";
639     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
640       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
641   }
642
643   OS << '\n';
644 }
645
646 void MachineJumpTableInfo::dump() const { print(dbgs()); }
647
648
649 //===----------------------------------------------------------------------===//
650 //  MachineConstantPool implementation
651 //===----------------------------------------------------------------------===//
652
653 const Type *MachineConstantPoolEntry::getType() const {
654   if (isMachineConstantPoolEntry())
655     return Val.MachineCPVal->getType();
656   return Val.ConstVal->getType();
657 }
658
659
660 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
661   if (isMachineConstantPoolEntry())
662     return Val.MachineCPVal->getRelocationInfo();
663   return Val.ConstVal->getRelocationInfo();
664 }
665
666 MachineConstantPool::~MachineConstantPool() {
667   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
668     if (Constants[i].isMachineConstantPoolEntry())
669       delete Constants[i].Val.MachineCPVal;
670 }
671
672 /// CanShareConstantPoolEntry - Test whether the given two constants
673 /// can be allocated the same constant pool entry.
674 static bool CanShareConstantPoolEntry(Constant *A, Constant *B,
675                                       const TargetData *TD) {
676   // Handle the trivial case quickly.
677   if (A == B) return true;
678
679   // If they have the same type but weren't the same constant, quickly
680   // reject them.
681   if (A->getType() == B->getType()) return false;
682
683   // For now, only support constants with the same size.
684   if (TD->getTypeStoreSize(A->getType()) != TD->getTypeStoreSize(B->getType()))
685     return false;
686
687   // If a floating-point value and an integer value have the same encoding,
688   // they can share a constant-pool entry.
689   if (ConstantFP *AFP = dyn_cast<ConstantFP>(A))
690     if (ConstantInt *BI = dyn_cast<ConstantInt>(B))
691       return AFP->getValueAPF().bitcastToAPInt() == BI->getValue();
692   if (ConstantFP *BFP = dyn_cast<ConstantFP>(B))
693     if (ConstantInt *AI = dyn_cast<ConstantInt>(A))
694       return BFP->getValueAPF().bitcastToAPInt() == AI->getValue();
695
696   // Two vectors can share an entry if each pair of corresponding
697   // elements could.
698   if (ConstantVector *AV = dyn_cast<ConstantVector>(A))
699     if (ConstantVector *BV = dyn_cast<ConstantVector>(B)) {
700       if (AV->getType()->getNumElements() != BV->getType()->getNumElements())
701         return false;
702       for (unsigned i = 0, e = AV->getType()->getNumElements(); i != e; ++i)
703         if (!CanShareConstantPoolEntry(AV->getOperand(i),
704                                        BV->getOperand(i), TD))
705           return false;
706       return true;
707     }
708
709   // TODO: Handle other cases.
710
711   return false;
712 }
713
714 /// getConstantPoolIndex - Create a new entry in the constant pool or return
715 /// an existing one.  User must specify the log2 of the minimum required
716 /// alignment for the object.
717 ///
718 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 
719                                                    unsigned Alignment) {
720   assert(Alignment && "Alignment must be specified!");
721   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
722
723   // Check to see if we already have this constant.
724   //
725   // FIXME, this could be made much more efficient for large constant pools.
726   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
727     if (!Constants[i].isMachineConstantPoolEntry() &&
728         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
729       if ((unsigned)Constants[i].getAlignment() < Alignment)
730         Constants[i].Alignment = Alignment;
731       return i;
732     }
733   
734   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
735   return Constants.size()-1;
736 }
737
738 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
739                                                    unsigned Alignment) {
740   assert(Alignment && "Alignment must be specified!");
741   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
742   
743   // Check to see if we already have this constant.
744   //
745   // FIXME, this could be made much more efficient for large constant pools.
746   int Idx = V->getExistingMachineCPValue(this, Alignment);
747   if (Idx != -1)
748     return (unsigned)Idx;
749
750   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
751   return Constants.size()-1;
752 }
753
754 void MachineConstantPool::print(raw_ostream &OS) const {
755   if (Constants.empty()) return;
756
757   OS << "Constant Pool:\n";
758   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
759     OS << "  cp#" << i << ": ";
760     if (Constants[i].isMachineConstantPoolEntry())
761       Constants[i].Val.MachineCPVal->print(OS);
762     else
763       OS << *(Value*)Constants[i].Val.ConstVal;
764     OS << ", align=" << Constants[i].getAlignment();
765     OS << "\n";
766   }
767 }
768
769 void MachineConstantPool::dump() const { print(dbgs()); }