LLVM  mainline
MachineFunction.cpp
Go to the documentation of this file.
00001 //===-- MachineFunction.cpp -----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Collect native machine code information for a function.  This allows
00011 // target-specific information about the generated code to be stored with each
00012 // function.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/CodeGen/MachineFunction.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/Analysis/ConstantFolding.h"
00020 #include "llvm/Analysis/EHPersonalities.h"
00021 #include "llvm/CodeGen/MachineConstantPool.h"
00022 #include "llvm/CodeGen/MachineFrameInfo.h"
00023 #include "llvm/CodeGen/MachineFunctionInitializer.h"
00024 #include "llvm/CodeGen/MachineFunctionPass.h"
00025 #include "llvm/CodeGen/MachineInstr.h"
00026 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00027 #include "llvm/CodeGen/MachineModuleInfo.h"
00028 #include "llvm/CodeGen/MachineRegisterInfo.h"
00029 #include "llvm/CodeGen/Passes.h"
00030 #include "llvm/CodeGen/PseudoSourceValue.h"
00031 #include "llvm/CodeGen/WinEHFuncInfo.h"
00032 #include "llvm/IR/DataLayout.h"
00033 #include "llvm/IR/DebugInfo.h"
00034 #include "llvm/IR/Function.h"
00035 #include "llvm/IR/Module.h"
00036 #include "llvm/IR/ModuleSlotTracker.h"
00037 #include "llvm/MC/MCAsmInfo.h"
00038 #include "llvm/MC/MCContext.h"
00039 #include "llvm/Support/Debug.h"
00040 #include "llvm/Support/GraphWriter.h"
00041 #include "llvm/Support/raw_ostream.h"
00042 #include "llvm/Target/TargetFrameLowering.h"
00043 #include "llvm/Target/TargetLowering.h"
00044 #include "llvm/Target/TargetMachine.h"
00045 #include "llvm/Target/TargetSubtargetInfo.h"
00046 using namespace llvm;
00047 
00048 #define DEBUG_TYPE "codegen"
00049 
00050 static cl::opt<unsigned>
00051     AlignAllFunctions("align-all-functions",
00052                       cl::desc("Force the alignment of all functions."),
00053                       cl::init(0), cl::Hidden);
00054 
00055 void MachineFunctionInitializer::anchor() {}
00056 
00057 //===----------------------------------------------------------------------===//
00058 // MachineFunction implementation
00059 //===----------------------------------------------------------------------===//
00060 
00061 // Out-of-line virtual method.
00062 MachineFunctionInfo::~MachineFunctionInfo() {}
00063 
00064 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
00065   MBB->getParent()->DeleteMachineBasicBlock(MBB);
00066 }
00067 
00068 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
00069                                  unsigned FunctionNum, MachineModuleInfo &mmi)
00070     : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
00071       MMI(mmi) {
00072   if (STI->getRegisterInfo())
00073     RegInfo = new (Allocator) MachineRegisterInfo(this);
00074   else
00075     RegInfo = nullptr;
00076 
00077   MFInfo = nullptr;
00078   FrameInfo = new (Allocator)
00079       MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
00080                        STI->getFrameLowering()->isStackRealignable(),
00081                        !F->hasFnAttribute("no-realign-stack"));
00082 
00083   if (Fn->hasFnAttribute(Attribute::StackAlignment))
00084     FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
00085 
00086   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
00087   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
00088 
00089   // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
00090   // FIXME: Use Function::optForSize().
00091   if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
00092     Alignment = std::max(Alignment,
00093                          STI->getTargetLowering()->getPrefFunctionAlignment());
00094 
00095   if (AlignAllFunctions)
00096     Alignment = AlignAllFunctions;
00097 
00098   FunctionNumber = FunctionNum;
00099   JumpTableInfo = nullptr;
00100 
00101   if (isFuncletEHPersonality(classifyEHPersonality(
00102           F->hasPersonalityFn() ? F->getPersonalityFn() : nullptr))) {
00103     WinEHInfo = new (Allocator) WinEHFuncInfo();
00104   }
00105 
00106   assert(TM.isCompatibleDataLayout(getDataLayout()) &&
00107          "Can't create a MachineFunction using a Module with a "
00108          "Target-incompatible DataLayout attached\n");
00109 
00110   PSVManager = llvm::make_unique<PseudoSourceValueManager>();
00111 }
00112 
00113 MachineFunction::~MachineFunction() {
00114   // Don't call destructors on MachineInstr and MachineOperand. All of their
00115   // memory comes from the BumpPtrAllocator which is about to be purged.
00116   //
00117   // Do call MachineBasicBlock destructors, it contains std::vectors.
00118   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
00119     I->Insts.clearAndLeakNodesUnsafely();
00120 
00121   InstructionRecycler.clear(Allocator);
00122   OperandRecycler.clear(Allocator);
00123   BasicBlockRecycler.clear(Allocator);
00124   if (RegInfo) {
00125     RegInfo->~MachineRegisterInfo();
00126     Allocator.Deallocate(RegInfo);
00127   }
00128   if (MFInfo) {
00129     MFInfo->~MachineFunctionInfo();
00130     Allocator.Deallocate(MFInfo);
00131   }
00132 
00133   FrameInfo->~MachineFrameInfo();
00134   Allocator.Deallocate(FrameInfo);
00135 
00136   ConstantPool->~MachineConstantPool();
00137   Allocator.Deallocate(ConstantPool);
00138 
00139   if (JumpTableInfo) {
00140     JumpTableInfo->~MachineJumpTableInfo();
00141     Allocator.Deallocate(JumpTableInfo);
00142   }
00143 
00144   if (WinEHInfo) {
00145     WinEHInfo->~WinEHFuncInfo();
00146     Allocator.Deallocate(WinEHInfo);
00147   }
00148 }
00149 
00150 const DataLayout &MachineFunction::getDataLayout() const {
00151   return Fn->getParent()->getDataLayout();
00152 }
00153 
00154 /// Get the JumpTableInfo for this function.
00155 /// If it does not already exist, allocate one.
00156 MachineJumpTableInfo *MachineFunction::
00157 getOrCreateJumpTableInfo(unsigned EntryKind) {
00158   if (JumpTableInfo) return JumpTableInfo;
00159 
00160   JumpTableInfo = new (Allocator)
00161     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
00162   return JumpTableInfo;
00163 }
00164 
00165 /// Should we be emitting segmented stack stuff for the function
00166 bool MachineFunction::shouldSplitStack() const {
00167   return getFunction()->hasFnAttribute("split-stack");
00168 }
00169 
00170 /// This discards all of the MachineBasicBlock numbers and recomputes them.
00171 /// This guarantees that the MBB numbers are sequential, dense, and match the
00172 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
00173 /// is specified, only that block and those after it are renumbered.
00174 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
00175   if (empty()) { MBBNumbering.clear(); return; }
00176   MachineFunction::iterator MBBI, E = end();
00177   if (MBB == nullptr)
00178     MBBI = begin();
00179   else
00180     MBBI = MBB->getIterator();
00181 
00182   // Figure out the block number this should have.
00183   unsigned BlockNo = 0;
00184   if (MBBI != begin())
00185     BlockNo = std::prev(MBBI)->getNumber() + 1;
00186 
00187   for (; MBBI != E; ++MBBI, ++BlockNo) {
00188     if (MBBI->getNumber() != (int)BlockNo) {
00189       // Remove use of the old number.
00190       if (MBBI->getNumber() != -1) {
00191         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
00192                "MBB number mismatch!");
00193         MBBNumbering[MBBI->getNumber()] = nullptr;
00194       }
00195 
00196       // If BlockNo is already taken, set that block's number to -1.
00197       if (MBBNumbering[BlockNo])
00198         MBBNumbering[BlockNo]->setNumber(-1);
00199 
00200       MBBNumbering[BlockNo] = &*MBBI;
00201       MBBI->setNumber(BlockNo);
00202     }
00203   }
00204 
00205   // Okay, all the blocks are renumbered.  If we have compactified the block
00206   // numbering, shrink MBBNumbering now.
00207   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
00208   MBBNumbering.resize(BlockNo);
00209 }
00210 
00211 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
00212 MachineInstr *
00213 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
00214                                     DebugLoc DL, bool NoImp) {
00215   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
00216     MachineInstr(*this, MCID, DL, NoImp);
00217 }
00218 
00219 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
00220 /// identical in all ways except the instruction has no parent, prev, or next.
00221 MachineInstr *
00222 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
00223   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
00224              MachineInstr(*this, *Orig);
00225 }
00226 
00227 /// Delete the given MachineInstr.
00228 ///
00229 /// This function also serves as the MachineInstr destructor - the real
00230 /// ~MachineInstr() destructor must be empty.
00231 void
00232 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
00233   // Strip it for parts. The operand array and the MI object itself are
00234   // independently recyclable.
00235   if (MI->Operands)
00236     deallocateOperandArray(MI->CapOperands, MI->Operands);
00237   // Don't call ~MachineInstr() which must be trivial anyway because
00238   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
00239   // destructors.
00240   InstructionRecycler.Deallocate(Allocator, MI);
00241 }
00242 
00243 /// Allocate a new MachineBasicBlock. Use this instead of
00244 /// `new MachineBasicBlock'.
00245 MachineBasicBlock *
00246 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
00247   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
00248              MachineBasicBlock(*this, bb);
00249 }
00250 
00251 /// Delete the given MachineBasicBlock.
00252 void
00253 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
00254   assert(MBB->getParent() == this && "MBB parent mismatch!");
00255   MBB->~MachineBasicBlock();
00256   BasicBlockRecycler.Deallocate(Allocator, MBB);
00257 }
00258 
00259 MachineMemOperand *
00260 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
00261                                       uint64_t s, unsigned base_alignment,
00262                                       const AAMDNodes &AAInfo,
00263                                       const MDNode *Ranges) {
00264   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
00265                                            AAInfo, Ranges);
00266 }
00267 
00268 MachineMemOperand *
00269 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
00270                                       int64_t Offset, uint64_t Size) {
00271   if (MMO->getValue())
00272     return new (Allocator)
00273                MachineMemOperand(MachinePointerInfo(MMO->getValue(),
00274                                                     MMO->getOffset()+Offset),
00275                                  MMO->getFlags(), Size,
00276                                  MMO->getBaseAlignment());
00277   return new (Allocator)
00278              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
00279                                                   MMO->getOffset()+Offset),
00280                                MMO->getFlags(), Size,
00281                                MMO->getBaseAlignment());
00282 }
00283 
00284 MachineInstr::mmo_iterator
00285 MachineFunction::allocateMemRefsArray(unsigned long Num) {
00286   return Allocator.Allocate<MachineMemOperand *>(Num);
00287 }
00288 
00289 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
00290 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
00291                                     MachineInstr::mmo_iterator End) {
00292   // Count the number of load mem refs.
00293   unsigned Num = 0;
00294   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
00295     if ((*I)->isLoad())
00296       ++Num;
00297 
00298   // Allocate a new array and populate it with the load information.
00299   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
00300   unsigned Index = 0;
00301   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
00302     if ((*I)->isLoad()) {
00303       if (!(*I)->isStore())
00304         // Reuse the MMO.
00305         Result[Index] = *I;
00306       else {
00307         // Clone the MMO and unset the store flag.
00308         MachineMemOperand *JustLoad =
00309           getMachineMemOperand((*I)->getPointerInfo(),
00310                                (*I)->getFlags() & ~MachineMemOperand::MOStore,
00311                                (*I)->getSize(), (*I)->getBaseAlignment(),
00312                                (*I)->getAAInfo());
00313         Result[Index] = JustLoad;
00314       }
00315       ++Index;
00316     }
00317   }
00318   return std::make_pair(Result, Result + Num);
00319 }
00320 
00321 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
00322 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
00323                                      MachineInstr::mmo_iterator End) {
00324   // Count the number of load mem refs.
00325   unsigned Num = 0;
00326   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
00327     if ((*I)->isStore())
00328       ++Num;
00329 
00330   // Allocate a new array and populate it with the store information.
00331   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
00332   unsigned Index = 0;
00333   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
00334     if ((*I)->isStore()) {
00335       if (!(*I)->isLoad())
00336         // Reuse the MMO.
00337         Result[Index] = *I;
00338       else {
00339         // Clone the MMO and unset the load flag.
00340         MachineMemOperand *JustStore =
00341           getMachineMemOperand((*I)->getPointerInfo(),
00342                                (*I)->getFlags() & ~MachineMemOperand::MOLoad,
00343                                (*I)->getSize(), (*I)->getBaseAlignment(),
00344                                (*I)->getAAInfo());
00345         Result[Index] = JustStore;
00346       }
00347       ++Index;
00348     }
00349   }
00350   return std::make_pair(Result, Result + Num);
00351 }
00352 
00353 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
00354   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
00355   std::copy(Name.begin(), Name.end(), Dest);
00356   Dest[Name.size()] = 0;
00357   return Dest;
00358 }
00359 
00360 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00361 void MachineFunction::dump() const {
00362   print(dbgs());
00363 }
00364 #endif
00365 
00366 StringRef MachineFunction::getName() const {
00367   assert(getFunction() && "No function!");
00368   return getFunction()->getName();
00369 }
00370 
00371 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
00372   OS << "# Machine code for function " << getName() << ": ";
00373   if (RegInfo) {
00374     OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
00375     if (!RegInfo->tracksLiveness())
00376       OS << ", not tracking liveness";
00377   }
00378   OS << '\n';
00379 
00380   // Print Frame Information
00381   FrameInfo->print(*this, OS);
00382 
00383   // Print JumpTable Information
00384   if (JumpTableInfo)
00385     JumpTableInfo->print(OS);
00386 
00387   // Print Constant Pool
00388   ConstantPool->print(OS);
00389 
00390   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
00391 
00392   if (RegInfo && !RegInfo->livein_empty()) {
00393     OS << "Function Live Ins: ";
00394     for (MachineRegisterInfo::livein_iterator
00395          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
00396       OS << PrintReg(I->first, TRI);
00397       if (I->second)
00398         OS << " in " << PrintReg(I->second, TRI);
00399       if (std::next(I) != E)
00400         OS << ", ";
00401     }
00402     OS << '\n';
00403   }
00404 
00405   ModuleSlotTracker MST(getFunction()->getParent());
00406   MST.incorporateFunction(*getFunction());
00407   for (const auto &BB : *this) {
00408     OS << '\n';
00409     BB.print(OS, MST, Indexes);
00410   }
00411 
00412   OS << "\n# End machine code for function " << getName() << ".\n\n";
00413 }
00414 
00415 namespace llvm {
00416   template<>
00417   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
00418 
00419   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
00420 
00421     static std::string getGraphName(const MachineFunction *F) {
00422       return ("CFG for '" + F->getName() + "' function").str();
00423     }
00424 
00425     std::string getNodeLabel(const MachineBasicBlock *Node,
00426                              const MachineFunction *Graph) {
00427       std::string OutStr;
00428       {
00429         raw_string_ostream OSS(OutStr);
00430 
00431         if (isSimple()) {
00432           OSS << "BB#" << Node->getNumber();
00433           if (const BasicBlock *BB = Node->getBasicBlock())
00434             OSS << ": " << BB->getName();
00435         } else
00436           Node->print(OSS);
00437       }
00438 
00439       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
00440 
00441       // Process string output to make it nicer...
00442       for (unsigned i = 0; i != OutStr.length(); ++i)
00443         if (OutStr[i] == '\n') {                            // Left justify
00444           OutStr[i] = '\\';
00445           OutStr.insert(OutStr.begin()+i+1, 'l');
00446         }
00447       return OutStr;
00448     }
00449   };
00450 }
00451 
00452 void MachineFunction::viewCFG() const
00453 {
00454 #ifndef NDEBUG
00455   ViewGraph(this, "mf" + getName());
00456 #else
00457   errs() << "MachineFunction::viewCFG is only available in debug builds on "
00458          << "systems with Graphviz or gv!\n";
00459 #endif // NDEBUG
00460 }
00461 
00462 void MachineFunction::viewCFGOnly() const
00463 {
00464 #ifndef NDEBUG
00465   ViewGraph(this, "mf" + getName(), true);
00466 #else
00467   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
00468          << "systems with Graphviz or gv!\n";
00469 #endif // NDEBUG
00470 }
00471 
00472 /// Add the specified physical register as a live-in value and
00473 /// create a corresponding virtual register for it.
00474 unsigned MachineFunction::addLiveIn(unsigned PReg,
00475                                     const TargetRegisterClass *RC) {
00476   MachineRegisterInfo &MRI = getRegInfo();
00477   unsigned VReg = MRI.getLiveInVirtReg(PReg);
00478   if (VReg) {
00479     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
00480     (void)VRegRC;
00481     // A physical register can be added several times.
00482     // Between two calls, the register class of the related virtual register
00483     // may have been constrained to match some operation constraints.
00484     // In that case, check that the current register class includes the
00485     // physical register and is a sub class of the specified RC.
00486     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
00487                              RC->hasSubClassEq(VRegRC))) &&
00488             "Register class mismatch!");
00489     return VReg;
00490   }
00491   VReg = MRI.createVirtualRegister(RC);
00492   MRI.addLiveIn(PReg, VReg);
00493   return VReg;
00494 }
00495 
00496 /// Return the MCSymbol for the specified non-empty jump table.
00497 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
00498 /// normal 'L' label is returned.
00499 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
00500                                         bool isLinkerPrivate) const {
00501   const DataLayout &DL = getDataLayout();
00502   assert(JumpTableInfo && "No jump tables");
00503   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
00504 
00505   const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
00506                                        : DL.getPrivateGlobalPrefix();
00507   SmallString<60> Name;
00508   raw_svector_ostream(Name)
00509     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
00510   return Ctx.getOrCreateSymbol(Name);
00511 }
00512 
00513 /// Return a function-local symbol to represent the PIC base.
00514 MCSymbol *MachineFunction::getPICBaseSymbol() const {
00515   const DataLayout &DL = getDataLayout();
00516   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
00517                                Twine(getFunctionNumber()) + "$pb");
00518 }
00519 
00520 //===----------------------------------------------------------------------===//
00521 //  MachineFrameInfo implementation
00522 //===----------------------------------------------------------------------===//
00523 
00524 /// Make sure the function is at least Align bytes aligned.
00525 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
00526   if (!StackRealignable || !RealignOption)
00527     assert(Align <= StackAlignment &&
00528            "For targets without stack realignment, Align is out of limit!");
00529   if (MaxAlignment < Align) MaxAlignment = Align;
00530 }
00531 
00532 /// Clamp the alignment if requested and emit a warning.
00533 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
00534                                            unsigned StackAlign) {
00535   if (!ShouldClamp || Align <= StackAlign)
00536     return Align;
00537   DEBUG(dbgs() << "Warning: requested alignment " << Align
00538                << " exceeds the stack alignment " << StackAlign
00539                << " when stack realignment is off" << '\n');
00540   return StackAlign;
00541 }
00542 
00543 /// Create a new statically sized stack object, returning a nonnegative
00544 /// identifier to represent it.
00545 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
00546                       bool isSS, const AllocaInst *Alloca) {
00547   assert(Size != 0 && "Cannot allocate zero size stack objects!");
00548   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00549                                   Alignment, StackAlignment);
00550   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
00551                                 !isSS));
00552   int Index = (int)Objects.size() - NumFixedObjects - 1;
00553   assert(Index >= 0 && "Bad frame index!");
00554   ensureMaxAlignment(Alignment);
00555   return Index;
00556 }
00557 
00558 /// Create a new statically sized stack object that represents a spill slot,
00559 /// returning a nonnegative identifier to represent it.
00560 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
00561                                              unsigned Alignment) {
00562   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00563                                   Alignment, StackAlignment);
00564   CreateStackObject(Size, Alignment, true);
00565   int Index = (int)Objects.size() - NumFixedObjects - 1;
00566   ensureMaxAlignment(Alignment);
00567   return Index;
00568 }
00569 
00570 /// Notify the MachineFrameInfo object that a variable sized object has been
00571 /// created. This must be created whenever a variable sized object is created,
00572 /// whether or not the index returned is actually used.
00573 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
00574                                                 const AllocaInst *Alloca) {
00575   HasVarSizedObjects = true;
00576   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00577                                   Alignment, StackAlignment);
00578   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
00579   ensureMaxAlignment(Alignment);
00580   return (int)Objects.size()-NumFixedObjects-1;
00581 }
00582 
00583 /// Create a new object at a fixed location on the stack.
00584 /// All fixed objects should be created before other objects are created for
00585 /// efficiency. By default, fixed objects are immutable. This returns an
00586 /// index with a negative value.
00587 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
00588                                         bool Immutable, bool isAliased) {
00589   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
00590   // The alignment of the frame index can be determined from its offset from
00591   // the incoming frame position.  If the frame object is at offset 32 and
00592   // the stack is guaranteed to be 16-byte aligned, then we know that the
00593   // object is 16-byte aligned.
00594   unsigned Align = MinAlign(SPOffset, StackAlignment);
00595   Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
00596                               StackAlignment);
00597   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
00598                                               /*isSS*/   false,
00599                                               /*Alloca*/ nullptr, isAliased));
00600   return -++NumFixedObjects;
00601 }
00602 
00603 /// Create a spill slot at a fixed location on the stack.
00604 /// Returns an index with a negative value.
00605 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
00606                                                   int64_t SPOffset) {
00607   unsigned Align = MinAlign(SPOffset, StackAlignment);
00608   Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
00609                               StackAlignment);
00610   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
00611                                               /*Immutable*/ true,
00612                                               /*isSS*/ true,
00613                                               /*Alloca*/ nullptr,
00614                                               /*isAliased*/ false));
00615   return -++NumFixedObjects;
00616 }
00617 
00618 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
00619   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00620   BitVector BV(TRI->getNumRegs());
00621 
00622   // Before CSI is calculated, no registers are considered pristine. They can be
00623   // freely used and PEI will make sure they are saved.
00624   if (!isCalleeSavedInfoValid())
00625     return BV;
00626 
00627   for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
00628     BV.set(*CSR);
00629 
00630   // Saved CSRs are not pristine.
00631   for (auto &I : getCalleeSavedInfo())
00632     for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S)
00633       BV.reset(*S);
00634 
00635   return BV;
00636 }
00637 
00638 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
00639   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
00640   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
00641   unsigned MaxAlign = getMaxAlignment();
00642   int Offset = 0;
00643 
00644   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
00645   // It really should be refactored to share code. Until then, changes
00646   // should keep in mind that there's tight coupling between the two.
00647 
00648   for (int i = getObjectIndexBegin(); i != 0; ++i) {
00649     int FixedOff = -getObjectOffset(i);
00650     if (FixedOff > Offset) Offset = FixedOff;
00651   }
00652   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
00653     if (isDeadObjectIndex(i))
00654       continue;
00655     Offset += getObjectSize(i);
00656     unsigned Align = getObjectAlignment(i);
00657     // Adjust to alignment boundary
00658     Offset = (Offset+Align-1)/Align*Align;
00659 
00660     MaxAlign = std::max(Align, MaxAlign);
00661   }
00662 
00663   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
00664     Offset += getMaxCallFrameSize();
00665 
00666   // Round up the size to a multiple of the alignment.  If the function has
00667   // any calls or alloca's, align to the target's StackAlignment value to
00668   // ensure that the callee's frame or the alloca data is suitably aligned;
00669   // otherwise, for leaf functions, align to the TransientStackAlignment
00670   // value.
00671   unsigned StackAlign;
00672   if (adjustsStack() || hasVarSizedObjects() ||
00673       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
00674     StackAlign = TFI->getStackAlignment();
00675   else
00676     StackAlign = TFI->getTransientStackAlignment();
00677 
00678   // If the frame pointer is eliminated, all frame offsets will be relative to
00679   // SP not FP. Align to MaxAlign so this works.
00680   StackAlign = std::max(StackAlign, MaxAlign);
00681   unsigned AlignMask = StackAlign - 1;
00682   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
00683 
00684   return (unsigned)Offset;
00685 }
00686 
00687 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
00688   if (Objects.empty()) return;
00689 
00690   const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
00691   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
00692 
00693   OS << "Frame Objects:\n";
00694 
00695   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
00696     const StackObject &SO = Objects[i];
00697     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
00698     if (SO.Size == ~0ULL) {
00699       OS << "dead\n";
00700       continue;
00701     }
00702     if (SO.Size == 0)
00703       OS << "variable sized";
00704     else
00705       OS << "size=" << SO.Size;
00706     OS << ", align=" << SO.Alignment;
00707 
00708     if (i < NumFixedObjects)
00709       OS << ", fixed";
00710     if (i < NumFixedObjects || SO.SPOffset != -1) {
00711       int64_t Off = SO.SPOffset - ValOffset;
00712       OS << ", at location [SP";
00713       if (Off > 0)
00714         OS << "+" << Off;
00715       else if (Off < 0)
00716         OS << Off;
00717       OS << "]";
00718     }
00719     OS << "\n";
00720   }
00721 }
00722 
00723 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00724 void MachineFrameInfo::dump(const MachineFunction &MF) const {
00725   print(MF, dbgs());
00726 }
00727 #endif
00728 
00729 //===----------------------------------------------------------------------===//
00730 //  MachineJumpTableInfo implementation
00731 //===----------------------------------------------------------------------===//
00732 
00733 /// Return the size of each entry in the jump table.
00734 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
00735   // The size of a jump table entry is 4 bytes unless the entry is just the
00736   // address of a block, in which case it is the pointer size.
00737   switch (getEntryKind()) {
00738   case MachineJumpTableInfo::EK_BlockAddress:
00739     return TD.getPointerSize();
00740   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00741     return 8;
00742   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00743   case MachineJumpTableInfo::EK_LabelDifference32:
00744   case MachineJumpTableInfo::EK_Custom32:
00745     return 4;
00746   case MachineJumpTableInfo::EK_Inline:
00747     return 0;
00748   }
00749   llvm_unreachable("Unknown jump table encoding!");
00750 }
00751 
00752 /// Return the alignment of each entry in the jump table.
00753 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
00754   // The alignment of a jump table entry is the alignment of int32 unless the
00755   // entry is just the address of a block, in which case it is the pointer
00756   // alignment.
00757   switch (getEntryKind()) {
00758   case MachineJumpTableInfo::EK_BlockAddress:
00759     return TD.getPointerABIAlignment();
00760   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00761     return TD.getABIIntegerTypeAlignment(64);
00762   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00763   case MachineJumpTableInfo::EK_LabelDifference32:
00764   case MachineJumpTableInfo::EK_Custom32:
00765     return TD.getABIIntegerTypeAlignment(32);
00766   case MachineJumpTableInfo::EK_Inline:
00767     return 1;
00768   }
00769   llvm_unreachable("Unknown jump table encoding!");
00770 }
00771 
00772 /// Create a new jump table entry in the jump table info.
00773 unsigned MachineJumpTableInfo::createJumpTableIndex(
00774                                const std::vector<MachineBasicBlock*> &DestBBs) {
00775   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
00776   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
00777   return JumpTables.size()-1;
00778 }
00779 
00780 /// If Old is the target of any jump tables, update the jump tables to branch
00781 /// to New instead.
00782 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
00783                                                   MachineBasicBlock *New) {
00784   assert(Old != New && "Not making a change?");
00785   bool MadeChange = false;
00786   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
00787     ReplaceMBBInJumpTable(i, Old, New);
00788   return MadeChange;
00789 }
00790 
00791 /// If Old is a target of the jump tables, update the jump table to branch to
00792 /// New instead.
00793 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
00794                                                  MachineBasicBlock *Old,
00795                                                  MachineBasicBlock *New) {
00796   assert(Old != New && "Not making a change?");
00797   bool MadeChange = false;
00798   MachineJumpTableEntry &JTE = JumpTables[Idx];
00799   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
00800     if (JTE.MBBs[j] == Old) {
00801       JTE.MBBs[j] = New;
00802       MadeChange = true;
00803     }
00804   return MadeChange;
00805 }
00806 
00807 void MachineJumpTableInfo::print(raw_ostream &OS) const {
00808   if (JumpTables.empty()) return;
00809 
00810   OS << "Jump Tables:\n";
00811 
00812   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
00813     OS << "  jt#" << i << ": ";
00814     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
00815       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
00816   }
00817 
00818   OS << '\n';
00819 }
00820 
00821 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00822 void MachineJumpTableInfo::dump() const { print(dbgs()); }
00823 #endif
00824 
00825 
00826 //===----------------------------------------------------------------------===//
00827 //  MachineConstantPool implementation
00828 //===----------------------------------------------------------------------===//
00829 
00830 void MachineConstantPoolValue::anchor() { }
00831 
00832 Type *MachineConstantPoolEntry::getType() const {
00833   if (isMachineConstantPoolEntry())
00834     return Val.MachineCPVal->getType();
00835   return Val.ConstVal->getType();
00836 }
00837 
00838 bool MachineConstantPoolEntry::needsRelocation() const {
00839   if (isMachineConstantPoolEntry())
00840     return true;
00841   return Val.ConstVal->needsRelocation();
00842 }
00843 
00844 SectionKind
00845 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
00846   if (needsRelocation())
00847     return SectionKind::getReadOnlyWithRel();
00848   switch (DL->getTypeAllocSize(getType())) {
00849   case 4:
00850     return SectionKind::getMergeableConst4();
00851   case 8:
00852     return SectionKind::getMergeableConst8();
00853   case 16:
00854     return SectionKind::getMergeableConst16();
00855   default:
00856     return SectionKind::getReadOnly();
00857   }
00858 }
00859 
00860 MachineConstantPool::~MachineConstantPool() {
00861   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00862     if (Constants[i].isMachineConstantPoolEntry())
00863       delete Constants[i].Val.MachineCPVal;
00864   for (DenseSet<MachineConstantPoolValue*>::iterator I =
00865        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
00866        I != E; ++I)
00867     delete *I;
00868 }
00869 
00870 /// Test whether the given two constants can be allocated the same constant pool
00871 /// entry.
00872 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
00873                                       const DataLayout &DL) {
00874   // Handle the trivial case quickly.
00875   if (A == B) return true;
00876 
00877   // If they have the same type but weren't the same constant, quickly
00878   // reject them.
00879   if (A->getType() == B->getType()) return false;
00880 
00881   // We can't handle structs or arrays.
00882   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
00883       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
00884     return false;
00885 
00886   // For now, only support constants with the same size.
00887   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
00888   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
00889     return false;
00890 
00891   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
00892 
00893   // Try constant folding a bitcast of both instructions to an integer.  If we
00894   // get two identical ConstantInt's, then we are good to share them.  We use
00895   // the constant folding APIs to do this so that we get the benefit of
00896   // DataLayout.
00897   if (isa<PointerType>(A->getType()))
00898     A = ConstantFoldCastOperand(Instruction::PtrToInt,
00899                                 const_cast<Constant *>(A), IntTy, DL);
00900   else if (A->getType() != IntTy)
00901     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
00902                                 IntTy, DL);
00903   if (isa<PointerType>(B->getType()))
00904     B = ConstantFoldCastOperand(Instruction::PtrToInt,
00905                                 const_cast<Constant *>(B), IntTy, DL);
00906   else if (B->getType() != IntTy)
00907     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
00908                                 IntTy, DL);
00909 
00910   return A == B;
00911 }
00912 
00913 /// Create a new entry in the constant pool or return an existing one.
00914 /// User must specify the log2 of the minimum required alignment for the object.
00915 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
00916                                                    unsigned Alignment) {
00917   assert(Alignment && "Alignment must be specified!");
00918   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00919 
00920   // Check to see if we already have this constant.
00921   //
00922   // FIXME, this could be made much more efficient for large constant pools.
00923   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00924     if (!Constants[i].isMachineConstantPoolEntry() &&
00925         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
00926       if ((unsigned)Constants[i].getAlignment() < Alignment)
00927         Constants[i].Alignment = Alignment;
00928       return i;
00929     }
00930 
00931   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
00932   return Constants.size()-1;
00933 }
00934 
00935 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
00936                                                    unsigned Alignment) {
00937   assert(Alignment && "Alignment must be specified!");
00938   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00939 
00940   // Check to see if we already have this constant.
00941   //
00942   // FIXME, this could be made much more efficient for large constant pools.
00943   int Idx = V->getExistingMachineCPValue(this, Alignment);
00944   if (Idx != -1) {
00945     MachineCPVsSharingEntries.insert(V);
00946     return (unsigned)Idx;
00947   }
00948 
00949   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
00950   return Constants.size()-1;
00951 }
00952 
00953 void MachineConstantPool::print(raw_ostream &OS) const {
00954   if (Constants.empty()) return;
00955 
00956   OS << "Constant Pool:\n";
00957   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
00958     OS << "  cp#" << i << ": ";
00959     if (Constants[i].isMachineConstantPoolEntry())
00960       Constants[i].Val.MachineCPVal->print(OS);
00961     else
00962       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
00963     OS << ", align=" << Constants[i].getAlignment();
00964     OS << "\n";
00965   }
00966 }
00967 
00968 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00969 void MachineConstantPool::dump() const { print(dbgs()); }
00970 #endif