1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
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/Instructions.h"
27 #include "llvm/Type.h"
28 #include "Support/LeakDetector.h"
29 #include "Support/GraphWriter.h"
36 static AnnotationID MF_AID(
37 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
41 struct Printer : public MachineFunctionPass {
43 const std::string Banner;
45 Printer (std::ostream *_OS, const std::string &_Banner) :
46 OS (_OS), Banner (_Banner) { }
48 const char *getPassName() const { return "MachineFunction Printer"; }
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 bool runOnMachineFunction(MachineFunction &MF) {
62 /// Returns a newly-created MachineFunction Printer pass. The default output
63 /// stream is std::cerr; the default banner is empty.
65 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
66 const std::string &Banner) {
67 return new Printer(OS, Banner);
71 struct Deleter : public MachineFunctionPass {
72 const char *getPassName() const { return "Machine Code Deleter"; }
74 bool runOnMachineFunction(MachineFunction &MF) {
75 // Delete the annotation from the function now.
76 MachineFunction::destruct(MF.getFunction());
82 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
83 /// the current function, which should happen after the function has been
84 /// emitted to a .s file or to memory.
85 FunctionPass *llvm::createMachineCodeDeleter() {
91 //===---------------------------------------------------------------------===//
92 // MachineFunction implementation
93 //===---------------------------------------------------------------------===//
94 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createNode()
96 MachineBasicBlock* dummy = new MachineBasicBlock();
97 LeakDetector::removeGarbageObject(dummy);
101 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
102 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
103 ilist_iterator<MachineBasicBlock> first,
104 ilist_iterator<MachineBasicBlock> last)
106 if (Parent != toList.Parent)
107 for (; first != last; ++first)
108 first->Parent = toList.Parent;
111 MachineFunction::MachineFunction(const Function *F,
112 const TargetMachine &TM)
113 : Annotation(MF_AID), Fn(F), Target(TM) {
114 SSARegMapping = new SSARegMap();
115 MFInfo = new MachineFunctionInfo(*this);
116 FrameInfo = new MachineFrameInfo();
117 ConstantPool = new MachineConstantPool();
118 BasicBlocks.Parent = this;
121 MachineFunction::~MachineFunction() {
123 delete SSARegMapping;
129 void MachineFunction::dump() const { print(std::cerr); }
131 void MachineFunction::print(std::ostream &OS) const {
132 OS << "# Machine code for " << Fn->getName () << "():\n";
134 // Print Frame Information
135 getFrameInfo()->print(*this, OS);
137 // Print Constant Pool
138 getConstantPool()->print(OS);
140 for (const_iterator BB = begin(); BB != end(); ++BB)
143 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
146 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
147 /// prints out the contents of basic blocks or not. This is acceptable because
148 /// this code is only really used for debugging purposes.
150 static bool CFGOnly = false;
154 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
155 static std::string getGraphName(const MachineFunction *F) {
156 return "CFG for '" + F->getFunction()->getName() + "' function";
159 static std::string getNodeLabel(const MachineBasicBlock *Node,
160 const MachineFunction *Graph) {
161 if (CFGOnly && Node->getBasicBlock() &&
162 !Node->getBasicBlock()->getName().empty())
163 return Node->getBasicBlock()->getName() + ":";
165 std::ostringstream Out;
167 Out << Node->getNumber() << ':';
173 std::string OutStr = Out.str();
174 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
176 // Process string output to make it nicer...
177 for (unsigned i = 0; i != OutStr.length(); ++i)
178 if (OutStr[i] == '\n') { // Left justify
180 OutStr.insert(OutStr.begin()+i+1, 'l');
187 void MachineFunction::viewCFG() const
189 std::string Filename = "/tmp/cfg." + getFunction()->getName() + ".dot";
190 std::cerr << "Writing '" << Filename << "'... ";
191 std::ofstream F(Filename.c_str());
194 std::cerr << " error opening file for writing!\n";
202 std::cerr << "Running 'dot' program... " << std::flush;
203 if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
204 + " > /tmp/cfg.tempgraph.ps").c_str())) {
205 std::cerr << "Error running dot: 'dot' not in path?\n";
208 system("gv /tmp/cfg.tempgraph.ps");
210 system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
213 void MachineFunction::viewCFGOnly() const
220 // The next two methods are used to construct and to retrieve
221 // the MachineCodeForFunction object for the given function.
222 // construct() -- Allocates and initializes for a given function and target
223 // get() -- Returns a handle to the object.
224 // This should not be called before "construct()"
225 // for a given Function.
228 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
230 assert(Fn->getAnnotation(MF_AID) == 0 &&
231 "Object already exists for this function!");
232 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
233 Fn->addAnnotation(mcInfo);
237 void MachineFunction::destruct(const Function *Fn) {
238 bool Deleted = Fn->deleteAnnotation(MF_AID);
239 assert(Deleted && "Machine code did not exist for function!");
242 MachineFunction& MachineFunction::get(const Function *F)
244 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
245 assert(mc && "Call construct() method first to allocate the object");
249 void MachineFunction::clearSSARegMap() {
250 delete SSARegMapping;
254 //===----------------------------------------------------------------------===//
255 // MachineFrameInfo implementation
256 //===----------------------------------------------------------------------===//
258 /// CreateStackObject - Create a stack object for a value of the specified type.
260 int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
261 return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
264 int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
265 return CreateStackObject(RC->getSize(), RC->getAlignment());
269 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
270 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
272 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
273 const StackObject &SO = Objects[i];
274 OS << " <fi #" << (int)(i-NumFixedObjects) << "> is ";
276 OS << "variable sized";
278 OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");
280 if (i < NumFixedObjects)
282 if (i < NumFixedObjects || SO.SPOffset != -1) {
283 int Off = SO.SPOffset - ValOffset;
284 OS << " at location [SP";
294 if (HasVarSizedObjects)
295 OS << " Stack frame contains variable sized objects\n";
298 void MachineFrameInfo::dump(const MachineFunction &MF) const {
299 print(MF, std::cerr);
303 //===----------------------------------------------------------------------===//
304 // MachineConstantPool implementation
305 //===----------------------------------------------------------------------===//
307 void MachineConstantPool::print(std::ostream &OS) const {
308 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
309 OS << " <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
312 void MachineConstantPool::dump() const { print(std::cerr); }
314 //===----------------------------------------------------------------------===//
315 // MachineFunctionInfo implementation
316 //===----------------------------------------------------------------------===//
319 ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
320 unsigned &maxOptionalNumArgs)
322 const TargetFrameInfo &frameInfo = *target.getFrameInfo();
324 unsigned maxSize = 0;
326 for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
327 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
328 if (const CallInst *callInst = dyn_cast<CallInst>(I))
330 unsigned numOperands = callInst->getNumOperands() - 1;
331 int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
335 unsigned sizeForThisCall;
336 if (frameInfo.argsOnStackHaveFixedSize())
338 int argSize = frameInfo.getSizeOfEachArgOnStack();
339 sizeForThisCall = numExtra * (unsigned) argSize;
343 assert(0 && "UNTESTED CODE: Size per stack argument is not "
344 "fixed on this architecture: use actual arg sizes to "
345 "compute MaxOptionalArgsSize");
347 for (unsigned i = 0; i < numOperands; ++i)
348 sizeForThisCall += target.getTargetData().getTypeSize(callInst->
349 getOperand(i)->getType());
352 if (maxSize < sizeForThisCall)
353 maxSize = sizeForThisCall;
355 if ((int)maxOptionalNumArgs < numExtra)
356 maxOptionalNumArgs = (unsigned) numExtra;
362 // Align data larger than one L1 cache line on L1 cache line boundaries.
363 // Align all smaller data on the next higher 2^x boundary (4, 8, ...),
364 // but not higher than the alignment of the largest type we support
365 // (currently a double word). -- see class TargetData).
367 // This function is similar to the corresponding function in EmitAssembly.cpp
368 // but they are unrelated. This one does not align at more than a
369 // double-word boundary whereas that one might.
372 SizeToAlignment(unsigned size, const TargetMachine& target)
374 const unsigned short cacheLineSize = 16;
375 if (size > (unsigned) cacheLineSize / 2)
376 return cacheLineSize;
378 for (unsigned sz=1; /*no condition*/; sz *= 2)
379 if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
384 void MachineFunctionInfo::CalculateArgSize() {
385 maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
388 staticStackSize = maxOptionalArgsSize
389 + MF.getTarget().getFrameInfo()->getMinStackFrameSize();
393 MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
394 unsigned &getPaddedSize,
397 if (sizeToUse == 0) {
398 // All integer types smaller than ints promote to 4 byte integers.
399 if (val->getType()->isIntegral() && val->getType()->getPrimitiveSize() < 4)
402 sizeToUse = MF.getTarget().getTargetData().getTypeSize(val->getType());
404 unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());
407 int firstOffset = MF.getTarget().getFrameInfo()->getFirstAutomaticVarOffset(MF,
409 int offset = growUp? firstOffset + getAutomaticVarsSize()
410 : firstOffset - (getAutomaticVarsSize() + sizeToUse);
412 int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);
413 getPaddedSize = sizeToUse + abs(aligned - offset);
419 int MachineFunctionInfo::allocateLocalVar(const Value* val,
420 unsigned sizeToUse) {
421 assert(! automaticVarsAreaFrozen &&
422 "Size of auto vars area has been used to compute an offset so "
423 "no more automatic vars should be allocated!");
425 // Check if we've allocated a stack slot for this value already
427 hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
428 if (pair != offsets.end())
431 unsigned getPaddedSize;
432 unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
433 offsets[val] = offset;
434 incrementAutomaticVarsSize(getPaddedSize);
439 MachineFunctionInfo::allocateSpilledValue(const Type* type)
441 assert(! spillsAreaFrozen &&
442 "Size of reg spills area has been used to compute an offset so "
443 "no more register spill slots should be allocated!");
445 unsigned size = MF.getTarget().getTargetData().getTypeSize(type);
446 unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);
449 int firstOffset = MF.getTarget().getFrameInfo()->getRegSpillAreaOffset(MF, growUp);
451 int offset = growUp? firstOffset + getRegSpillsSize()
452 : firstOffset - (getRegSpillsSize() + size);
454 int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);
455 size += abs(aligned - offset); // include alignment padding in size
457 incrementRegSpillsSize(size); // update size of reg. spills area
463 MachineFunctionInfo::pushTempValue(unsigned size)
465 unsigned align = SizeToAlignment(size, MF.getTarget());
468 int firstOffset = MF.getTarget().getFrameInfo()->getTmpAreaOffset(MF, growUp);
470 int offset = growUp? firstOffset + currentTmpValuesSize
471 : firstOffset - (currentTmpValuesSize + size);
473 int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp,
475 size += abs(aligned - offset); // include alignment padding in size
477 incrementTmpAreaSize(size); // update "current" size of tmp area
482 void MachineFunctionInfo::popAllTempValues() {
483 resetTmpAreaSize(); // clear tmp area to reuse