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