MachineFunction.cpp revision 792699c46ef9bfc47dd459bbfa7e71bcb2cee29a
1//===-- MachineFunction.cpp -----------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/CodeGen/MachineFunctionPass.h"
17#include "llvm/CodeGen/MachineInstr.h"
18#include "llvm/CodeGen/SSARegMap.h"
19#include "llvm/CodeGen/MachineFunctionInfo.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetFrameInfo.h"
25#include "llvm/Function.h"
26#include "llvm/iOther.h"
27#include "Support/LeakDetector.h"
28
29using namespace llvm;
30
31static AnnotationID MF_AID(
32                 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
33
34
35namespace {
36  struct Printer : public MachineFunctionPass {
37    std::ostream *OS;
38    const std::string Banner;
39
40    Printer (std::ostream *_OS, const std::string &_Banner) :
41      OS (_OS), Banner (_Banner) { }
42
43    const char *getPassName() const { return "MachineFunction Printer"; }
44
45    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46      AU.setPreservesAll();
47    }
48
49    bool runOnMachineFunction(MachineFunction &MF) {
50      (*OS) << Banner;
51      MF.print (*OS);
52      return false;
53    }
54  };
55}
56
57/// Returns a newly-created MachineFunction Printer pass. The default output
58/// stream is std::cerr; the default banner is empty.
59///
60FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
61                                                     const std::string &Banner) {
62  return new Printer(OS, Banner);
63}
64
65namespace {
66  struct Deleter : public MachineFunctionPass {
67    const char *getPassName() const { return "Machine Code Deleter"; }
68
69    bool runOnMachineFunction(MachineFunction &MF) {
70      // Delete the annotation from the function now.
71      MachineFunction::destruct(MF.getFunction());
72      return true;
73    }
74  };
75}
76
77/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
78/// the current function, which should happen after the function has been
79/// emitted to a .s file or to memory.
80FunctionPass *llvm::createMachineCodeDeleter() {
81  return new Deleter();
82}
83
84
85
86//===---------------------------------------------------------------------===//
87// MachineFunction implementation
88//===---------------------------------------------------------------------===//
89MachineBasicBlock* ilist_traits<MachineBasicBlock>::createNode()
90{
91    MachineBasicBlock* dummy = new MachineBasicBlock();
92    LeakDetector::removeGarbageObject(dummy);
93    return dummy;
94}
95
96void ilist_traits<MachineBasicBlock>::transferNodesFromList(
97    iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
98    ilist_iterator<MachineBasicBlock> first,
99    ilist_iterator<MachineBasicBlock> last)
100{
101    if (parent != toList.parent)
102        for (; first != last; ++first)
103            first->Parent = toList.parent;
104}
105
106MachineFunction::MachineFunction(const Function *F,
107                                 const TargetMachine &TM)
108  : Annotation(MF_AID), Fn(F), Target(TM), NextMBBNumber(0) {
109  SSARegMapping = new SSARegMap();
110  MFInfo = new MachineFunctionInfo(*this);
111  FrameInfo = new MachineFrameInfo();
112  ConstantPool = new MachineConstantPool();
113  BasicBlocks.parent = this;
114}
115
116MachineFunction::~MachineFunction() {
117  delete SSARegMapping;
118  delete MFInfo;
119  delete FrameInfo;
120  delete ConstantPool;
121}
122
123void MachineFunction::dump() const { print(std::cerr); }
124
125void MachineFunction::print(std::ostream &OS) const {
126  OS << "# Machine code for " << Fn->getName () << "():\n";
127
128  // Print Frame Information
129  getFrameInfo()->print(*this, OS);
130
131  // Print Constant Pool
132  getConstantPool()->print(OS);
133
134  for (const_iterator BB = begin(); BB != end(); ++BB)
135    BB->print(OS);
136
137  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
138}
139
140// The next two methods are used to construct and to retrieve
141// the MachineCodeForFunction object for the given function.
142// construct() -- Allocates and initializes for a given function and target
143// get()       -- Returns a handle to the object.
144//                This should not be called before "construct()"
145//                for a given Function.
146//
147MachineFunction&
148MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
149{
150  assert(Fn->getAnnotation(MF_AID) == 0 &&
151         "Object already exists for this function!");
152  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
153  Fn->addAnnotation(mcInfo);
154  return *mcInfo;
155}
156
157void MachineFunction::destruct(const Function *Fn) {
158  bool Deleted = Fn->deleteAnnotation(MF_AID);
159  assert(Deleted && "Machine code did not exist for function!");
160}
161
162MachineFunction& MachineFunction::get(const Function *F)
163{
164  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
165  assert(mc && "Call construct() method first to allocate the object");
166  return *mc;
167}
168
169void MachineFunction::clearSSARegMap() {
170  delete SSARegMapping;
171  SSARegMapping = 0;
172}
173
174//===----------------------------------------------------------------------===//
175//  MachineFrameInfo implementation
176//===----------------------------------------------------------------------===//
177
178/// CreateStackObject - Create a stack object for a value of the specified type.
179///
180int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
181  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
182}
183
184int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
185  return CreateStackObject(RC->getSize(), RC->getAlignment());
186}
187
188
189void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
190  int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea();
191
192  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
193    const StackObject &SO = Objects[i];
194    OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
195    if (SO.Size == 0)
196      OS << "variable sized";
197    else
198      OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");
199
200    if (i < NumFixedObjects)
201      OS << " fixed";
202    if (i < NumFixedObjects || SO.SPOffset != -1) {
203      int Off = SO.SPOffset + ValOffset;
204      OS << " at location [SP";
205      if (Off > 0)
206	OS << "+" << Off;
207      else if (Off < 0)
208	OS << Off;
209      OS << "]";
210    }
211    OS << "\n";
212  }
213
214  if (HasVarSizedObjects)
215    OS << "  Stack frame contains variable sized objects\n";
216}
217
218void MachineFrameInfo::dump(const MachineFunction &MF) const {
219  print(MF, std::cerr);
220}
221
222
223//===----------------------------------------------------------------------===//
224//  MachineConstantPool implementation
225//===----------------------------------------------------------------------===//
226
227void MachineConstantPool::print(std::ostream &OS) const {
228  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
229    OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
230}
231
232void MachineConstantPool::dump() const { print(std::cerr); }
233
234//===----------------------------------------------------------------------===//
235//  MachineFunctionInfo implementation
236//===----------------------------------------------------------------------===//
237
238static unsigned
239ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
240                           unsigned &maxOptionalNumArgs)
241{
242  const TargetFrameInfo &frameInfo = target.getFrameInfo();
243
244  unsigned maxSize = 0;
245
246  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
247    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
248      if (const CallInst *callInst = dyn_cast<CallInst>(I))
249        {
250          unsigned numOperands = callInst->getNumOperands() - 1;
251          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
252          if (numExtra <= 0)
253            continue;
254
255          unsigned sizeForThisCall;
256          if (frameInfo.argsOnStackHaveFixedSize())
257            {
258              int argSize = frameInfo.getSizeOfEachArgOnStack();
259              sizeForThisCall = numExtra * (unsigned) argSize;
260            }
261          else
262            {
263              assert(0 && "UNTESTED CODE: Size per stack argument is not "
264                     "fixed on this architecture: use actual arg sizes to "
265                     "compute MaxOptionalArgsSize");
266              sizeForThisCall = 0;
267              for (unsigned i = 0; i < numOperands; ++i)
268                sizeForThisCall += target.getTargetData().getTypeSize(callInst->
269                                              getOperand(i)->getType());
270            }
271
272          if (maxSize < sizeForThisCall)
273            maxSize = sizeForThisCall;
274
275          if ((int)maxOptionalNumArgs < numExtra)
276            maxOptionalNumArgs = (unsigned) numExtra;
277        }
278
279  return maxSize;
280}
281
282// Align data larger than one L1 cache line on L1 cache line boundaries.
283// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
284// but not higher than the alignment of the largest type we support
285// (currently a double word). -- see class TargetData).
286//
287// This function is similar to the corresponding function in EmitAssembly.cpp
288// but they are unrelated.  This one does not align at more than a
289// double-word boundary whereas that one might.
290//
291inline unsigned
292SizeToAlignment(unsigned size, const TargetMachine& target)
293{
294  const unsigned short cacheLineSize = 16;
295  if (size > (unsigned) cacheLineSize / 2)
296    return cacheLineSize;
297  else
298    for (unsigned sz=1; /*no condition*/; sz *= 2)
299      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
300        return sz;
301}
302
303
304void MachineFunctionInfo::CalculateArgSize() {
305  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
306						   MF.getFunction(),
307                                                   maxOptionalNumArgs);
308  staticStackSize = maxOptionalArgsSize
309    + MF.getTarget().getFrameInfo().getMinStackFrameSize();
310}
311
312int
313MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
314					      unsigned &getPaddedSize,
315					      unsigned  sizeToUse)
316{
317  if (sizeToUse == 0)
318    sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
319  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());
320
321  bool growUp;
322  int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
323									     growUp);
324  int offset = growUp? firstOffset + getAutomaticVarsSize()
325                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);
326
327  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
328  getPaddedSize = sizeToUse + abs(aligned - offset);
329
330  return aligned;
331}
332
333
334int MachineFunctionInfo::allocateLocalVar(const Value* val,
335                                          unsigned sizeToUse) {
336  assert(! automaticVarsAreaFrozen &&
337         "Size of auto vars area has been used to compute an offset so "
338         "no more automatic vars should be allocated!");
339
340  // Check if we've allocated a stack slot for this value already
341  //
342  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
343  if (pair != offsets.end())
344    return pair->second;
345
346  unsigned getPaddedSize;
347  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
348  offsets[val] = offset;
349  incrementAutomaticVarsSize(getPaddedSize);
350  return offset;
351}
352
353int
354MachineFunctionInfo::allocateSpilledValue(const Type* type)
355{
356  assert(! spillsAreaFrozen &&
357         "Size of reg spills area has been used to compute an offset so "
358         "no more register spill slots should be allocated!");
359
360  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
361  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);
362
363  bool growUp;
364  int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);
365
366  int offset = growUp? firstOffset + getRegSpillsSize()
367                     : firstOffset - (getRegSpillsSize() + size);
368
369  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
370  size += abs(aligned - offset); // include alignment padding in size
371
372  incrementRegSpillsSize(size);  // update size of reg. spills area
373
374  return aligned;
375}
376
377int
378MachineFunctionInfo::pushTempValue(unsigned size)
379{
380  unsigned align = SizeToAlignment(size, MF.getTarget());
381
382  bool growUp;
383  int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);
384
385  int offset = growUp? firstOffset + currentTmpValuesSize
386                     : firstOffset - (currentTmpValuesSize + size);
387
388  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
389							      align);
390  size += abs(aligned - offset); // include alignment padding in size
391
392  incrementTmpAreaSize(size);    // update "current" size of tmp area
393
394  return aligned;
395}
396
397void MachineFunctionInfo::popAllTempValues() {
398  resetTmpAreaSize();            // clear tmp area to reuse
399}
400
401