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