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