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