1193323Sed//===-- MachineFunction.cpp -----------------------------------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// Collect native machine code information for a function.  This allows
11193323Sed// target-specific information about the generated code to be stored with each
12193323Sed// function.
13193323Sed//
14193323Sed//===----------------------------------------------------------------------===//
15193323Sed
16234353Sdim#include "llvm/CodeGen/MachineFunction.h"
17249423Sdim#include "llvm/ADT/STLExtras.h"
18249423Sdim#include "llvm/ADT/SmallString.h"
19249423Sdim#include "llvm/Analysis/ConstantFolding.h"
20263508Sdim#include "llvm/Assembly/Writer.h"
21193323Sed#include "llvm/CodeGen/MachineConstantPool.h"
22249423Sdim#include "llvm/CodeGen/MachineFrameInfo.h"
23193323Sed#include "llvm/CodeGen/MachineFunctionPass.h"
24193323Sed#include "llvm/CodeGen/MachineInstr.h"
25193323Sed#include "llvm/CodeGen/MachineJumpTableInfo.h"
26206274Srdivacky#include "llvm/CodeGen/MachineModuleInfo.h"
27193323Sed#include "llvm/CodeGen/MachineRegisterInfo.h"
28193323Sed#include "llvm/CodeGen/Passes.h"
29249423Sdim#include "llvm/DebugInfo.h"
30249423Sdim#include "llvm/IR/DataLayout.h"
31249423Sdim#include "llvm/IR/Function.h"
32203954Srdivacky#include "llvm/MC/MCAsmInfo.h"
33203954Srdivacky#include "llvm/MC/MCContext.h"
34202375Srdivacky#include "llvm/Support/Debug.h"
35249423Sdim#include "llvm/Support/GraphWriter.h"
36249423Sdim#include "llvm/Support/raw_ostream.h"
37249423Sdim#include "llvm/Target/TargetFrameLowering.h"
38195340Sed#include "llvm/Target/TargetLowering.h"
39193323Sed#include "llvm/Target/TargetMachine.h"
40193323Sedusing namespace llvm;
41193323Sed
42203954Srdivacky//===----------------------------------------------------------------------===//
43193323Sed// MachineFunction implementation
44203954Srdivacky//===----------------------------------------------------------------------===//
45193323Sed
46198090Srdivacky// Out of line virtual method.
47198090SrdivackyMachineFunctionInfo::~MachineFunctionInfo() {}
48198090Srdivacky
49193323Sedvoid ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
50193323Sed  MBB->getParent()->DeleteMachineBasicBlock(MBB);
51193323Sed}
52193323Sed
53207618SrdivackyMachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
54218893Sdim                                 unsigned FunctionNum, MachineModuleInfo &mmi,
55218893Sdim                                 GCModuleInfo* gmi)
56218893Sdim  : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
57193323Sed  if (TM.getRegisterInfo())
58263508Sdim    RegInfo = new (Allocator) MachineRegisterInfo(TM);
59193323Sed  else
60193323Sed    RegInfo = 0;
61263508Sdim
62193323Sed  MFInfo = 0;
63263508Sdim  FrameInfo =
64263508Sdim    new (Allocator) MachineFrameInfo(TM,!F->hasFnAttribute("no-realign-stack"));
65263508Sdim
66249423Sdim  if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
67249423Sdim                                       Attribute::StackAlignment))
68243830Sdim    FrameInfo->ensureMaxAlignment(Fn->getAttributes().
69249423Sdim                                getStackAlignment(AttributeSet::FunctionIndex));
70263508Sdim
71263508Sdim  ConstantPool = new (Allocator) MachineConstantPool(TM);
72223017Sdim  Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
73263508Sdim
74223017Sdim  // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
75249423Sdim  if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
76249423Sdim                                        Attribute::OptimizeForSize))
77223017Sdim    Alignment = std::max(Alignment,
78223017Sdim                         TM.getTargetLowering()->getPrefFunctionAlignment());
79263508Sdim
80203954Srdivacky  FunctionNumber = FunctionNum;
81203954Srdivacky  JumpTableInfo = 0;
82193323Sed}
83193323Sed
84193323SedMachineFunction::~MachineFunction() {
85249423Sdim  // Don't call destructors on MachineInstr and MachineOperand. All of their
86249423Sdim  // memory comes from the BumpPtrAllocator which is about to be purged.
87249423Sdim  //
88249423Sdim  // Do call MachineBasicBlock destructors, it contains std::vectors.
89249423Sdim  for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
90249423Sdim    I->Insts.clearAndLeakNodesUnsafely();
91249423Sdim
92193323Sed  InstructionRecycler.clear(Allocator);
93249423Sdim  OperandRecycler.clear(Allocator);
94193323Sed  BasicBlockRecycler.clear(Allocator);
95195098Sed  if (RegInfo) {
96195098Sed    RegInfo->~MachineRegisterInfo();
97195098Sed    Allocator.Deallocate(RegInfo);
98195098Sed  }
99193323Sed  if (MFInfo) {
100195098Sed    MFInfo->~MachineFunctionInfo();
101195098Sed    Allocator.Deallocate(MFInfo);
102193323Sed  }
103239462Sdim
104239462Sdim  FrameInfo->~MachineFrameInfo();
105239462Sdim  Allocator.Deallocate(FrameInfo);
106239462Sdim
107239462Sdim  ConstantPool->~MachineConstantPool();
108239462Sdim  Allocator.Deallocate(ConstantPool);
109239462Sdim
110203954Srdivacky  if (JumpTableInfo) {
111203954Srdivacky    JumpTableInfo->~MachineJumpTableInfo();
112203954Srdivacky    Allocator.Deallocate(JumpTableInfo);
113203954Srdivacky  }
114193323Sed}
115193323Sed
116203954Srdivacky/// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
117203954Srdivacky/// does already exist, allocate one.
118203954SrdivackyMachineJumpTableInfo *MachineFunction::
119203954SrdivackygetOrCreateJumpTableInfo(unsigned EntryKind) {
120203954Srdivacky  if (JumpTableInfo) return JumpTableInfo;
121239462Sdim
122205407Srdivacky  JumpTableInfo = new (Allocator)
123203954Srdivacky    MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
124203954Srdivacky  return JumpTableInfo;
125203954Srdivacky}
126193323Sed
127193323Sed/// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
128193323Sed/// recomputes them.  This guarantees that the MBB numbers are sequential,
129193323Sed/// dense, and match the ordering of the blocks within the function.  If a
130193323Sed/// specific MachineBasicBlock is specified, only that block and those after
131193323Sed/// it are renumbered.
132193323Sedvoid MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
133193323Sed  if (empty()) { MBBNumbering.clear(); return; }
134193323Sed  MachineFunction::iterator MBBI, E = end();
135193323Sed  if (MBB == 0)
136193323Sed    MBBI = begin();
137193323Sed  else
138193323Sed    MBBI = MBB;
139239462Sdim
140193323Sed  // Figure out the block number this should have.
141193323Sed  unsigned BlockNo = 0;
142193323Sed  if (MBBI != begin())
143193323Sed    BlockNo = prior(MBBI)->getNumber()+1;
144239462Sdim
145193323Sed  for (; MBBI != E; ++MBBI, ++BlockNo) {
146193323Sed    if (MBBI->getNumber() != (int)BlockNo) {
147193323Sed      // Remove use of the old number.
148193323Sed      if (MBBI->getNumber() != -1) {
149193323Sed        assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
150193323Sed               "MBB number mismatch!");
151193323Sed        MBBNumbering[MBBI->getNumber()] = 0;
152193323Sed      }
153239462Sdim
154193323Sed      // If BlockNo is already taken, set that block's number to -1.
155193323Sed      if (MBBNumbering[BlockNo])
156193323Sed        MBBNumbering[BlockNo]->setNumber(-1);
157193323Sed
158193323Sed      MBBNumbering[BlockNo] = MBBI;
159193323Sed      MBBI->setNumber(BlockNo);
160193323Sed    }
161239462Sdim  }
162193323Sed
163193323Sed  // Okay, all the blocks are renumbered.  If we have compactified the block
164193323Sed  // numbering, shrink MBBNumbering now.
165193323Sed  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
166193323Sed  MBBNumbering.resize(BlockNo);
167193323Sed}
168193323Sed
169193323Sed/// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
170193323Sed/// of `new MachineInstr'.
171193323Sed///
172193323SedMachineInstr *
173224145SdimMachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
174193323Sed                                    DebugLoc DL, bool NoImp) {
175193323Sed  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
176249423Sdim    MachineInstr(*this, MCID, DL, NoImp);
177193323Sed}
178193323Sed
179193323Sed/// CloneMachineInstr - Create a new MachineInstr which is a copy of the
180203954Srdivacky/// 'Orig' instruction, identical in all ways except the instruction
181193323Sed/// has no parent, prev, or next.
182193323Sed///
183193323SedMachineInstr *
184193323SedMachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
185193323Sed  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
186193323Sed             MachineInstr(*this, *Orig);
187193323Sed}
188193323Sed
189193323Sed/// DeleteMachineInstr - Delete the given MachineInstr.
190193323Sed///
191249423Sdim/// This function also serves as the MachineInstr destructor - the real
192249423Sdim/// ~MachineInstr() destructor must be empty.
193193323Sedvoid
194193323SedMachineFunction::DeleteMachineInstr(MachineInstr *MI) {
195249423Sdim  // Strip it for parts. The operand array and the MI object itself are
196249423Sdim  // independently recyclable.
197249423Sdim  if (MI->Operands)
198249423Sdim    deallocateOperandArray(MI->CapOperands, MI->Operands);
199249423Sdim  // Don't call ~MachineInstr() which must be trivial anyway because
200249423Sdim  // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
201249423Sdim  // destructors.
202193323Sed  InstructionRecycler.Deallocate(Allocator, MI);
203193323Sed}
204193323Sed
205193323Sed/// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
206193323Sed/// instead of `new MachineBasicBlock'.
207193323Sed///
208193323SedMachineBasicBlock *
209193323SedMachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
210193323Sed  return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
211193323Sed             MachineBasicBlock(*this, bb);
212193323Sed}
213193323Sed
214193323Sed/// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
215193323Sed///
216193323Sedvoid
217193323SedMachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
218193323Sed  assert(MBB->getParent() == this && "MBB parent mismatch!");
219193323Sed  MBB->~MachineBasicBlock();
220193323Sed  BasicBlockRecycler.Deallocate(Allocator, MBB);
221193323Sed}
222193323Sed
223198090SrdivackyMachineMemOperand *
224218893SdimMachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
225218893Sdim                                      uint64_t s, unsigned base_alignment,
226234353Sdim                                      const MDNode *TBAAInfo,
227234353Sdim                                      const MDNode *Ranges) {
228218893Sdim  return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
229234353Sdim                                           TBAAInfo, Ranges);
230198090Srdivacky}
231198090Srdivacky
232198090SrdivackyMachineMemOperand *
233198090SrdivackyMachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
234198090Srdivacky                                      int64_t Offset, uint64_t Size) {
235205407Srdivacky  return new (Allocator)
236218893Sdim             MachineMemOperand(MachinePointerInfo(MMO->getValue(),
237218893Sdim                                                  MMO->getOffset()+Offset),
238218893Sdim                               MMO->getFlags(), Size,
239218893Sdim                               MMO->getBaseAlignment(), 0);
240198090Srdivacky}
241198090Srdivacky
242198090SrdivackyMachineInstr::mmo_iterator
243198090SrdivackyMachineFunction::allocateMemRefsArray(unsigned long Num) {
244198090Srdivacky  return Allocator.Allocate<MachineMemOperand *>(Num);
245198090Srdivacky}
246198090Srdivacky
247198090Srdivackystd::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
248198090SrdivackyMachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
249198090Srdivacky                                    MachineInstr::mmo_iterator End) {
250198090Srdivacky  // Count the number of load mem refs.
251198090Srdivacky  unsigned Num = 0;
252198090Srdivacky  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
253198090Srdivacky    if ((*I)->isLoad())
254198090Srdivacky      ++Num;
255198090Srdivacky
256198090Srdivacky  // Allocate a new array and populate it with the load information.
257198090Srdivacky  MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
258198090Srdivacky  unsigned Index = 0;
259198090Srdivacky  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
260198090Srdivacky    if ((*I)->isLoad()) {
261198090Srdivacky      if (!(*I)->isStore())
262198090Srdivacky        // Reuse the MMO.
263198090Srdivacky        Result[Index] = *I;
264198090Srdivacky      else {
265198090Srdivacky        // Clone the MMO and unset the store flag.
266198090Srdivacky        MachineMemOperand *JustLoad =
267218893Sdim          getMachineMemOperand((*I)->getPointerInfo(),
268198090Srdivacky                               (*I)->getFlags() & ~MachineMemOperand::MOStore,
269218893Sdim                               (*I)->getSize(), (*I)->getBaseAlignment(),
270218893Sdim                               (*I)->getTBAAInfo());
271198090Srdivacky        Result[Index] = JustLoad;
272198090Srdivacky      }
273198090Srdivacky      ++Index;
274198090Srdivacky    }
275198090Srdivacky  }
276198090Srdivacky  return std::make_pair(Result, Result + Num);
277198090Srdivacky}
278198090Srdivacky
279198090Srdivackystd::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
280198090SrdivackyMachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
281198090Srdivacky                                     MachineInstr::mmo_iterator End) {
282198090Srdivacky  // Count the number of load mem refs.
283198090Srdivacky  unsigned Num = 0;
284198090Srdivacky  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
285198090Srdivacky    if ((*I)->isStore())
286198090Srdivacky      ++Num;
287198090Srdivacky
288198090Srdivacky  // Allocate a new array and populate it with the store information.
289198090Srdivacky  MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
290198090Srdivacky  unsigned Index = 0;
291198090Srdivacky  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
292198090Srdivacky    if ((*I)->isStore()) {
293198090Srdivacky      if (!(*I)->isLoad())
294198090Srdivacky        // Reuse the MMO.
295198090Srdivacky        Result[Index] = *I;
296198090Srdivacky      else {
297198090Srdivacky        // Clone the MMO and unset the load flag.
298198090Srdivacky        MachineMemOperand *JustStore =
299218893Sdim          getMachineMemOperand((*I)->getPointerInfo(),
300198090Srdivacky                               (*I)->getFlags() & ~MachineMemOperand::MOLoad,
301218893Sdim                               (*I)->getSize(), (*I)->getBaseAlignment(),
302218893Sdim                               (*I)->getTBAAInfo());
303198090Srdivacky        Result[Index] = JustStore;
304198090Srdivacky      }
305198090Srdivacky      ++Index;
306198090Srdivacky    }
307198090Srdivacky  }
308198090Srdivacky  return std::make_pair(Result, Result + Num);
309198090Srdivacky}
310198090Srdivacky
311243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
312193323Sedvoid MachineFunction::dump() const {
313202375Srdivacky  print(dbgs());
314193323Sed}
315243830Sdim#endif
316193323Sed
317243830SdimStringRef MachineFunction::getName() const {
318243830Sdim  assert(getFunction() && "No function!");
319243830Sdim  return getFunction()->getName();
320243830Sdim}
321243830Sdim
322218893Sdimvoid MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
323243830Sdim  OS << "# Machine code for function " << getName() << ": ";
324234353Sdim  if (RegInfo) {
325234353Sdim    OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
326234353Sdim    if (!RegInfo->tracksLiveness())
327234353Sdim      OS << ", not tracking liveness";
328234353Sdim  }
329234353Sdim  OS << '\n';
330193323Sed
331193323Sed  // Print Frame Information
332193323Sed  FrameInfo->print(*this, OS);
333239462Sdim
334193323Sed  // Print JumpTable Information
335203954Srdivacky  if (JumpTableInfo)
336203954Srdivacky    JumpTableInfo->print(OS);
337193323Sed
338193323Sed  // Print Constant Pool
339198090Srdivacky  ConstantPool->print(OS);
340239462Sdim
341193323Sed  const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
342239462Sdim
343193323Sed  if (RegInfo && !RegInfo->livein_empty()) {
344198892Srdivacky    OS << "Function Live Ins: ";
345193323Sed    for (MachineRegisterInfo::livein_iterator
346193323Sed         I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
347223017Sdim      OS << PrintReg(I->first, TRI);
348193323Sed      if (I->second)
349223017Sdim        OS << " in " << PrintReg(I->second, TRI);
350200581Srdivacky      if (llvm::next(I) != E)
351198892Srdivacky        OS << ", ";
352193323Sed    }
353198090Srdivacky    OS << '\n';
354193323Sed  }
355239462Sdim
356198892Srdivacky  for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
357198892Srdivacky    OS << '\n';
358218893Sdim    BB->print(OS, Indexes);
359198892Srdivacky  }
360193323Sed
361243830Sdim  OS << "\n# End machine code for function " << getName() << ".\n\n";
362193323Sed}
363193323Sed
364193323Sednamespace llvm {
365193323Sed  template<>
366193323Sed  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
367199989Srdivacky
368199989Srdivacky  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
369199989Srdivacky
370193323Sed    static std::string getGraphName(const MachineFunction *F) {
371243830Sdim      return "CFG for '" + F->getName().str() + "' function";
372193323Sed    }
373193323Sed
374199989Srdivacky    std::string getNodeLabel(const MachineBasicBlock *Node,
375199989Srdivacky                             const MachineFunction *Graph) {
376198090Srdivacky      std::string OutStr;
377198090Srdivacky      {
378198090Srdivacky        raw_string_ostream OSS(OutStr);
379218893Sdim
380218893Sdim        if (isSimple()) {
381218893Sdim          OSS << "BB#" << Node->getNumber();
382218893Sdim          if (const BasicBlock *BB = Node->getBasicBlock())
383218893Sdim            OSS << ": " << BB->getName();
384218893Sdim        } else
385198090Srdivacky          Node->print(OSS);
386193323Sed      }
387193323Sed
388193323Sed      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
389193323Sed
390193323Sed      // Process string output to make it nicer...
391193323Sed      for (unsigned i = 0; i != OutStr.length(); ++i)
392193323Sed        if (OutStr[i] == '\n') {                            // Left justify
393193323Sed          OutStr[i] = '\\';
394193323Sed          OutStr.insert(OutStr.begin()+i+1, 'l');
395193323Sed        }
396193323Sed      return OutStr;
397193323Sed    }
398193323Sed  };
399193323Sed}
400193323Sed
401193323Sedvoid MachineFunction::viewCFG() const
402193323Sed{
403193323Sed#ifndef NDEBUG
404243830Sdim  ViewGraph(this, "mf" + getName());
405193323Sed#else
406210299Sed  errs() << "MachineFunction::viewCFG is only available in debug builds on "
407198090Srdivacky         << "systems with Graphviz or gv!\n";
408193323Sed#endif // NDEBUG
409193323Sed}
410193323Sed
411193323Sedvoid MachineFunction::viewCFGOnly() const
412193323Sed{
413195098Sed#ifndef NDEBUG
414243830Sdim  ViewGraph(this, "mf" + getName(), true);
415195098Sed#else
416210299Sed  errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
417198090Srdivacky         << "systems with Graphviz or gv!\n";
418195098Sed#endif // NDEBUG
419193323Sed}
420193323Sed
421193323Sed/// addLiveIn - Add the specified physical register as a live-in value and
422193323Sed/// create a corresponding virtual register for it.
423193323Sedunsigned MachineFunction::addLiveIn(unsigned PReg,
424219077Sdim                                    const TargetRegisterClass *RC) {
425208599Srdivacky  MachineRegisterInfo &MRI = getRegInfo();
426208599Srdivacky  unsigned VReg = MRI.getLiveInVirtReg(PReg);
427208599Srdivacky  if (VReg) {
428208599Srdivacky    assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
429208599Srdivacky    return VReg;
430208599Srdivacky  }
431208599Srdivacky  VReg = MRI.createVirtualRegister(RC);
432208599Srdivacky  MRI.addLiveIn(PReg, VReg);
433193323Sed  return VReg;
434193323Sed}
435193323Sed
436203954Srdivacky/// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
437203954Srdivacky/// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
438203954Srdivacky/// normal 'L' label is returned.
439203954SrdivackyMCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
440203954Srdivacky                                        bool isLinkerPrivate) const {
441203954Srdivacky  assert(JumpTableInfo && "No jump tables");
442203954Srdivacky  assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
443203954Srdivacky  const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
444239462Sdim
445203954Srdivacky  const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
446203954Srdivacky                                         MAI.getPrivateGlobalPrefix();
447203954Srdivacky  SmallString<60> Name;
448203954Srdivacky  raw_svector_ostream(Name)
449203954Srdivacky    << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
450206083Srdivacky  return Ctx.GetOrCreateSymbol(Name.str());
451203954Srdivacky}
452203954Srdivacky
453218893Sdim/// getPICBaseSymbol - Return a function-local symbol to represent the PIC
454218893Sdim/// base.
455218893SdimMCSymbol *MachineFunction::getPICBaseSymbol() const {
456218893Sdim  const MCAsmInfo &MAI = *Target.getMCAsmInfo();
457218893Sdim  return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
458218893Sdim                               Twine(getFunctionNumber())+"$pb");
459218893Sdim}
460203954Srdivacky
461193323Sed//===----------------------------------------------------------------------===//
462193323Sed//  MachineFrameInfo implementation
463193323Sed//===----------------------------------------------------------------------===//
464193323Sed
465263508Sdimconst TargetFrameLowering *MachineFrameInfo::getFrameLowering() const {
466263508Sdim  return TM.getFrameLowering();
467263508Sdim}
468263508Sdim
469249423Sdim/// ensureMaxAlignment - Make sure the function is at least Align bytes
470249423Sdim/// aligned.
471249423Sdimvoid MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
472263508Sdim  if (!getFrameLowering()->isStackRealignable() || !RealignOption)
473263508Sdim    assert(Align <= getFrameLowering()->getStackAlignment() &&
474249423Sdim           "For targets without stack realignment, Align is out of limit!");
475249423Sdim  if (MaxAlignment < Align) MaxAlignment = Align;
476249423Sdim}
477249423Sdim
478249423Sdim/// clampStackAlignment - Clamp the alignment if requested and emit a warning.
479249423Sdimstatic inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
480249423Sdim                                           unsigned StackAlign) {
481249423Sdim  if (!ShouldClamp || Align <= StackAlign)
482249423Sdim    return Align;
483249423Sdim  DEBUG(dbgs() << "Warning: requested alignment " << Align
484249423Sdim               << " exceeds the stack alignment " << StackAlign
485249423Sdim               << " when stack realignment is off" << '\n');
486249423Sdim  return StackAlign;
487249423Sdim}
488249423Sdim
489249423Sdim/// CreateStackObject - Create a new statically sized stack object, returning
490249423Sdim/// a nonnegative identifier to represent it.
491249423Sdim///
492249423Sdimint MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
493249423Sdim                      bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
494249423Sdim  assert(Size != 0 && "Cannot allocate zero size stack objects!");
495263508Sdim  Alignment =
496263508Sdim    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
497263508Sdim                          !RealignOption,
498263508Sdim                        Alignment, getFrameLowering()->getStackAlignment());
499249423Sdim  Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
500249423Sdim                                Alloca));
501249423Sdim  int Index = (int)Objects.size() - NumFixedObjects - 1;
502249423Sdim  assert(Index >= 0 && "Bad frame index!");
503249423Sdim  ensureMaxAlignment(Alignment);
504249423Sdim  return Index;
505249423Sdim}
506249423Sdim
507249423Sdim/// CreateSpillStackObject - Create a new statically sized stack object that
508249423Sdim/// represents a spill slot, returning a nonnegative identifier to represent
509249423Sdim/// it.
510249423Sdim///
511249423Sdimint MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
512249423Sdim                                             unsigned Alignment) {
513263508Sdim  Alignment =
514263508Sdim    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
515263508Sdim                          !RealignOption,
516263508Sdim                        Alignment, getFrameLowering()->getStackAlignment());
517249423Sdim  CreateStackObject(Size, Alignment, true, false);
518249423Sdim  int Index = (int)Objects.size() - NumFixedObjects - 1;
519249423Sdim  ensureMaxAlignment(Alignment);
520249423Sdim  return Index;
521249423Sdim}
522249423Sdim
523249423Sdim/// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
524249423Sdim/// variable sized object has been created.  This must be created whenever a
525249423Sdim/// variable sized object is created, whether or not the index returned is
526249423Sdim/// actually used.
527249423Sdim///
528263765Sdimint MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
529263765Sdim                                                const AllocaInst *Alloca) {
530249423Sdim  HasVarSizedObjects = true;
531263508Sdim  Alignment =
532263508Sdim    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
533263508Sdim                          !RealignOption,
534263508Sdim                        Alignment, getFrameLowering()->getStackAlignment());
535263765Sdim  Objects.push_back(StackObject(0, Alignment, 0, false, false, true, Alloca));
536249423Sdim  ensureMaxAlignment(Alignment);
537249423Sdim  return (int)Objects.size()-NumFixedObjects-1;
538249423Sdim}
539249423Sdim
540193323Sed/// CreateFixedObject - Create a new object at a fixed location on the stack.
541193323Sed/// All fixed objects should be created before other objects are created for
542193323Sed/// efficiency. By default, fixed objects are immutable. This returns an
543193323Sed/// index with a negative value.
544193323Sed///
545193323Sedint MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
546210299Sed                                        bool Immutable) {
547193323Sed  assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
548210299Sed  // The alignment of the frame index can be determined from its offset from
549210299Sed  // the incoming frame position.  If the frame object is at offset 32 and
550210299Sed  // the stack is guaranteed to be 16-byte aligned, then we know that the
551210299Sed  // object is 16-byte aligned.
552263508Sdim  unsigned StackAlign = getFrameLowering()->getStackAlignment();
553210299Sed  unsigned Align = MinAlign(SPOffset, StackAlign);
554263508Sdim  Align =
555263508Sdim    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
556263508Sdim                          !RealignOption,
557263508Sdim                        Align, getFrameLowering()->getStackAlignment());
558210299Sed  Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
559243830Sdim                                              /*isSS*/   false,
560243830Sdim                                              /*NeedSP*/ false,
561243830Sdim                                              /*Alloca*/ 0));
562193323Sed  return -++NumFixedObjects;
563193323Sed}
564193323Sed
565193323Sed
566198090SrdivackyBitVector
567198090SrdivackyMachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
568198090Srdivacky  assert(MBB && "MBB must be valid");
569198090Srdivacky  const MachineFunction *MF = MBB->getParent();
570198090Srdivacky  assert(MF && "MBB must be part of a MachineFunction");
571198090Srdivacky  const TargetMachine &TM = MF->getTarget();
572198090Srdivacky  const TargetRegisterInfo *TRI = TM.getRegisterInfo();
573198090Srdivacky  BitVector BV(TRI->getNumRegs());
574198090Srdivacky
575198090Srdivacky  // Before CSI is calculated, no registers are considered pristine. They can be
576198090Srdivacky  // freely used and PEI will make sure they are saved.
577198090Srdivacky  if (!isCalleeSavedInfoValid())
578198090Srdivacky    return BV;
579198090Srdivacky
580234353Sdim  for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
581198090Srdivacky    BV.set(*CSR);
582198090Srdivacky
583198090Srdivacky  // The entry MBB always has all CSRs pristine.
584198090Srdivacky  if (MBB == &MF->front())
585198090Srdivacky    return BV;
586198090Srdivacky
587198090Srdivacky  // On other MBBs the saved CSRs are not pristine.
588198090Srdivacky  const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
589198090Srdivacky  for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
590198090Srdivacky         E = CSI.end(); I != E; ++I)
591198090Srdivacky    BV.reset(I->getReg());
592198090Srdivacky
593198090Srdivacky  return BV;
594198090Srdivacky}
595198090Srdivacky
596249423Sdimunsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
597249423Sdim  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
598249423Sdim  const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
599249423Sdim  unsigned MaxAlign = getMaxAlignment();
600249423Sdim  int Offset = 0;
601198090Srdivacky
602249423Sdim  // This code is very, very similar to PEI::calculateFrameObjectOffsets().
603249423Sdim  // It really should be refactored to share code. Until then, changes
604249423Sdim  // should keep in mind that there's tight coupling between the two.
605249423Sdim
606249423Sdim  for (int i = getObjectIndexBegin(); i != 0; ++i) {
607249423Sdim    int FixedOff = -getObjectOffset(i);
608249423Sdim    if (FixedOff > Offset) Offset = FixedOff;
609249423Sdim  }
610249423Sdim  for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
611249423Sdim    if (isDeadObjectIndex(i))
612249423Sdim      continue;
613249423Sdim    Offset += getObjectSize(i);
614249423Sdim    unsigned Align = getObjectAlignment(i);
615249423Sdim    // Adjust to alignment boundary
616249423Sdim    Offset = (Offset+Align-1)/Align*Align;
617249423Sdim
618249423Sdim    MaxAlign = std::max(Align, MaxAlign);
619249423Sdim  }
620249423Sdim
621249423Sdim  if (adjustsStack() && TFI->hasReservedCallFrame(MF))
622249423Sdim    Offset += getMaxCallFrameSize();
623249423Sdim
624249423Sdim  // Round up the size to a multiple of the alignment.  If the function has
625249423Sdim  // any calls or alloca's, align to the target's StackAlignment value to
626249423Sdim  // ensure that the callee's frame or the alloca data is suitably aligned;
627249423Sdim  // otherwise, for leaf functions, align to the TransientStackAlignment
628249423Sdim  // value.
629249423Sdim  unsigned StackAlign;
630249423Sdim  if (adjustsStack() || hasVarSizedObjects() ||
631249423Sdim      (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
632249423Sdim    StackAlign = TFI->getStackAlignment();
633249423Sdim  else
634249423Sdim    StackAlign = TFI->getTransientStackAlignment();
635249423Sdim
636249423Sdim  // If the frame pointer is eliminated, all frame offsets will be relative to
637249423Sdim  // SP not FP. Align to MaxAlign so this works.
638249423Sdim  StackAlign = std::max(StackAlign, MaxAlign);
639249423Sdim  unsigned AlignMask = StackAlign - 1;
640249423Sdim  Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
641249423Sdim
642249423Sdim  return (unsigned)Offset;
643249423Sdim}
644249423Sdim
645198090Srdivackyvoid MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
646198892Srdivacky  if (Objects.empty()) return;
647198892Srdivacky
648218893Sdim  const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
649193323Sed  int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
650193323Sed
651198892Srdivacky  OS << "Frame Objects:\n";
652198892Srdivacky
653193323Sed  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
654193323Sed    const StackObject &SO = Objects[i];
655198892Srdivacky    OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
656193323Sed    if (SO.Size == ~0ULL) {
657193323Sed      OS << "dead\n";
658193323Sed      continue;
659193323Sed    }
660193323Sed    if (SO.Size == 0)
661193323Sed      OS << "variable sized";
662193323Sed    else
663198892Srdivacky      OS << "size=" << SO.Size;
664198892Srdivacky    OS << ", align=" << SO.Alignment;
665193323Sed
666193323Sed    if (i < NumFixedObjects)
667198892Srdivacky      OS << ", fixed";
668193323Sed    if (i < NumFixedObjects || SO.SPOffset != -1) {
669193323Sed      int64_t Off = SO.SPOffset - ValOffset;
670198892Srdivacky      OS << ", at location [SP";
671193323Sed      if (Off > 0)
672193323Sed        OS << "+" << Off;
673193323Sed      else if (Off < 0)
674193323Sed        OS << Off;
675193323Sed      OS << "]";
676193323Sed    }
677193323Sed    OS << "\n";
678193323Sed  }
679193323Sed}
680193323Sed
681243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
682193323Sedvoid MachineFrameInfo::dump(const MachineFunction &MF) const {
683202375Srdivacky  print(MF, dbgs());
684193323Sed}
685243830Sdim#endif
686193323Sed
687193323Sed//===----------------------------------------------------------------------===//
688193323Sed//  MachineJumpTableInfo implementation
689193323Sed//===----------------------------------------------------------------------===//
690193323Sed
691203954Srdivacky/// getEntrySize - Return the size of each entry in the jump table.
692243830Sdimunsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
693203954Srdivacky  // The size of a jump table entry is 4 bytes unless the entry is just the
694203954Srdivacky  // address of a block, in which case it is the pointer size.
695203954Srdivacky  switch (getEntryKind()) {
696203954Srdivacky  case MachineJumpTableInfo::EK_BlockAddress:
697203954Srdivacky    return TD.getPointerSize();
698234353Sdim  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
699234353Sdim    return 8;
700203954Srdivacky  case MachineJumpTableInfo::EK_GPRel32BlockAddress:
701203954Srdivacky  case MachineJumpTableInfo::EK_LabelDifference32:
702203954Srdivacky  case MachineJumpTableInfo::EK_Custom32:
703203954Srdivacky    return 4;
704205218Srdivacky  case MachineJumpTableInfo::EK_Inline:
705205218Srdivacky    return 0;
706203954Srdivacky  }
707234353Sdim  llvm_unreachable("Unknown jump table encoding!");
708203954Srdivacky}
709203954Srdivacky
710203954Srdivacky/// getEntryAlignment - Return the alignment of each entry in the jump table.
711243830Sdimunsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
712203954Srdivacky  // The alignment of a jump table entry is the alignment of int32 unless the
713203954Srdivacky  // entry is just the address of a block, in which case it is the pointer
714203954Srdivacky  // alignment.
715203954Srdivacky  switch (getEntryKind()) {
716203954Srdivacky  case MachineJumpTableInfo::EK_BlockAddress:
717203954Srdivacky    return TD.getPointerABIAlignment();
718234353Sdim  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
719234353Sdim    return TD.getABIIntegerTypeAlignment(64);
720203954Srdivacky  case MachineJumpTableInfo::EK_GPRel32BlockAddress:
721203954Srdivacky  case MachineJumpTableInfo::EK_LabelDifference32:
722203954Srdivacky  case MachineJumpTableInfo::EK_Custom32:
723203954Srdivacky    return TD.getABIIntegerTypeAlignment(32);
724205218Srdivacky  case MachineJumpTableInfo::EK_Inline:
725205218Srdivacky    return 1;
726203954Srdivacky  }
727234353Sdim  llvm_unreachable("Unknown jump table encoding!");
728203954Srdivacky}
729203954Srdivacky
730205407Srdivacky/// createJumpTableIndex - Create a new jump table entry in the jump table info.
731193323Sed///
732205407Srdivackyunsigned MachineJumpTableInfo::createJumpTableIndex(
733193323Sed                               const std::vector<MachineBasicBlock*> &DestBBs) {
734193323Sed  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
735193323Sed  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
736193323Sed  return JumpTables.size()-1;
737193323Sed}
738193323Sed
739193323Sed/// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
740193323Sed/// the jump tables to branch to New instead.
741203954Srdivackybool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
742203954Srdivacky                                                  MachineBasicBlock *New) {
743193323Sed  assert(Old != New && "Not making a change?");
744193323Sed  bool MadeChange = false;
745199481Srdivacky  for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
746199481Srdivacky    ReplaceMBBInJumpTable(i, Old, New);
747193323Sed  return MadeChange;
748193323Sed}
749193323Sed
750199481Srdivacky/// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
751199481Srdivacky/// the jump table to branch to New instead.
752203954Srdivackybool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
753203954Srdivacky                                                 MachineBasicBlock *Old,
754203954Srdivacky                                                 MachineBasicBlock *New) {
755199481Srdivacky  assert(Old != New && "Not making a change?");
756199481Srdivacky  bool MadeChange = false;
757199481Srdivacky  MachineJumpTableEntry &JTE = JumpTables[Idx];
758199481Srdivacky  for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
759199481Srdivacky    if (JTE.MBBs[j] == Old) {
760199481Srdivacky      JTE.MBBs[j] = New;
761199481Srdivacky      MadeChange = true;
762199481Srdivacky    }
763199481Srdivacky  return MadeChange;
764199481Srdivacky}
765199481Srdivacky
766198090Srdivackyvoid MachineJumpTableInfo::print(raw_ostream &OS) const {
767198892Srdivacky  if (JumpTables.empty()) return;
768198892Srdivacky
769198892Srdivacky  OS << "Jump Tables:\n";
770198892Srdivacky
771193323Sed  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
772198892Srdivacky    OS << "  jt#" << i << ": ";
773198892Srdivacky    for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
774198892Srdivacky      OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
775193323Sed  }
776198892Srdivacky
777198892Srdivacky  OS << '\n';
778193323Sed}
779193323Sed
780243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
781202375Srdivackyvoid MachineJumpTableInfo::dump() const { print(dbgs()); }
782243830Sdim#endif
783193323Sed
784193323Sed
785193323Sed//===----------------------------------------------------------------------===//
786193323Sed//  MachineConstantPool implementation
787193323Sed//===----------------------------------------------------------------------===//
788193323Sed
789234353Sdimvoid MachineConstantPoolValue::anchor() { }
790234353Sdim
791263508Sdimconst DataLayout *MachineConstantPool::getDataLayout() const {
792263508Sdim  return TM.getDataLayout();
793263508Sdim}
794263508Sdim
795226633SdimType *MachineConstantPoolEntry::getType() const {
796193323Sed  if (isMachineConstantPoolEntry())
797198090Srdivacky    return Val.MachineCPVal->getType();
798193323Sed  return Val.ConstVal->getType();
799193323Sed}
800193323Sed
801198090Srdivacky
802198090Srdivackyunsigned MachineConstantPoolEntry::getRelocationInfo() const {
803198090Srdivacky  if (isMachineConstantPoolEntry())
804198090Srdivacky    return Val.MachineCPVal->getRelocationInfo();
805198090Srdivacky  return Val.ConstVal->getRelocationInfo();
806198090Srdivacky}
807198090Srdivacky
808193323SedMachineConstantPool::~MachineConstantPool() {
809193323Sed  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
810193323Sed    if (Constants[i].isMachineConstantPoolEntry())
811193323Sed      delete Constants[i].Val.MachineCPVal;
812219077Sdim  for (DenseSet<MachineConstantPoolValue*>::iterator I =
813219077Sdim       MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
814219077Sdim       I != E; ++I)
815219077Sdim    delete *I;
816193323Sed}
817193323Sed
818198892Srdivacky/// CanShareConstantPoolEntry - Test whether the given two constants
819198892Srdivacky/// can be allocated the same constant pool entry.
820207618Srdivackystatic bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
821243830Sdim                                      const DataLayout *TD) {
822198892Srdivacky  // Handle the trivial case quickly.
823198892Srdivacky  if (A == B) return true;
824198892Srdivacky
825198892Srdivacky  // If they have the same type but weren't the same constant, quickly
826198892Srdivacky  // reject them.
827198892Srdivacky  if (A->getType() == B->getType()) return false;
828198892Srdivacky
829234353Sdim  // We can't handle structs or arrays.
830234353Sdim  if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
831234353Sdim      isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
832234353Sdim    return false;
833234353Sdim
834198892Srdivacky  // For now, only support constants with the same size.
835234353Sdim  uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
836234353Sdim  if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
837234353Sdim      StoreSize > 128)
838198892Srdivacky    return false;
839198892Srdivacky
840234353Sdim  Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
841198892Srdivacky
842234353Sdim  // Try constant folding a bitcast of both instructions to an integer.  If we
843234353Sdim  // get two identical ConstantInt's, then we are good to share them.  We use
844234353Sdim  // the constant folding APIs to do this so that we get the benefit of
845243830Sdim  // DataLayout.
846234353Sdim  if (isa<PointerType>(A->getType()))
847234353Sdim    A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
848234353Sdim                                 const_cast<Constant*>(A), TD);
849234353Sdim  else if (A->getType() != IntTy)
850234353Sdim    A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
851234353Sdim                                 const_cast<Constant*>(A), TD);
852234353Sdim  if (isa<PointerType>(B->getType()))
853234353Sdim    B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
854234353Sdim                                 const_cast<Constant*>(B), TD);
855234353Sdim  else if (B->getType() != IntTy)
856234353Sdim    B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
857234353Sdim                                 const_cast<Constant*>(B), TD);
858239462Sdim
859234353Sdim  return A == B;
860198892Srdivacky}
861198892Srdivacky
862193323Sed/// getConstantPoolIndex - Create a new entry in the constant pool or return
863193323Sed/// an existing one.  User must specify the log2 of the minimum required
864193323Sed/// alignment for the object.
865193323Sed///
866207618Srdivackyunsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
867193323Sed                                                   unsigned Alignment) {
868193323Sed  assert(Alignment && "Alignment must be specified!");
869193323Sed  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
870198892Srdivacky
871193323Sed  // Check to see if we already have this constant.
872193323Sed  //
873193323Sed  // FIXME, this could be made much more efficient for large constant pools.
874193323Sed  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
875198892Srdivacky    if (!Constants[i].isMachineConstantPoolEntry() &&
876263508Sdim        CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
877263508Sdim                                  getDataLayout())) {
878198892Srdivacky      if ((unsigned)Constants[i].getAlignment() < Alignment)
879198892Srdivacky        Constants[i].Alignment = Alignment;
880193323Sed      return i;
881198892Srdivacky    }
882239462Sdim
883193323Sed  Constants.push_back(MachineConstantPoolEntry(C, Alignment));
884193323Sed  return Constants.size()-1;
885193323Sed}
886193323Sed
887193323Sedunsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
888193323Sed                                                   unsigned Alignment) {
889193323Sed  assert(Alignment && "Alignment must be specified!");
890193323Sed  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
891239462Sdim
892193323Sed  // Check to see if we already have this constant.
893193323Sed  //
894193323Sed  // FIXME, this could be made much more efficient for large constant pools.
895193323Sed  int Idx = V->getExistingMachineCPValue(this, Alignment);
896219077Sdim  if (Idx != -1) {
897219077Sdim    MachineCPVsSharingEntries.insert(V);
898193323Sed    return (unsigned)Idx;
899219077Sdim  }
900193323Sed
901193323Sed  Constants.push_back(MachineConstantPoolEntry(V, Alignment));
902193323Sed  return Constants.size()-1;
903193323Sed}
904193323Sed
905193323Sedvoid MachineConstantPool::print(raw_ostream &OS) const {
906198892Srdivacky  if (Constants.empty()) return;
907198892Srdivacky
908198892Srdivacky  OS << "Constant Pool:\n";
909193323Sed  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
910198892Srdivacky    OS << "  cp#" << i << ": ";
911193323Sed    if (Constants[i].isMachineConstantPoolEntry())
912193323Sed      Constants[i].Val.MachineCPVal->print(OS);
913193323Sed    else
914263508Sdim      WriteAsOperand(OS, Constants[i].Val.ConstVal, /*PrintType=*/false);
915198892Srdivacky    OS << ", align=" << Constants[i].getAlignment();
916193323Sed    OS << "\n";
917193323Sed  }
918193323Sed}
919193323Sed
920243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
921202375Srdivackyvoid MachineConstantPool::dump() const { print(dbgs()); }
922243830Sdim#endif
923