xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision b5706c45fa2ec5e9e35922b68da34c7755f59ac8)
1 //===-- MachineFunction.cpp -----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/DerivedTypes.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Config/config.h"
34 #include <fstream>
35 #include <sstream>
36 using namespace llvm;
37 
38 static AnnotationID MF_AID(
39   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
40 
41 // Out of line virtual function to home classes.
42 void MachineFunctionPass::virtfn() {}
43 
44 namespace {
45   struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
46     static char ID;
47 
48     std::ostream *OS;
49     const std::string Banner;
50 
51     Printer (std::ostream *os, const std::string &banner)
52       : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
53 
54     const char *getPassName() const { return "MachineFunction Printer"; }
55 
56     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57       AU.setPreservesAll();
58     }
59 
60     bool runOnMachineFunction(MachineFunction &MF) {
61       (*OS) << Banner;
62       MF.print (*OS);
63       return false;
64     }
65   };
66   char Printer::ID = 0;
67 }
68 
69 /// Returns a newly-created MachineFunction Printer pass. The default output
70 /// stream is std::cerr; the default banner is empty.
71 ///
72 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
73                                                      const std::string &Banner){
74   return new Printer(OS, Banner);
75 }
76 
77 namespace {
78   struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
79     static char ID;
80     Deleter() : MachineFunctionPass(&ID) {}
81 
82     const char *getPassName() const { return "Machine Code Deleter"; }
83 
84     bool runOnMachineFunction(MachineFunction &MF) {
85       // Delete the annotation from the function now.
86       MachineFunction::destruct(MF.getFunction());
87       return true;
88     }
89   };
90   char Deleter::ID = 0;
91 }
92 
93 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
94 /// the current function, which should happen after the function has been
95 /// emitted to a .s file or to memory.
96 FunctionPass *llvm::createMachineCodeDeleter() {
97   return new Deleter();
98 }
99 
100 
101 
102 //===---------------------------------------------------------------------===//
103 // MachineFunction implementation
104 //===---------------------------------------------------------------------===//
105 
106 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
107   MBB->getParent()->DeleteMachineBasicBlock(MBB);
108 }
109 
110 MachineFunction::MachineFunction(const Function *F,
111                                  const TargetMachine &TM)
112   : Annotation(MF_AID), Fn(F), Target(TM) {
113   if (TM.getRegisterInfo())
114     RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
115                   MachineRegisterInfo(*TM.getRegisterInfo());
116   else
117     RegInfo = 0;
118   MFInfo = 0;
119   FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
120                   MachineFrameInfo(*TM.getFrameInfo());
121   ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
122                      MachineConstantPool(TM.getTargetData());
123 
124   // Set up jump table.
125   const TargetData &TD = *TM.getTargetData();
126   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
127   unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
128   unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
129                              : TD.getPointerABIAlignment();
130   JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
131                       MachineJumpTableInfo(EntrySize, Alignment);
132 }
133 
134 MachineFunction::~MachineFunction() {
135   BasicBlocks.clear();
136   InstructionRecycler.clear(Allocator);
137   BasicBlockRecycler.clear(Allocator);
138   if (RegInfo)
139     RegInfo->~MachineRegisterInfo();        Allocator.Deallocate(RegInfo);
140   if (MFInfo) {
141     MFInfo->~MachineFunctionInfo();       Allocator.Deallocate(MFInfo);
142   }
143   FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
144   ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
145   JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
146 }
147 
148 
149 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
150 /// recomputes them.  This guarantees that the MBB numbers are sequential,
151 /// dense, and match the ordering of the blocks within the function.  If a
152 /// specific MachineBasicBlock is specified, only that block and those after
153 /// it are renumbered.
154 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
155   if (empty()) { MBBNumbering.clear(); return; }
156   MachineFunction::iterator MBBI, E = end();
157   if (MBB == 0)
158     MBBI = begin();
159   else
160     MBBI = MBB;
161 
162   // Figure out the block number this should have.
163   unsigned BlockNo = 0;
164   if (MBBI != begin())
165     BlockNo = prior(MBBI)->getNumber()+1;
166 
167   for (; MBBI != E; ++MBBI, ++BlockNo) {
168     if (MBBI->getNumber() != (int)BlockNo) {
169       // Remove use of the old number.
170       if (MBBI->getNumber() != -1) {
171         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
172                "MBB number mismatch!");
173         MBBNumbering[MBBI->getNumber()] = 0;
174       }
175 
176       // If BlockNo is already taken, set that block's number to -1.
177       if (MBBNumbering[BlockNo])
178         MBBNumbering[BlockNo]->setNumber(-1);
179 
180       MBBNumbering[BlockNo] = MBBI;
181       MBBI->setNumber(BlockNo);
182     }
183   }
184 
185   // Okay, all the blocks are renumbered.  If we have compactified the block
186   // numbering, shrink MBBNumbering now.
187   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
188   MBBNumbering.resize(BlockNo);
189 }
190 
191 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
192 /// of `new MachineInstr'.
193 ///
194 MachineInstr *
195 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID, bool NoImp) {
196   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
197              MachineInstr(TID, NoImp);
198 }
199 
200 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
201 /// 'Orig' instruction, identical in all ways except the the instruction
202 /// has no parent, prev, or next.
203 ///
204 MachineInstr *
205 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
206   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
207              MachineInstr(*this, *Orig);
208 }
209 
210 /// DeleteMachineInstr - Delete the given MachineInstr.
211 ///
212 void
213 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
214   // Clear the instructions memoperands. This must be done manually because
215   // the instruction's parent pointer is now null, so it can't properly
216   // deallocate them on its own.
217   MI->clearMemOperands(*this);
218 
219   MI->~MachineInstr();
220   InstructionRecycler.Deallocate(Allocator, MI);
221 }
222 
223 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
224 /// instead of `new MachineBasicBlock'.
225 ///
226 MachineBasicBlock *
227 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
228   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
229              MachineBasicBlock(*this, bb);
230 }
231 
232 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
233 ///
234 void
235 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
236   assert(MBB->getParent() == this && "MBB parent mismatch!");
237   MBB->~MachineBasicBlock();
238   BasicBlockRecycler.Deallocate(Allocator, MBB);
239 }
240 
241 void MachineFunction::dump() const {
242   print(*cerr.stream());
243 }
244 
245 void MachineFunction::print(std::ostream &OS) const {
246   OS << "# Machine code for " << Fn->getName () << "():\n";
247 
248   // Print Frame Information
249   FrameInfo->print(*this, OS);
250 
251   // Print JumpTable Information
252   JumpTableInfo->print(OS);
253 
254   // Print Constant Pool
255   {
256     raw_os_ostream OSS(OS);
257     ConstantPool->print(OSS);
258   }
259 
260   const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
261 
262   if (RegInfo && !RegInfo->livein_empty()) {
263     OS << "Live Ins:";
264     for (MachineRegisterInfo::livein_iterator
265          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
266       if (TRI)
267         OS << " " << TRI->getName(I->first);
268       else
269         OS << " Reg #" << I->first;
270 
271       if (I->second)
272         OS << " in VR#" << I->second << " ";
273     }
274     OS << "\n";
275   }
276   if (RegInfo && !RegInfo->liveout_empty()) {
277     OS << "Live Outs:";
278     for (MachineRegisterInfo::liveout_iterator
279          I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
280       if (TRI)
281         OS << " " << TRI->getName(*I);
282       else
283         OS << " Reg #" << *I;
284     OS << "\n";
285   }
286 
287   for (const_iterator BB = begin(); BB != end(); ++BB)
288     BB->print(OS);
289 
290   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
291 }
292 
293 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
294 /// prints out the contents of basic blocks or not.  This is acceptable because
295 /// this code is only really used for debugging purposes.
296 ///
297 static bool CFGOnly = false;
298 
299 namespace llvm {
300   template<>
301   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
302     static std::string getGraphName(const MachineFunction *F) {
303       return "CFG for '" + F->getFunction()->getName() + "' function";
304     }
305 
306     static std::string getNodeLabel(const MachineBasicBlock *Node,
307                                     const MachineFunction *Graph) {
308       if (CFGOnly && Node->getBasicBlock() &&
309           !Node->getBasicBlock()->getName().empty())
310         return Node->getBasicBlock()->getName() + ":";
311 
312       std::ostringstream Out;
313       if (CFGOnly) {
314         Out << Node->getNumber() << ':';
315         return Out.str();
316       }
317 
318       Node->print(Out);
319 
320       std::string OutStr = Out.str();
321       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
322 
323       // Process string output to make it nicer...
324       for (unsigned i = 0; i != OutStr.length(); ++i)
325         if (OutStr[i] == '\n') {                            // Left justify
326           OutStr[i] = '\\';
327           OutStr.insert(OutStr.begin()+i+1, 'l');
328         }
329       return OutStr;
330     }
331   };
332 }
333 
334 void MachineFunction::viewCFG() const
335 {
336 #ifndef NDEBUG
337   ViewGraph(this, "mf" + getFunction()->getName());
338 #else
339   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
340        << "systems with Graphviz or gv!\n";
341 #endif // NDEBUG
342 }
343 
344 void MachineFunction::viewCFGOnly() const
345 {
346   CFGOnly = true;
347   viewCFG();
348   CFGOnly = false;
349 }
350 
351 // The next two methods are used to construct and to retrieve
352 // the MachineCodeForFunction object for the given function.
353 // construct() -- Allocates and initializes for a given function and target
354 // get()       -- Returns a handle to the object.
355 //                This should not be called before "construct()"
356 //                for a given Function.
357 //
358 MachineFunction&
359 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
360 {
361   assert(Fn->getAnnotation(MF_AID) == 0 &&
362          "Object already exists for this function!");
363   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
364   Fn->addAnnotation(mcInfo);
365   return *mcInfo;
366 }
367 
368 void MachineFunction::destruct(const Function *Fn) {
369   bool Deleted = Fn->deleteAnnotation(MF_AID);
370   assert(Deleted && "Machine code did not exist for function!");
371   Deleted = Deleted; // silence warning when no assertions.
372 }
373 
374 MachineFunction& MachineFunction::get(const Function *F)
375 {
376   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
377   assert(mc && "Call construct() method first to allocate the object");
378   return *mc;
379 }
380 
381 /// lookUpDebugLocId - Look up the DebugLocTuple index with the given
382 /// filename, line, and column. It may add a new filename and / or
383 /// a new DebugLocTuple.
384 unsigned MachineFunction::lookUpDebugLocId(const char *Filename, unsigned Line,
385                                            unsigned Col) {
386   unsigned FileId;
387   StringMap<unsigned>::iterator I =
388     DebugLocInfo.DebugFilenamesMap.find(Filename);
389   if (I != DebugLocInfo.DebugFilenamesMap.end())
390     FileId = I->second;
391   else {
392     // Add a new filename.
393     FileId = DebugLocInfo.NumFilenames++;
394     DebugLocInfo.DebugFilenames.push_back(Filename);
395     DebugLocInfo.DebugFilenamesMap[Filename] = FileId;
396   }
397 
398   struct DebugLocTuple Tuple(FileId, Line, Col);
399   DebugIdMapType::iterator II = DebugLocInfo.DebugIdMap.find(Tuple);
400   if (II != DebugLocInfo.DebugIdMap.end())
401     return II->second;
402   // Add a new tuple.
403   DebugLocInfo.DebugLocations.push_back(Tuple);
404   DebugLocInfo.DebugIdMap[Tuple] = DebugLocInfo.NumDebugLocations;
405   return DebugLocInfo.NumDebugLocations++;
406 }
407 
408 //===----------------------------------------------------------------------===//
409 //  MachineFrameInfo implementation
410 //===----------------------------------------------------------------------===//
411 
412 /// CreateFixedObject - Create a new object at a fixed location on the stack.
413 /// All fixed objects should be created before other objects are created for
414 /// efficiency. By default, fixed objects are immutable. This returns an
415 /// index with a negative value.
416 ///
417 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
418                                         bool Immutable) {
419   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
420   Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
421   return -++NumFixedObjects;
422 }
423 
424 
425 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
426   const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
427   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
428 
429   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
430     const StackObject &SO = Objects[i];
431     OS << "  <fi#" << (int)(i-NumFixedObjects) << ">: ";
432     if (SO.Size == ~0ULL) {
433       OS << "dead\n";
434       continue;
435     }
436     if (SO.Size == 0)
437       OS << "variable sized";
438     else
439       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
440     OS << " alignment is " << SO.Alignment << " byte"
441        << (SO.Alignment != 1 ? "s," : ",");
442 
443     if (i < NumFixedObjects)
444       OS << " fixed";
445     if (i < NumFixedObjects || SO.SPOffset != -1) {
446       int64_t Off = SO.SPOffset - ValOffset;
447       OS << " at location [SP";
448       if (Off > 0)
449         OS << "+" << Off;
450       else if (Off < 0)
451         OS << Off;
452       OS << "]";
453     }
454     OS << "\n";
455   }
456 
457   if (HasVarSizedObjects)
458     OS << "  Stack frame contains variable sized objects\n";
459 }
460 
461 void MachineFrameInfo::dump(const MachineFunction &MF) const {
462   print(MF, *cerr.stream());
463 }
464 
465 
466 //===----------------------------------------------------------------------===//
467 //  MachineJumpTableInfo implementation
468 //===----------------------------------------------------------------------===//
469 
470 /// getJumpTableIndex - Create a new jump table entry in the jump table info
471 /// or return an existing one.
472 ///
473 unsigned MachineJumpTableInfo::getJumpTableIndex(
474                                const std::vector<MachineBasicBlock*> &DestBBs) {
475   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
476   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
477     if (JumpTables[i].MBBs == DestBBs)
478       return i;
479 
480   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
481   return JumpTables.size()-1;
482 }
483 
484 
485 void MachineJumpTableInfo::print(std::ostream &OS) const {
486   // FIXME: this is lame, maybe we could print out the MBB numbers or something
487   // like {1, 2, 4, 5, 3, 0}
488   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
489     OS << "  <jt#" << i << "> has " << JumpTables[i].MBBs.size()
490        << " entries\n";
491   }
492 }
493 
494 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
495 
496 
497 //===----------------------------------------------------------------------===//
498 //  MachineConstantPool implementation
499 //===----------------------------------------------------------------------===//
500 
501 const Type *MachineConstantPoolEntry::getType() const {
502   if (isMachineConstantPoolEntry())
503       return Val.MachineCPVal->getType();
504   return Val.ConstVal->getType();
505 }
506 
507 MachineConstantPool::~MachineConstantPool() {
508   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
509     if (Constants[i].isMachineConstantPoolEntry())
510       delete Constants[i].Val.MachineCPVal;
511 }
512 
513 /// getConstantPoolIndex - Create a new entry in the constant pool or return
514 /// an existing one.  User must specify the log2 of the minimum required
515 /// alignment for the object.
516 ///
517 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
518                                                    unsigned Alignment) {
519   assert(Alignment && "Alignment must be specified!");
520   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
521 
522   // Check to see if we already have this constant.
523   //
524   // FIXME, this could be made much more efficient for large constant pools.
525   unsigned AlignMask = (1 << Alignment)-1;
526   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
527     if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
528       return i;
529 
530   unsigned Offset = 0;
531   if (!Constants.empty()) {
532     Offset = Constants.back().getOffset();
533     Offset += TD->getTypePaddedSize(Constants.back().getType());
534     Offset = (Offset+AlignMask)&~AlignMask;
535   }
536 
537   Constants.push_back(MachineConstantPoolEntry(C, Offset));
538   return Constants.size()-1;
539 }
540 
541 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
542                                                    unsigned Alignment) {
543   assert(Alignment && "Alignment must be specified!");
544   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
545 
546   // Check to see if we already have this constant.
547   //
548   // FIXME, this could be made much more efficient for large constant pools.
549   unsigned AlignMask = (1 << Alignment)-1;
550   int Idx = V->getExistingMachineCPValue(this, Alignment);
551   if (Idx != -1)
552     return (unsigned)Idx;
553 
554   unsigned Offset = 0;
555   if (!Constants.empty()) {
556     Offset = Constants.back().getOffset();
557     Offset += TD->getTypePaddedSize(Constants.back().getType());
558     Offset = (Offset+AlignMask)&~AlignMask;
559   }
560 
561   Constants.push_back(MachineConstantPoolEntry(V, Offset));
562   return Constants.size()-1;
563 }
564 
565 void MachineConstantPool::print(raw_ostream &OS) const {
566   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
567     OS << "  <cp#" << i << "> is";
568     if (Constants[i].isMachineConstantPoolEntry())
569       Constants[i].Val.MachineCPVal->print(OS);
570     else
571       OS << *(Value*)Constants[i].Val.ConstVal;
572     OS << " , offset=" << Constants[i].getOffset();
573     OS << "\n";
574   }
575 }
576 
577 void MachineConstantPool::dump() const { print(errs()); errs().flush(); }
578