MachineFunction.cpp revision 263508
1266423Sjfv//===-- MachineFunction.cpp -----------------------------------------------===//
2266423Sjfv//
3266423Sjfv//                     The LLVM Compiler Infrastructure
4266423Sjfv//
5266423Sjfv// This file is distributed under the University of Illinois Open Source
6266423Sjfv// License. See LICENSE.TXT for details.
7266423Sjfv//
8266423Sjfv//===----------------------------------------------------------------------===//
9266423Sjfv//
10266423Sjfv// Collect native machine code information for a function.  This allows
11266423Sjfv// target-specific information about the generated code to be stored with each
12266423Sjfv// function.
13266423Sjfv//
14266423Sjfv//===----------------------------------------------------------------------===//
15266423Sjfv
16266423Sjfv#include "llvm/CodeGen/MachineFunction.h"
17266423Sjfv#include "llvm/ADT/STLExtras.h"
18266423Sjfv#include "llvm/ADT/SmallString.h"
19266423Sjfv#include "llvm/Analysis/ConstantFolding.h"
20266423Sjfv#include "llvm/Assembly/Writer.h"
21266423Sjfv#include "llvm/CodeGen/MachineConstantPool.h"
22266423Sjfv#include "llvm/CodeGen/MachineFrameInfo.h"
23266423Sjfv#include "llvm/CodeGen/MachineFunctionPass.h"
24266423Sjfv#include "llvm/CodeGen/MachineInstr.h"
25266423Sjfv#include "llvm/CodeGen/MachineJumpTableInfo.h"
26266423Sjfv#include "llvm/CodeGen/MachineModuleInfo.h"
27266423Sjfv#include "llvm/CodeGen/MachineRegisterInfo.h"
28266423Sjfv#include "llvm/CodeGen/Passes.h"
29266423Sjfv#include "llvm/DebugInfo.h"
30266423Sjfv#include "llvm/IR/DataLayout.h"
31266423Sjfv#include "llvm/IR/Function.h"
32266423Sjfv#include "llvm/MC/MCAsmInfo.h"
33266423Sjfv#include "llvm/MC/MCContext.h"
34266423Sjfv#include "llvm/Support/Debug.h"
35266423Sjfv#include "llvm/Support/GraphWriter.h"
36266423Sjfv#include "llvm/Support/raw_ostream.h"
37266423Sjfv#include "llvm/Target/TargetFrameLowering.h"
38266423Sjfv#include "llvm/Target/TargetLowering.h"
39266423Sjfv#include "llvm/Target/TargetMachine.h"
40266423Sjfvusing namespace llvm;
41266423Sjfv
42266423Sjfv//===----------------------------------------------------------------------===//
43266423Sjfv// MachineFunction implementation
44266423Sjfv//===----------------------------------------------------------------------===//
45266423Sjfv
46266423Sjfv// Out of line virtual method.
47266423SjfvMachineFunctionInfo::~MachineFunctionInfo() {}
48266423Sjfv
49266423Sjfvvoid ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
50266423Sjfv  MBB->getParent()->DeleteMachineBasicBlock(MBB);
51266423Sjfv}
52266423Sjfv
53266423SjfvMachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
54266423Sjfv                                 unsigned FunctionNum, MachineModuleInfo &mmi,
55266423Sjfv                                 GCModuleInfo* gmi)
56266423Sjfv  : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
57266423Sjfv  if (TM.getRegisterInfo())
58266423Sjfv    RegInfo = new (Allocator) MachineRegisterInfo(TM);
59270346Sjfv  else
60266423Sjfv    RegInfo = 0;
61266423Sjfv
62266423Sjfv  MFInfo = 0;
63266423Sjfv  FrameInfo =
64266423Sjfv    new (Allocator) MachineFrameInfo(TM,!F->hasFnAttribute("no-realign-stack"));
65266423Sjfv
66266423Sjfv  if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
67269198Sjfv                                       Attribute::StackAlignment))
68266423Sjfv    FrameInfo->ensureMaxAlignment(Fn->getAttributes().
69266423Sjfv                                getStackAlignment(AttributeSet::FunctionIndex));
70269198Sjfv
71266423Sjfv  ConstantPool = new (Allocator) MachineConstantPool(TM);
72266423Sjfv  Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
73266423Sjfv
74266423Sjfv  // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
75266423Sjfv  if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
76266423Sjfv                                        Attribute::OptimizeForSize))
77266423Sjfv    Alignment = std::max(Alignment,
78266423Sjfv                         TM.getTargetLowering()->getPrefFunctionAlignment());
79266423Sjfv
80266423Sjfv  FunctionNumber = FunctionNum;
81266423Sjfv  JumpTableInfo = 0;
82266423Sjfv}
83266423Sjfv
84266423SjfvMachineFunction::~MachineFunction() {
85266423Sjfv  // Don't call destructors on MachineInstr and MachineOperand. All of their
86266423Sjfv  // memory comes from the BumpPtrAllocator which is about to be purged.
87266423Sjfv  //
88266423Sjfv  // Do call MachineBasicBlock destructors, it contains std::vectors.
89266423Sjfv  for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
90266423Sjfv    I->Insts.clearAndLeakNodesUnsafely();
91266423Sjfv
92266423Sjfv  InstructionRecycler.clear(Allocator);
93266423Sjfv  OperandRecycler.clear(Allocator);
94266423Sjfv  BasicBlockRecycler.clear(Allocator);
95266423Sjfv  if (RegInfo) {
96266423Sjfv    RegInfo->~MachineRegisterInfo();
97266423Sjfv    Allocator.Deallocate(RegInfo);
98266423Sjfv  }
99266423Sjfv  if (MFInfo) {
100266423Sjfv    MFInfo->~MachineFunctionInfo();
101266423Sjfv    Allocator.Deallocate(MFInfo);
102266423Sjfv  }
103266423Sjfv
104266423Sjfv  FrameInfo->~MachineFrameInfo();
105266423Sjfv  Allocator.Deallocate(FrameInfo);
106266423Sjfv
107266423Sjfv  ConstantPool->~MachineConstantPool();
108266423Sjfv  Allocator.Deallocate(ConstantPool);
109266423Sjfv
110266423Sjfv  if (JumpTableInfo) {
111266423Sjfv    JumpTableInfo->~MachineJumpTableInfo();
112266423Sjfv    Allocator.Deallocate(JumpTableInfo);
113266423Sjfv  }
114266423Sjfv}
115266423Sjfv
116266423Sjfv/// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
117266423Sjfv/// does already exist, allocate one.
118266423SjfvMachineJumpTableInfo *MachineFunction::
119266423SjfvgetOrCreateJumpTableInfo(unsigned EntryKind) {
120266423Sjfv  if (JumpTableInfo) return JumpTableInfo;
121266423Sjfv
122266423Sjfv  JumpTableInfo = new (Allocator)
123266423Sjfv    MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
124266423Sjfv  return JumpTableInfo;
125266423Sjfv}
126266423Sjfv
127266423Sjfv/// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
128266423Sjfv/// recomputes them.  This guarantees that the MBB numbers are sequential,
129266423Sjfv/// dense, and match the ordering of the blocks within the function.  If a
130266423Sjfv/// specific MachineBasicBlock is specified, only that block and those after
131266423Sjfv/// it are renumbered.
132266423Sjfvvoid MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
133266423Sjfv  if (empty()) { MBBNumbering.clear(); return; }
134266423Sjfv  MachineFunction::iterator MBBI, E = end();
135266423Sjfv  if (MBB == 0)
136266423Sjfv    MBBI = begin();
137266423Sjfv  else
138266423Sjfv    MBBI = MBB;
139266423Sjfv
140266423Sjfv  // Figure out the block number this should have.
141266423Sjfv  unsigned BlockNo = 0;
142266423Sjfv  if (MBBI != begin())
143266423Sjfv    BlockNo = prior(MBBI)->getNumber()+1;
144266423Sjfv
145266423Sjfv  for (; MBBI != E; ++MBBI, ++BlockNo) {
146266423Sjfv    if (MBBI->getNumber() != (int)BlockNo) {
147266423Sjfv      // Remove use of the old number.
148266423Sjfv      if (MBBI->getNumber() != -1) {
149266423Sjfv        assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
150266423Sjfv               "MBB number mismatch!");
151266423Sjfv        MBBNumbering[MBBI->getNumber()] = 0;
152266423Sjfv      }
153266423Sjfv
154266423Sjfv      // If BlockNo is already taken, set that block's number to -1.
155266423Sjfv      if (MBBNumbering[BlockNo])
156266423Sjfv        MBBNumbering[BlockNo]->setNumber(-1);
157266423Sjfv
158266423Sjfv      MBBNumbering[BlockNo] = MBBI;
159266423Sjfv      MBBI->setNumber(BlockNo);
160266423Sjfv    }
161266423Sjfv  }
162266423Sjfv
163266423Sjfv  // Okay, all the blocks are renumbered.  If we have compactified the block
164266423Sjfv  // numbering, shrink MBBNumbering now.
165266423Sjfv  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
166266423Sjfv  MBBNumbering.resize(BlockNo);
167266423Sjfv}
168266423Sjfv
169266423Sjfv/// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
170266423Sjfv/// of `new MachineInstr'.
171266423Sjfv///
172266423SjfvMachineInstr *
173266423SjfvMachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
174266423Sjfv                                    DebugLoc DL, bool NoImp) {
175266423Sjfv  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
176266423Sjfv    MachineInstr(*this, MCID, DL, NoImp);
177266423Sjfv}
178266423Sjfv
179266423Sjfv/// CloneMachineInstr - Create a new MachineInstr which is a copy of the
180266423Sjfv/// 'Orig' instruction, identical in all ways except the instruction
181266423Sjfv/// has no parent, prev, or next.
182266423Sjfv///
183266423SjfvMachineInstr *
184266423SjfvMachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
185266423Sjfv  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
186266423Sjfv             MachineInstr(*this, *Orig);
187266423Sjfv}
188266423Sjfv
189266423Sjfv/// DeleteMachineInstr - Delete the given MachineInstr.
190266423Sjfv///
191266423Sjfv/// This function also serves as the MachineInstr destructor - the real
192266423Sjfv/// ~MachineInstr() destructor must be empty.
193266423Sjfvvoid
194266423SjfvMachineFunction::DeleteMachineInstr(MachineInstr *MI) {
195266423Sjfv  // Strip it for parts. The operand array and the MI object itself are
196266423Sjfv  // independently recyclable.
197266423Sjfv  if (MI->Operands)
198266423Sjfv    deallocateOperandArray(MI->CapOperands, MI->Operands);
199266423Sjfv  // Don't call ~MachineInstr() which must be trivial anyway because
200266423Sjfv  // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
201266423Sjfv  // destructors.
202266423Sjfv  InstructionRecycler.Deallocate(Allocator, MI);
203266423Sjfv}
204266423Sjfv
205266423Sjfv/// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
206266423Sjfv/// instead of `new MachineBasicBlock'.
207266423Sjfv///
208266423SjfvMachineBasicBlock *
209266423SjfvMachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
210266423Sjfv  return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
211266423Sjfv             MachineBasicBlock(*this, bb);
212266423Sjfv}
213266423Sjfv
214266423Sjfv/// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
215266423Sjfv///
216266423Sjfvvoid
217269198SjfvMachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
218266423Sjfv  assert(MBB->getParent() == this && "MBB parent mismatch!");
219269198Sjfv  MBB->~MachineBasicBlock();
220269198Sjfv  BasicBlockRecycler.Deallocate(Allocator, MBB);
221266423Sjfv}
222266423Sjfv
223266423SjfvMachineMemOperand *
224266423SjfvMachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
225266423Sjfv                                      uint64_t s, unsigned base_alignment,
226266423Sjfv                                      const MDNode *TBAAInfo,
227266423Sjfv                                      const MDNode *Ranges) {
228266423Sjfv  return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
229266423Sjfv                                           TBAAInfo, Ranges);
230266423Sjfv}
231266423Sjfv
232266423SjfvMachineMemOperand *
233266423SjfvMachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
234266423Sjfv                                      int64_t Offset, uint64_t Size) {
235266423Sjfv  return new (Allocator)
236266423Sjfv             MachineMemOperand(MachinePointerInfo(MMO->getValue(),
237266423Sjfv                                                  MMO->getOffset()+Offset),
238266423Sjfv                               MMO->getFlags(), Size,
239266423Sjfv                               MMO->getBaseAlignment(), 0);
240266423Sjfv}
241266423Sjfv
242266423SjfvMachineInstr::mmo_iterator
243266423SjfvMachineFunction::allocateMemRefsArray(unsigned long Num) {
244266423Sjfv  return Allocator.Allocate<MachineMemOperand *>(Num);
245266423Sjfv}
246266423Sjfv
247266423Sjfvstd::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
248266423SjfvMachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
249266423Sjfv                                    MachineInstr::mmo_iterator End) {
250266423Sjfv  // Count the number of load mem refs.
251266423Sjfv  unsigned Num = 0;
252266423Sjfv  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
253266423Sjfv    if ((*I)->isLoad())
254277082Sjfv      ++Num;
255266423Sjfv
256266423Sjfv  // Allocate a new array and populate it with the load information.
257266423Sjfv  MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
258266423Sjfv  unsigned Index = 0;
259266423Sjfv  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
260266423Sjfv    if ((*I)->isLoad()) {
261266423Sjfv      if (!(*I)->isStore())
262266423Sjfv        // Reuse the MMO.
263266423Sjfv        Result[Index] = *I;
264266423Sjfv      else {
265266423Sjfv        // Clone the MMO and unset the store flag.
266266423Sjfv        MachineMemOperand *JustLoad =
267266423Sjfv          getMachineMemOperand((*I)->getPointerInfo(),
268266423Sjfv                               (*I)->getFlags() & ~MachineMemOperand::MOStore,
269266423Sjfv                               (*I)->getSize(), (*I)->getBaseAlignment(),
270266423Sjfv                               (*I)->getTBAAInfo());
271266423Sjfv        Result[Index] = JustLoad;
272266423Sjfv      }
273266423Sjfv      ++Index;
274266423Sjfv    }
275266423Sjfv  }
276266423Sjfv  return std::make_pair(Result, Result + Num);
277266423Sjfv}
278266423Sjfv
279266423Sjfvstd::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
280266423SjfvMachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
281266423Sjfv                                     MachineInstr::mmo_iterator End) {
282266423Sjfv  // Count the number of load mem refs.
283266423Sjfv  unsigned Num = 0;
284266423Sjfv  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
285266423Sjfv    if ((*I)->isStore())
286266423Sjfv      ++Num;
287266423Sjfv
288277082Sjfv  // Allocate a new array and populate it with the store information.
289266423Sjfv  MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
290266423Sjfv  unsigned Index = 0;
291266423Sjfv  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
292266423Sjfv    if ((*I)->isStore()) {
293266423Sjfv      if (!(*I)->isLoad())
294266423Sjfv        // Reuse the MMO.
295266423Sjfv        Result[Index] = *I;
296266423Sjfv      else {
297266423Sjfv        // Clone the MMO and unset the load flag.
298266423Sjfv        MachineMemOperand *JustStore =
299266423Sjfv          getMachineMemOperand((*I)->getPointerInfo(),
300266423Sjfv                               (*I)->getFlags() & ~MachineMemOperand::MOLoad,
301266423Sjfv                               (*I)->getSize(), (*I)->getBaseAlignment(),
302266423Sjfv                               (*I)->getTBAAInfo());
303266423Sjfv        Result[Index] = JustStore;
304266423Sjfv      }
305266423Sjfv      ++Index;
306266423Sjfv    }
307266423Sjfv  }
308266423Sjfv  return std::make_pair(Result, Result + Num);
309266423Sjfv}
310266423Sjfv
311266423Sjfv#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
312266423Sjfvvoid MachineFunction::dump() const {
313266423Sjfv  print(dbgs());
314266423Sjfv}
315266423Sjfv#endif
316266423Sjfv
317266423SjfvStringRef MachineFunction::getName() const {
318266423Sjfv  assert(getFunction() && "No function!");
319266423Sjfv  return getFunction()->getName();
320266423Sjfv}
321266423Sjfv
322266423Sjfvvoid MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
323266423Sjfv  OS << "# Machine code for function " << getName() << ": ";
324266423Sjfv  if (RegInfo) {
325266423Sjfv    OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
326266423Sjfv    if (!RegInfo->tracksLiveness())
327266423Sjfv      OS << ", not tracking liveness";
328266423Sjfv  }
329266423Sjfv  OS << '\n';
330266423Sjfv
331266423Sjfv  // Print Frame Information
332266423Sjfv  FrameInfo->print(*this, OS);
333266423Sjfv
334266423Sjfv  // Print JumpTable Information
335266423Sjfv  if (JumpTableInfo)
336266423Sjfv    JumpTableInfo->print(OS);
337266423Sjfv
338266423Sjfv  // Print Constant Pool
339277082Sjfv  ConstantPool->print(OS);
340266423Sjfv
341266423Sjfv  const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
342266423Sjfv
343266423Sjfv  if (RegInfo && !RegInfo->livein_empty()) {
344266423Sjfv    OS << "Function Live Ins: ";
345266423Sjfv    for (MachineRegisterInfo::livein_iterator
346266423Sjfv         I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
347266423Sjfv      OS << PrintReg(I->first, TRI);
348266423Sjfv      if (I->second)
349266423Sjfv        OS << " in " << PrintReg(I->second, TRI);
350266423Sjfv      if (llvm::next(I) != E)
351266423Sjfv        OS << ", ";
352266423Sjfv    }
353266423Sjfv    OS << '\n';
354266423Sjfv  }
355266423Sjfv
356266423Sjfv  for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
357266423Sjfv    OS << '\n';
358266423Sjfv    BB->print(OS, Indexes);
359266423Sjfv  }
360266423Sjfv
361266423Sjfv  OS << "\n# End machine code for function " << getName() << ".\n\n";
362266423Sjfv}
363266423Sjfv
364266423Sjfvnamespace llvm {
365266423Sjfv  template<>
366266423Sjfv  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
367266423Sjfv
368266423Sjfv  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
369266423Sjfv
370266423Sjfv    static std::string getGraphName(const MachineFunction *F) {
371266423Sjfv      return "CFG for '" + F->getName().str() + "' function";
372266423Sjfv    }
373266423Sjfv
374266423Sjfv    std::string getNodeLabel(const MachineBasicBlock *Node,
375266423Sjfv                             const MachineFunction *Graph) {
376266423Sjfv      std::string OutStr;
377266423Sjfv      {
378266423Sjfv        raw_string_ostream OSS(OutStr);
379266423Sjfv
380266423Sjfv        if (isSimple()) {
381266423Sjfv          OSS << "BB#" << Node->getNumber();
382266423Sjfv          if (const BasicBlock *BB = Node->getBasicBlock())
383266423Sjfv            OSS << ": " << BB->getName();
384266423Sjfv        } else
385266423Sjfv          Node->print(OSS);
386266423Sjfv      }
387266423Sjfv
388266423Sjfv      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
389266423Sjfv
390266423Sjfv      // Process string output to make it nicer...
391266423Sjfv      for (unsigned i = 0; i != OutStr.length(); ++i)
392266423Sjfv        if (OutStr[i] == '\n') {                            // Left justify
393266423Sjfv          OutStr[i] = '\\';
394266423Sjfv          OutStr.insert(OutStr.begin()+i+1, 'l');
395266423Sjfv        }
396266423Sjfv      return OutStr;
397266423Sjfv    }
398266423Sjfv  };
399266423Sjfv}
400266423Sjfv
401266423Sjfvvoid MachineFunction::viewCFG() const
402266423Sjfv{
403266423Sjfv#ifndef NDEBUG
404266423Sjfv  ViewGraph(this, "mf" + getName());
405266423Sjfv#else
406266423Sjfv  errs() << "MachineFunction::viewCFG is only available in debug builds on "
407266423Sjfv         << "systems with Graphviz or gv!\n";
408266423Sjfv#endif // NDEBUG
409266423Sjfv}
410266423Sjfv
411266423Sjfvvoid MachineFunction::viewCFGOnly() const
412266423Sjfv{
413266423Sjfv#ifndef NDEBUG
414266423Sjfv  ViewGraph(this, "mf" + getName(), true);
415266423Sjfv#else
416266423Sjfv  errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
417266423Sjfv         << "systems with Graphviz or gv!\n";
418266423Sjfv#endif // NDEBUG
419266423Sjfv}
420266423Sjfv
421266423Sjfv/// addLiveIn - Add the specified physical register as a live-in value and
422266423Sjfv/// create a corresponding virtual register for it.
423266423Sjfvunsigned MachineFunction::addLiveIn(unsigned PReg,
424266423Sjfv                                    const TargetRegisterClass *RC) {
425266423Sjfv  MachineRegisterInfo &MRI = getRegInfo();
426266423Sjfv  unsigned VReg = MRI.getLiveInVirtReg(PReg);
427266423Sjfv  if (VReg) {
428266423Sjfv    assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
429266423Sjfv    return VReg;
430266423Sjfv  }
431266423Sjfv  VReg = MRI.createVirtualRegister(RC);
432266423Sjfv  MRI.addLiveIn(PReg, VReg);
433266423Sjfv  return VReg;
434266423Sjfv}
435266423Sjfv
436266423Sjfv/// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
437266423Sjfv/// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
438266423Sjfv/// normal 'L' label is returned.
439266423SjfvMCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
440266423Sjfv                                        bool isLinkerPrivate) const {
441266423Sjfv  assert(JumpTableInfo && "No jump tables");
442266423Sjfv  assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
443266423Sjfv  const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
444266423Sjfv
445266423Sjfv  const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
446266423Sjfv                                         MAI.getPrivateGlobalPrefix();
447266423Sjfv  SmallString<60> Name;
448266423Sjfv  raw_svector_ostream(Name)
449266423Sjfv    << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
450266423Sjfv  return Ctx.GetOrCreateSymbol(Name.str());
451266423Sjfv}
452266423Sjfv
453266423Sjfv/// getPICBaseSymbol - Return a function-local symbol to represent the PIC
454266423Sjfv/// base.
455266423SjfvMCSymbol *MachineFunction::getPICBaseSymbol() const {
456266423Sjfv  const MCAsmInfo &MAI = *Target.getMCAsmInfo();
457266423Sjfv  return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
458277082Sjfv                               Twine(getFunctionNumber())+"$pb");
459277082Sjfv}
460277082Sjfv
461277082Sjfv//===----------------------------------------------------------------------===//
462277082Sjfv//  MachineFrameInfo implementation
463277082Sjfv//===----------------------------------------------------------------------===//
464277082Sjfv
465277082Sjfvconst TargetFrameLowering *MachineFrameInfo::getFrameLowering() const {
466277082Sjfv  return TM.getFrameLowering();
467266423Sjfv}
468277082Sjfv
469277082Sjfv/// ensureMaxAlignment - Make sure the function is at least Align bytes
470266423Sjfv/// aligned.
471266423Sjfvvoid MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
472266423Sjfv  if (!getFrameLowering()->isStackRealignable() || !RealignOption)
473266423Sjfv    assert(Align <= getFrameLowering()->getStackAlignment() &&
474266423Sjfv           "For targets without stack realignment, Align is out of limit!");
475266423Sjfv  if (MaxAlignment < Align) MaxAlignment = Align;
476266423Sjfv}
477266423Sjfv
478277082Sjfv/// clampStackAlignment - Clamp the alignment if requested and emit a warning.
479277082Sjfvstatic inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
480266423Sjfv                                           unsigned StackAlign) {
481266423Sjfv  if (!ShouldClamp || Align <= StackAlign)
482266423Sjfv    return Align;
483266423Sjfv  DEBUG(dbgs() << "Warning: requested alignment " << Align
484266423Sjfv               << " exceeds the stack alignment " << StackAlign
485266423Sjfv               << " when stack realignment is off" << '\n');
486277082Sjfv  return StackAlign;
487277082Sjfv}
488266423Sjfv
489266423Sjfv/// CreateStackObject - Create a new statically sized stack object, returning
490266423Sjfv/// a nonnegative identifier to represent it.
491266423Sjfv///
492266423Sjfvint MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
493266423Sjfv                      bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
494277082Sjfv  assert(Size != 0 && "Cannot allocate zero size stack objects!");
495277082Sjfv  Alignment =
496277082Sjfv    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
497266423Sjfv                          !RealignOption,
498277082Sjfv                        Alignment, getFrameLowering()->getStackAlignment());
499277082Sjfv  Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
500277082Sjfv                                Alloca));
501277082Sjfv  int Index = (int)Objects.size() - NumFixedObjects - 1;
502266423Sjfv  assert(Index >= 0 && "Bad frame index!");
503266423Sjfv  ensureMaxAlignment(Alignment);
504266423Sjfv  return Index;
505266423Sjfv}
506266423Sjfv
507266423Sjfv/// CreateSpillStackObject - Create a new statically sized stack object that
508266423Sjfv/// represents a spill slot, returning a nonnegative identifier to represent
509277082Sjfv/// it.
510266423Sjfv///
511266423Sjfvint MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
512266423Sjfv                                             unsigned Alignment) {
513266423Sjfv  Alignment =
514266423Sjfv    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
515266423Sjfv                          !RealignOption,
516266423Sjfv                        Alignment, getFrameLowering()->getStackAlignment());
517266423Sjfv  CreateStackObject(Size, Alignment, true, false);
518266423Sjfv  int Index = (int)Objects.size() - NumFixedObjects - 1;
519266423Sjfv  ensureMaxAlignment(Alignment);
520266423Sjfv  return Index;
521266423Sjfv}
522266423Sjfv
523266423Sjfv/// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
524266423Sjfv/// variable sized object has been created.  This must be created whenever a
525266423Sjfv/// variable sized object is created, whether or not the index returned is
526266423Sjfv/// actually used.
527266423Sjfv///
528266423Sjfvint MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment) {
529266423Sjfv  HasVarSizedObjects = true;
530266423Sjfv  Alignment =
531266423Sjfv    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
532266423Sjfv                          !RealignOption,
533266423Sjfv                        Alignment, getFrameLowering()->getStackAlignment());
534266423Sjfv  Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
535266423Sjfv  ensureMaxAlignment(Alignment);
536277082Sjfv  return (int)Objects.size()-NumFixedObjects-1;
537277082Sjfv}
538277082Sjfv
539277082Sjfv/// CreateFixedObject - Create a new object at a fixed location on the stack.
540277082Sjfv/// All fixed objects should be created before other objects are created for
541266423Sjfv/// efficiency. By default, fixed objects are immutable. This returns an
542266423Sjfv/// index with a negative value.
543266423Sjfv///
544266423Sjfvint MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
545266423Sjfv                                        bool Immutable) {
546266423Sjfv  assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
547266423Sjfv  // The alignment of the frame index can be determined from its offset from
548266423Sjfv  // the incoming frame position.  If the frame object is at offset 32 and
549266423Sjfv  // the stack is guaranteed to be 16-byte aligned, then we know that the
550266423Sjfv  // object is 16-byte aligned.
551266423Sjfv  unsigned StackAlign = getFrameLowering()->getStackAlignment();
552266423Sjfv  unsigned Align = MinAlign(SPOffset, StackAlign);
553266423Sjfv  Align =
554266423Sjfv    clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
555266423Sjfv                          !RealignOption,
556266423Sjfv                        Align, getFrameLowering()->getStackAlignment());
557266423Sjfv  Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
558266423Sjfv                                              /*isSS*/   false,
559266423Sjfv                                              /*NeedSP*/ false,
560266423Sjfv                                              /*Alloca*/ 0));
561266423Sjfv  return -++NumFixedObjects;
562266423Sjfv}
563270346Sjfv
564266423Sjfv
565266423SjfvBitVector
566266423SjfvMachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
567266423Sjfv  assert(MBB && "MBB must be valid");
568266423Sjfv  const MachineFunction *MF = MBB->getParent();
569266423Sjfv  assert(MF && "MBB must be part of a MachineFunction");
570266423Sjfv  const TargetMachine &TM = MF->getTarget();
571266423Sjfv  const TargetRegisterInfo *TRI = TM.getRegisterInfo();
572266423Sjfv  BitVector BV(TRI->getNumRegs());
573266423Sjfv
574266423Sjfv  // Before CSI is calculated, no registers are considered pristine. They can be
575266423Sjfv  // freely used and PEI will make sure they are saved.
576266423Sjfv  if (!isCalleeSavedInfoValid())
577266423Sjfv    return BV;
578266423Sjfv
579266423Sjfv  for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
580266423Sjfv    BV.set(*CSR);
581266423Sjfv
582266423Sjfv  // The entry MBB always has all CSRs pristine.
583266423Sjfv  if (MBB == &MF->front())
584266423Sjfv    return BV;
585266423Sjfv
586266423Sjfv  // On other MBBs the saved CSRs are not pristine.
587266423Sjfv  const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
588266423Sjfv  for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
589266423Sjfv         E = CSI.end(); I != E; ++I)
590266423Sjfv    BV.reset(I->getReg());
591266423Sjfv
592266423Sjfv  return BV;
593266423Sjfv}
594266423Sjfv
595266423Sjfvunsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
596266423Sjfv  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
597266423Sjfv  const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
598266423Sjfv  unsigned MaxAlign = getMaxAlignment();
599266423Sjfv  int Offset = 0;
600266423Sjfv
601266423Sjfv  // This code is very, very similar to PEI::calculateFrameObjectOffsets().
602266423Sjfv  // It really should be refactored to share code. Until then, changes
603266423Sjfv  // should keep in mind that there's tight coupling between the two.
604266423Sjfv
605266423Sjfv  for (int i = getObjectIndexBegin(); i != 0; ++i) {
606266423Sjfv    int FixedOff = -getObjectOffset(i);
607266423Sjfv    if (FixedOff > Offset) Offset = FixedOff;
608266423Sjfv  }
609266423Sjfv  for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
610266423Sjfv    if (isDeadObjectIndex(i))
611266423Sjfv      continue;
612266423Sjfv    Offset += getObjectSize(i);
613266423Sjfv    unsigned Align = getObjectAlignment(i);
614266423Sjfv    // Adjust to alignment boundary
615266423Sjfv    Offset = (Offset+Align-1)/Align*Align;
616266423Sjfv
617266423Sjfv    MaxAlign = std::max(Align, MaxAlign);
618266423Sjfv  }
619266423Sjfv
620266423Sjfv  if (adjustsStack() && TFI->hasReservedCallFrame(MF))
621266423Sjfv    Offset += getMaxCallFrameSize();
622266423Sjfv
623266423Sjfv  // Round up the size to a multiple of the alignment.  If the function has
624266423Sjfv  // any calls or alloca's, align to the target's StackAlignment value to
625266423Sjfv  // ensure that the callee's frame or the alloca data is suitably aligned;
626266423Sjfv  // otherwise, for leaf functions, align to the TransientStackAlignment
627266423Sjfv  // value.
628266423Sjfv  unsigned StackAlign;
629266423Sjfv  if (adjustsStack() || hasVarSizedObjects() ||
630266423Sjfv      (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
631266423Sjfv    StackAlign = TFI->getStackAlignment();
632266423Sjfv  else
633266423Sjfv    StackAlign = TFI->getTransientStackAlignment();
634266423Sjfv
635266423Sjfv  // If the frame pointer is eliminated, all frame offsets will be relative to
636266423Sjfv  // SP not FP. Align to MaxAlign so this works.
637266423Sjfv  StackAlign = std::max(StackAlign, MaxAlign);
638266423Sjfv  unsigned AlignMask = StackAlign - 1;
639266423Sjfv  Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
640266423Sjfv
641266423Sjfv  return (unsigned)Offset;
642266423Sjfv}
643266423Sjfv
644266423Sjfvvoid MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
645266423Sjfv  if (Objects.empty()) return;
646266423Sjfv
647266423Sjfv  const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
648266423Sjfv  int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
649266423Sjfv
650266423Sjfv  OS << "Frame Objects:\n";
651266423Sjfv
652266423Sjfv  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
653266423Sjfv    const StackObject &SO = Objects[i];
654266423Sjfv    OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
655266423Sjfv    if (SO.Size == ~0ULL) {
656266423Sjfv      OS << "dead\n";
657266423Sjfv      continue;
658266423Sjfv    }
659266423Sjfv    if (SO.Size == 0)
660266423Sjfv      OS << "variable sized";
661266423Sjfv    else
662266423Sjfv      OS << "size=" << SO.Size;
663266423Sjfv    OS << ", align=" << SO.Alignment;
664266423Sjfv
665266423Sjfv    if (i < NumFixedObjects)
666277082Sjfv      OS << ", fixed";
667277082Sjfv    if (i < NumFixedObjects || SO.SPOffset != -1) {
668266423Sjfv      int64_t Off = SO.SPOffset - ValOffset;
669266423Sjfv      OS << ", at location [SP";
670266423Sjfv      if (Off > 0)
671266423Sjfv        OS << "+" << Off;
672266423Sjfv      else if (Off < 0)
673277082Sjfv        OS << Off;
674266423Sjfv      OS << "]";
675266423Sjfv    }
676266423Sjfv    OS << "\n";
677266423Sjfv  }
678266423Sjfv}
679266423Sjfv
680266423Sjfv#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
681266423Sjfvvoid MachineFrameInfo::dump(const MachineFunction &MF) const {
682266423Sjfv  print(MF, dbgs());
683266423Sjfv}
684266423Sjfv#endif
685266423Sjfv
686266423Sjfv//===----------------------------------------------------------------------===//
687266423Sjfv//  MachineJumpTableInfo implementation
688266423Sjfv//===----------------------------------------------------------------------===//
689266423Sjfv
690266423Sjfv/// getEntrySize - Return the size of each entry in the jump table.
691266423Sjfvunsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
692266423Sjfv  // The size of a jump table entry is 4 bytes unless the entry is just the
693266423Sjfv  // address of a block, in which case it is the pointer size.
694266423Sjfv  switch (getEntryKind()) {
695266423Sjfv  case MachineJumpTableInfo::EK_BlockAddress:
696266423Sjfv    return TD.getPointerSize();
697266423Sjfv  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
698266423Sjfv    return 8;
699266423Sjfv  case MachineJumpTableInfo::EK_GPRel32BlockAddress:
700266423Sjfv  case MachineJumpTableInfo::EK_LabelDifference32:
701266423Sjfv  case MachineJumpTableInfo::EK_Custom32:
702266423Sjfv    return 4;
703266423Sjfv  case MachineJumpTableInfo::EK_Inline:
704266423Sjfv    return 0;
705266423Sjfv  }
706266423Sjfv  llvm_unreachable("Unknown jump table encoding!");
707266423Sjfv}
708266423Sjfv
709266423Sjfv/// getEntryAlignment - Return the alignment of each entry in the jump table.
710266423Sjfvunsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
711266423Sjfv  // The alignment of a jump table entry is the alignment of int32 unless the
712266423Sjfv  // entry is just the address of a block, in which case it is the pointer
713266423Sjfv  // alignment.
714266423Sjfv  switch (getEntryKind()) {
715266423Sjfv  case MachineJumpTableInfo::EK_BlockAddress:
716266423Sjfv    return TD.getPointerABIAlignment();
717266423Sjfv  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
718266423Sjfv    return TD.getABIIntegerTypeAlignment(64);
719266423Sjfv  case MachineJumpTableInfo::EK_GPRel32BlockAddress:
720266423Sjfv  case MachineJumpTableInfo::EK_LabelDifference32:
721266423Sjfv  case MachineJumpTableInfo::EK_Custom32:
722266423Sjfv    return TD.getABIIntegerTypeAlignment(32);
723266423Sjfv  case MachineJumpTableInfo::EK_Inline:
724266423Sjfv    return 1;
725266423Sjfv  }
726266423Sjfv  llvm_unreachable("Unknown jump table encoding!");
727266423Sjfv}
728266423Sjfv
729266423Sjfv/// createJumpTableIndex - Create a new jump table entry in the jump table info.
730266423Sjfv///
731266423Sjfvunsigned MachineJumpTableInfo::createJumpTableIndex(
732266423Sjfv                               const std::vector<MachineBasicBlock*> &DestBBs) {
733266423Sjfv  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
734266423Sjfv  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
735266423Sjfv  return JumpTables.size()-1;
736266423Sjfv}
737266423Sjfv
738266423Sjfv/// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
739266423Sjfv/// the jump tables to branch to New instead.
740266423Sjfvbool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
741266423Sjfv                                                  MachineBasicBlock *New) {
742266423Sjfv  assert(Old != New && "Not making a change?");
743266423Sjfv  bool MadeChange = false;
744266423Sjfv  for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
745266423Sjfv    ReplaceMBBInJumpTable(i, Old, New);
746266423Sjfv  return MadeChange;
747266423Sjfv}
748266423Sjfv
749266423Sjfv/// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
750266423Sjfv/// the jump table to branch to New instead.
751266423Sjfvbool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
752266423Sjfv                                                 MachineBasicBlock *Old,
753266423Sjfv                                                 MachineBasicBlock *New) {
754266423Sjfv  assert(Old != New && "Not making a change?");
755266423Sjfv  bool MadeChange = false;
756266423Sjfv  MachineJumpTableEntry &JTE = JumpTables[Idx];
757266423Sjfv  for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
758266423Sjfv    if (JTE.MBBs[j] == Old) {
759266423Sjfv      JTE.MBBs[j] = New;
760266423Sjfv      MadeChange = true;
761266423Sjfv    }
762266423Sjfv  return MadeChange;
763266423Sjfv}
764266423Sjfv
765266423Sjfvvoid MachineJumpTableInfo::print(raw_ostream &OS) const {
766266423Sjfv  if (JumpTables.empty()) return;
767266423Sjfv
768266423Sjfv  OS << "Jump Tables:\n";
769266423Sjfv
770266423Sjfv  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
771266423Sjfv    OS << "  jt#" << i << ": ";
772266423Sjfv    for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
773266423Sjfv      OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
774266423Sjfv  }
775266423Sjfv
776266423Sjfv  OS << '\n';
777266423Sjfv}
778266423Sjfv
779266423Sjfv#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
780266423Sjfvvoid MachineJumpTableInfo::dump() const { print(dbgs()); }
781266423Sjfv#endif
782266423Sjfv
783266423Sjfv
784266423Sjfv//===----------------------------------------------------------------------===//
785266423Sjfv//  MachineConstantPool implementation
786266423Sjfv//===----------------------------------------------------------------------===//
787266423Sjfv
788266423Sjfvvoid MachineConstantPoolValue::anchor() { }
789266423Sjfv
790266423Sjfvconst DataLayout *MachineConstantPool::getDataLayout() const {
791266423Sjfv  return TM.getDataLayout();
792266423Sjfv}
793266423Sjfv
794266423SjfvType *MachineConstantPoolEntry::getType() const {
795266423Sjfv  if (isMachineConstantPoolEntry())
796266423Sjfv    return Val.MachineCPVal->getType();
797266423Sjfv  return Val.ConstVal->getType();
798266423Sjfv}
799266423Sjfv
800266423Sjfv
801266423Sjfvunsigned MachineConstantPoolEntry::getRelocationInfo() const {
802266423Sjfv  if (isMachineConstantPoolEntry())
803266423Sjfv    return Val.MachineCPVal->getRelocationInfo();
804266423Sjfv  return Val.ConstVal->getRelocationInfo();
805266423Sjfv}
806266423Sjfv
807266423SjfvMachineConstantPool::~MachineConstantPool() {
808266423Sjfv  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
809266423Sjfv    if (Constants[i].isMachineConstantPoolEntry())
810266423Sjfv      delete Constants[i].Val.MachineCPVal;
811266423Sjfv  for (DenseSet<MachineConstantPoolValue*>::iterator I =
812266423Sjfv       MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
813266423Sjfv       I != E; ++I)
814266423Sjfv    delete *I;
815266423Sjfv}
816266423Sjfv
817266423Sjfv/// CanShareConstantPoolEntry - Test whether the given two constants
818266423Sjfv/// can be allocated the same constant pool entry.
819266423Sjfvstatic bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
820266423Sjfv                                      const DataLayout *TD) {
821266423Sjfv  // Handle the trivial case quickly.
822266423Sjfv  if (A == B) return true;
823266423Sjfv
824266423Sjfv  // If they have the same type but weren't the same constant, quickly
825266423Sjfv  // reject them.
826266423Sjfv  if (A->getType() == B->getType()) return false;
827266423Sjfv
828266423Sjfv  // We can't handle structs or arrays.
829266423Sjfv  if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
830266423Sjfv      isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
831266423Sjfv    return false;
832266423Sjfv
833266423Sjfv  // For now, only support constants with the same size.
834266423Sjfv  uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
835266423Sjfv  if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
836266423Sjfv      StoreSize > 128)
837266423Sjfv    return false;
838266423Sjfv
839266423Sjfv  Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
840266423Sjfv
841266423Sjfv  // Try constant folding a bitcast of both instructions to an integer.  If we
842266423Sjfv  // get two identical ConstantInt's, then we are good to share them.  We use
843266423Sjfv  // the constant folding APIs to do this so that we get the benefit of
844266423Sjfv  // DataLayout.
845266423Sjfv  if (isa<PointerType>(A->getType()))
846266423Sjfv    A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
847266423Sjfv                                 const_cast<Constant*>(A), TD);
848266423Sjfv  else if (A->getType() != IntTy)
849266423Sjfv    A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
850266423Sjfv                                 const_cast<Constant*>(A), TD);
851266423Sjfv  if (isa<PointerType>(B->getType()))
852266423Sjfv    B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
853266423Sjfv                                 const_cast<Constant*>(B), TD);
854266423Sjfv  else if (B->getType() != IntTy)
855266423Sjfv    B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
856266423Sjfv                                 const_cast<Constant*>(B), TD);
857266423Sjfv
858266423Sjfv  return A == B;
859266423Sjfv}
860266423Sjfv
861266423Sjfv/// getConstantPoolIndex - Create a new entry in the constant pool or return
862266423Sjfv/// an existing one.  User must specify the log2 of the minimum required
863266423Sjfv/// alignment for the object.
864266423Sjfv///
865266423Sjfvunsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
866266423Sjfv                                                   unsigned Alignment) {
867266423Sjfv  assert(Alignment && "Alignment must be specified!");
868266423Sjfv  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
869266423Sjfv
870266423Sjfv  // Check to see if we already have this constant.
871266423Sjfv  //
872266423Sjfv  // FIXME, this could be made much more efficient for large constant pools.
873266423Sjfv  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
874266423Sjfv    if (!Constants[i].isMachineConstantPoolEntry() &&
875266423Sjfv        CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
876266423Sjfv                                  getDataLayout())) {
877266423Sjfv      if ((unsigned)Constants[i].getAlignment() < Alignment)
878266423Sjfv        Constants[i].Alignment = Alignment;
879266423Sjfv      return i;
880266423Sjfv    }
881266423Sjfv
882266423Sjfv  Constants.push_back(MachineConstantPoolEntry(C, Alignment));
883266423Sjfv  return Constants.size()-1;
884266423Sjfv}
885266423Sjfv
886266423Sjfvunsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
887266423Sjfv                                                   unsigned Alignment) {
888266423Sjfv  assert(Alignment && "Alignment must be specified!");
889266423Sjfv  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
890266423Sjfv
891266423Sjfv  // Check to see if we already have this constant.
892266423Sjfv  //
893266423Sjfv  // FIXME, this could be made much more efficient for large constant pools.
894266423Sjfv  int Idx = V->getExistingMachineCPValue(this, Alignment);
895266423Sjfv  if (Idx != -1) {
896266423Sjfv    MachineCPVsSharingEntries.insert(V);
897266423Sjfv    return (unsigned)Idx;
898266423Sjfv  }
899266423Sjfv
900266423Sjfv  Constants.push_back(MachineConstantPoolEntry(V, Alignment));
901266423Sjfv  return Constants.size()-1;
902266423Sjfv}
903266423Sjfv
904266423Sjfvvoid MachineConstantPool::print(raw_ostream &OS) const {
905266423Sjfv  if (Constants.empty()) return;
906266423Sjfv
907266423Sjfv  OS << "Constant Pool:\n";
908266423Sjfv  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
909266423Sjfv    OS << "  cp#" << i << ": ";
910266423Sjfv    if (Constants[i].isMachineConstantPoolEntry())
911266423Sjfv      Constants[i].Val.MachineCPVal->print(OS);
912266423Sjfv    else
913266423Sjfv      WriteAsOperand(OS, Constants[i].Val.ConstVal, /*PrintType=*/false);
914266423Sjfv    OS << ", align=" << Constants[i].getAlignment();
915266423Sjfv    OS << "\n";
916266423Sjfv  }
917266423Sjfv}
918266423Sjfv
919266423Sjfv#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
920266423Sjfvvoid MachineConstantPool::dump() const { print(dbgs()); }
921266423Sjfv#endif
922266423Sjfv