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