LLVM API Documentation

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