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/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     : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
00058       MMI(mmi) {
00059   if (STI->getRegisterInfo())
00060     RegInfo = new (Allocator) MachineRegisterInfo(this);
00061   else
00062     RegInfo = nullptr;
00063 
00064   MFInfo = nullptr;
00065   FrameInfo = new (Allocator)
00066       MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
00067                        STI->getFrameLowering()->isStackRealignable(),
00068                        !F->hasFnAttribute("no-realign-stack"));
00069 
00070   if (Fn->hasFnAttribute(Attribute::StackAlignment))
00071     FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
00072 
00073   ConstantPool = new (Allocator) MachineConstantPool(TM);
00074   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
00075 
00076   // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
00077   if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
00078     Alignment = std::max(Alignment,
00079                          STI->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 AAMDNodes &AAInfo,
00233                                       const MDNode *Ranges) {
00234   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
00235                                            AAInfo, 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());
00247   return new (Allocator)
00248              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
00249                                                   MMO->getOffset()+Offset),
00250                                MMO->getFlags(), Size,
00251                                MMO->getBaseAlignment());
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)->getAAInfo());
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)->getAAInfo());
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 = getSubtarget().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() + "' function").str();
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);
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 /// ensureMaxAlignment - Make sure the function is at least Align bytes
00487 /// aligned.
00488 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
00489   if (!StackRealignable || !RealignOption)
00490     assert(Align <= StackAlignment &&
00491            "For targets without stack realignment, Align is out of limit!");
00492   if (MaxAlignment < Align) MaxAlignment = Align;
00493 }
00494 
00495 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
00496 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
00497                                            unsigned StackAlign) {
00498   if (!ShouldClamp || Align <= StackAlign)
00499     return Align;
00500   DEBUG(dbgs() << "Warning: requested alignment " << Align
00501                << " exceeds the stack alignment " << StackAlign
00502                << " when stack realignment is off" << '\n');
00503   return StackAlign;
00504 }
00505 
00506 /// CreateStackObject - Create a new statically sized stack object, returning
00507 /// a nonnegative identifier to represent it.
00508 ///
00509 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
00510                       bool isSS, const AllocaInst *Alloca) {
00511   assert(Size != 0 && "Cannot allocate zero size stack objects!");
00512   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00513                                   Alignment, StackAlignment);
00514   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
00515                                 !isSS));
00516   int Index = (int)Objects.size() - NumFixedObjects - 1;
00517   assert(Index >= 0 && "Bad frame index!");
00518   ensureMaxAlignment(Alignment);
00519   return Index;
00520 }
00521 
00522 /// CreateSpillStackObject - Create a new statically sized stack object that
00523 /// represents a spill slot, returning a nonnegative identifier to represent
00524 /// it.
00525 ///
00526 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
00527                                              unsigned Alignment) {
00528   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00529                                   Alignment, StackAlignment);
00530   CreateStackObject(Size, Alignment, true);
00531   int Index = (int)Objects.size() - NumFixedObjects - 1;
00532   ensureMaxAlignment(Alignment);
00533   return Index;
00534 }
00535 
00536 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
00537 /// variable sized object has been created.  This must be created whenever a
00538 /// variable sized object is created, whether or not the index returned is
00539 /// actually used.
00540 ///
00541 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
00542                                                 const AllocaInst *Alloca) {
00543   HasVarSizedObjects = true;
00544   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00545                                   Alignment, StackAlignment);
00546   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
00547   ensureMaxAlignment(Alignment);
00548   return (int)Objects.size()-NumFixedObjects-1;
00549 }
00550 
00551 /// CreateFixedObject - Create a new object at a fixed location on the stack.
00552 /// All fixed objects should be created before other objects are created for
00553 /// efficiency. By default, fixed objects are immutable. This returns an
00554 /// index with a negative value.
00555 ///
00556 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
00557                                         bool Immutable, bool isAliased) {
00558   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
00559   // The alignment of the frame index can be determined from its offset from
00560   // the incoming frame position.  If the frame object is at offset 32 and
00561   // the stack is guaranteed to be 16-byte aligned, then we know that the
00562   // object is 16-byte aligned.
00563   unsigned Align = MinAlign(SPOffset, StackAlignment);
00564   Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
00565                               StackAlignment);
00566   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
00567                                               /*isSS*/   false,
00568                                               /*Alloca*/ nullptr, isAliased));
00569   return -++NumFixedObjects;
00570 }
00571 
00572 /// CreateFixedSpillStackObject - Create a spill slot at a fixed location
00573 /// on the stack.  Returns an index with a negative value.
00574 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
00575                                                   int64_t SPOffset) {
00576   unsigned Align = MinAlign(SPOffset, StackAlignment);
00577   Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
00578                               StackAlignment);
00579   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
00580                                               /*Immutable*/ true,
00581                                               /*isSS*/ true,
00582                                               /*Alloca*/ nullptr,
00583                                               /*isAliased*/ false));
00584   return -++NumFixedObjects;
00585 }
00586 
00587 BitVector
00588 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
00589   assert(MBB && "MBB must be valid");
00590   const MachineFunction *MF = MBB->getParent();
00591   assert(MF && "MBB must be part of a MachineFunction");
00592   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00593   BitVector BV(TRI->getNumRegs());
00594 
00595   // Before CSI is calculated, no registers are considered pristine. They can be
00596   // freely used and PEI will make sure they are saved.
00597   if (!isCalleeSavedInfoValid())
00598     return BV;
00599 
00600   for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
00601     BV.set(*CSR);
00602 
00603   // Each MBB before the save point has all CSRs pristine.
00604   if (isBeforeSavePoint(*MF, *MBB))
00605     return BV;
00606 
00607   // On other MBBs the saved CSRs are not pristine.
00608   const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
00609   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
00610          E = CSI.end(); I != E; ++I)
00611     BV.reset(I->getReg());
00612 
00613   return BV;
00614 }
00615 
00616 // Note: We could use some sort of caching mecanism, but we lack the ability
00617 // to know when the cache is invalid, i.e., the CFG changed.
00618 // Assuming we have that, we can simply compute all the set of MBBs
00619 // that are before the save point.
00620 bool MachineFrameInfo::isBeforeSavePoint(const MachineFunction &MF,
00621                                          const MachineBasicBlock &MBB) const {
00622   // Early exit if shrink-wrapping did not kick.
00623   if (!Save)
00624     return &MBB == &MF.front();
00625 
00626   // Starting from MBB, check if there is a path leading to Save that do
00627   // not cross Restore.
00628   SmallPtrSet<const MachineBasicBlock *, 8> Visited;
00629   SmallVector<const MachineBasicBlock *, 8> WorkList;
00630   WorkList.push_back(&MBB);
00631   Visited.insert(&MBB);
00632   do {
00633     const MachineBasicBlock *CurBB = WorkList.pop_back_val();
00634     // By construction, the region that is after the save point is
00635     // dominated by the Save and post-dominated by the Restore.
00636     // If we do not reach Restore and still reach Save, this
00637     // means MBB is before Save.
00638     if (CurBB == Save)
00639       return true;
00640     if (CurBB == Restore)
00641       continue;
00642     // Enqueue all the successors not already visited.
00643     for (MachineBasicBlock *SuccBB : CurBB->successors())
00644       if (Visited.insert(SuccBB).second)
00645         WorkList.push_back(SuccBB);
00646   } while (!WorkList.empty());
00647   return false;
00648 }
00649 
00650 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
00651   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
00652   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
00653   unsigned MaxAlign = getMaxAlignment();
00654   int Offset = 0;
00655 
00656   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
00657   // It really should be refactored to share code. Until then, changes
00658   // should keep in mind that there's tight coupling between the two.
00659 
00660   for (int i = getObjectIndexBegin(); i != 0; ++i) {
00661     int FixedOff = -getObjectOffset(i);
00662     if (FixedOff > Offset) Offset = FixedOff;
00663   }
00664   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
00665     if (isDeadObjectIndex(i))
00666       continue;
00667     Offset += getObjectSize(i);
00668     unsigned Align = getObjectAlignment(i);
00669     // Adjust to alignment boundary
00670     Offset = (Offset+Align-1)/Align*Align;
00671 
00672     MaxAlign = std::max(Align, MaxAlign);
00673   }
00674 
00675   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
00676     Offset += getMaxCallFrameSize();
00677 
00678   // Round up the size to a multiple of the alignment.  If the function has
00679   // any calls or alloca's, align to the target's StackAlignment value to
00680   // ensure that the callee's frame or the alloca data is suitably aligned;
00681   // otherwise, for leaf functions, align to the TransientStackAlignment
00682   // value.
00683   unsigned StackAlign;
00684   if (adjustsStack() || hasVarSizedObjects() ||
00685       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
00686     StackAlign = TFI->getStackAlignment();
00687   else
00688     StackAlign = TFI->getTransientStackAlignment();
00689 
00690   // If the frame pointer is eliminated, all frame offsets will be relative to
00691   // SP not FP. Align to MaxAlign so this works.
00692   StackAlign = std::max(StackAlign, MaxAlign);
00693   unsigned AlignMask = StackAlign - 1;
00694   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
00695 
00696   return (unsigned)Offset;
00697 }
00698 
00699 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
00700   if (Objects.empty()) return;
00701 
00702   const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
00703   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
00704 
00705   OS << "Frame Objects:\n";
00706 
00707   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
00708     const StackObject &SO = Objects[i];
00709     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
00710     if (SO.Size == ~0ULL) {
00711       OS << "dead\n";
00712       continue;
00713     }
00714     if (SO.Size == 0)
00715       OS << "variable sized";
00716     else
00717       OS << "size=" << SO.Size;
00718     OS << ", align=" << SO.Alignment;
00719 
00720     if (i < NumFixedObjects)
00721       OS << ", fixed";
00722     if (i < NumFixedObjects || SO.SPOffset != -1) {
00723       int64_t Off = SO.SPOffset - ValOffset;
00724       OS << ", at location [SP";
00725       if (Off > 0)
00726         OS << "+" << Off;
00727       else if (Off < 0)
00728         OS << Off;
00729       OS << "]";
00730     }
00731     OS << "\n";
00732   }
00733 }
00734 
00735 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00736 void MachineFrameInfo::dump(const MachineFunction &MF) const {
00737   print(MF, dbgs());
00738 }
00739 #endif
00740 
00741 //===----------------------------------------------------------------------===//
00742 //  MachineJumpTableInfo implementation
00743 //===----------------------------------------------------------------------===//
00744 
00745 /// getEntrySize - Return the size of each entry in the jump table.
00746 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
00747   // The size of a jump table entry is 4 bytes unless the entry is just the
00748   // address of a block, in which case it is the pointer size.
00749   switch (getEntryKind()) {
00750   case MachineJumpTableInfo::EK_BlockAddress:
00751     return TD.getPointerSize();
00752   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00753     return 8;
00754   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00755   case MachineJumpTableInfo::EK_LabelDifference32:
00756   case MachineJumpTableInfo::EK_Custom32:
00757     return 4;
00758   case MachineJumpTableInfo::EK_Inline:
00759     return 0;
00760   }
00761   llvm_unreachable("Unknown jump table encoding!");
00762 }
00763 
00764 /// getEntryAlignment - Return the alignment of each entry in the jump table.
00765 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
00766   // The alignment of a jump table entry is the alignment of int32 unless the
00767   // entry is just the address of a block, in which case it is the pointer
00768   // alignment.
00769   switch (getEntryKind()) {
00770   case MachineJumpTableInfo::EK_BlockAddress:
00771     return TD.getPointerABIAlignment();
00772   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00773     return TD.getABIIntegerTypeAlignment(64);
00774   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00775   case MachineJumpTableInfo::EK_LabelDifference32:
00776   case MachineJumpTableInfo::EK_Custom32:
00777     return TD.getABIIntegerTypeAlignment(32);
00778   case MachineJumpTableInfo::EK_Inline:
00779     return 1;
00780   }
00781   llvm_unreachable("Unknown jump table encoding!");
00782 }
00783 
00784 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
00785 ///
00786 unsigned MachineJumpTableInfo::createJumpTableIndex(
00787                                const std::vector<MachineBasicBlock*> &DestBBs) {
00788   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
00789   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
00790   return JumpTables.size()-1;
00791 }
00792 
00793 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
00794 /// the jump tables to branch to New instead.
00795 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
00796                                                   MachineBasicBlock *New) {
00797   assert(Old != New && "Not making a change?");
00798   bool MadeChange = false;
00799   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
00800     ReplaceMBBInJumpTable(i, Old, New);
00801   return MadeChange;
00802 }
00803 
00804 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
00805 /// the jump table to branch to New instead.
00806 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
00807                                                  MachineBasicBlock *Old,
00808                                                  MachineBasicBlock *New) {
00809   assert(Old != New && "Not making a change?");
00810   bool MadeChange = false;
00811   MachineJumpTableEntry &JTE = JumpTables[Idx];
00812   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
00813     if (JTE.MBBs[j] == Old) {
00814       JTE.MBBs[j] = New;
00815       MadeChange = true;
00816     }
00817   return MadeChange;
00818 }
00819 
00820 void MachineJumpTableInfo::print(raw_ostream &OS) const {
00821   if (JumpTables.empty()) return;
00822 
00823   OS << "Jump Tables:\n";
00824 
00825   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
00826     OS << "  jt#" << i << ": ";
00827     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
00828       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
00829   }
00830 
00831   OS << '\n';
00832 }
00833 
00834 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00835 void MachineJumpTableInfo::dump() const { print(dbgs()); }
00836 #endif
00837 
00838 
00839 //===----------------------------------------------------------------------===//
00840 //  MachineConstantPool implementation
00841 //===----------------------------------------------------------------------===//
00842 
00843 void MachineConstantPoolValue::anchor() { }
00844 
00845 const DataLayout *MachineConstantPool::getDataLayout() const {
00846   return TM.getDataLayout();
00847 }
00848 
00849 Type *MachineConstantPoolEntry::getType() const {
00850   if (isMachineConstantPoolEntry())
00851     return Val.MachineCPVal->getType();
00852   return Val.ConstVal->getType();
00853 }
00854 
00855 
00856 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
00857   if (isMachineConstantPoolEntry())
00858     return Val.MachineCPVal->getRelocationInfo();
00859   return Val.ConstVal->getRelocationInfo();
00860 }
00861 
00862 SectionKind
00863 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
00864   SectionKind Kind;
00865   switch (getRelocationInfo()) {
00866   default:
00867     llvm_unreachable("Unknown section kind");
00868   case Constant::GlobalRelocations:
00869     Kind = SectionKind::getReadOnlyWithRel();
00870     break;
00871   case Constant::LocalRelocation:
00872     Kind = SectionKind::getReadOnlyWithRelLocal();
00873     break;
00874   case Constant::NoRelocation:
00875     switch (DL->getTypeAllocSize(getType())) {
00876     case 4:
00877       Kind = SectionKind::getMergeableConst4();
00878       break;
00879     case 8:
00880       Kind = SectionKind::getMergeableConst8();
00881       break;
00882     case 16:
00883       Kind = SectionKind::getMergeableConst16();
00884       break;
00885     default:
00886       Kind = SectionKind::getReadOnly();
00887       break;
00888     }
00889   }
00890   return Kind;
00891 }
00892 
00893 MachineConstantPool::~MachineConstantPool() {
00894   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00895     if (Constants[i].isMachineConstantPoolEntry())
00896       delete Constants[i].Val.MachineCPVal;
00897   for (DenseSet<MachineConstantPoolValue*>::iterator I =
00898        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
00899        I != E; ++I)
00900     delete *I;
00901 }
00902 
00903 /// CanShareConstantPoolEntry - Test whether the given two constants
00904 /// can be allocated the same constant pool entry.
00905 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
00906                                       const DataLayout *TD) {
00907   // Handle the trivial case quickly.
00908   if (A == B) return true;
00909 
00910   // If they have the same type but weren't the same constant, quickly
00911   // reject them.
00912   if (A->getType() == B->getType()) return false;
00913 
00914   // We can't handle structs or arrays.
00915   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
00916       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
00917     return false;
00918 
00919   // For now, only support constants with the same size.
00920   uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
00921   if (StoreSize != TD->getTypeStoreSize(B->getType()) || StoreSize > 128)
00922     return false;
00923 
00924   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
00925 
00926   // Try constant folding a bitcast of both instructions to an integer.  If we
00927   // get two identical ConstantInt's, then we are good to share them.  We use
00928   // the constant folding APIs to do this so that we get the benefit of
00929   // DataLayout.
00930   if (isa<PointerType>(A->getType()))
00931     A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
00932                                  const_cast<Constant *>(A), *TD);
00933   else if (A->getType() != IntTy)
00934     A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
00935                                  const_cast<Constant *>(A), *TD);
00936   if (isa<PointerType>(B->getType()))
00937     B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
00938                                  const_cast<Constant *>(B), *TD);
00939   else if (B->getType() != IntTy)
00940     B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
00941                                  const_cast<Constant *>(B), *TD);
00942 
00943   return A == B;
00944 }
00945 
00946 /// getConstantPoolIndex - Create a new entry in the constant pool or return
00947 /// an existing one.  User must specify the log2 of the minimum required
00948 /// alignment for the object.
00949 ///
00950 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
00951                                                    unsigned Alignment) {
00952   assert(Alignment && "Alignment must be specified!");
00953   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00954 
00955   // Check to see if we already have this constant.
00956   //
00957   // FIXME, this could be made much more efficient for large constant pools.
00958   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00959     if (!Constants[i].isMachineConstantPoolEntry() &&
00960         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
00961                                   getDataLayout())) {
00962       if ((unsigned)Constants[i].getAlignment() < Alignment)
00963         Constants[i].Alignment = Alignment;
00964       return i;
00965     }
00966 
00967   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
00968   return Constants.size()-1;
00969 }
00970 
00971 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
00972                                                    unsigned Alignment) {
00973   assert(Alignment && "Alignment must be specified!");
00974   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00975 
00976   // Check to see if we already have this constant.
00977   //
00978   // FIXME, this could be made much more efficient for large constant pools.
00979   int Idx = V->getExistingMachineCPValue(this, Alignment);
00980   if (Idx != -1) {
00981     MachineCPVsSharingEntries.insert(V);
00982     return (unsigned)Idx;
00983   }
00984 
00985   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
00986   return Constants.size()-1;
00987 }
00988 
00989 void MachineConstantPool::print(raw_ostream &OS) const {
00990   if (Constants.empty()) return;
00991 
00992   OS << "Constant Pool:\n";
00993   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
00994     OS << "  cp#" << i << ": ";
00995     if (Constants[i].isMachineConstantPoolEntry())
00996       Constants[i].Val.MachineCPVal->print(OS);
00997     else
00998       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
00999     OS << ", align=" << Constants[i].getAlignment();
01000     OS << "\n";
01001   }
01002 }
01003 
01004 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01005 void MachineConstantPool::dump() const { print(dbgs()); }
01006 #endif