xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision 97ed706a962af7c6835c7b6716207c4072011ac1)
1 //===- MachineFunction.cpp ------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Collect native machine code information for a function.  This allows
10 // target-specific information about the generated code to be stored with each
11 // function.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/EHPersonalities.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/TargetFrameLowering.h"
36 #include "llvm/CodeGen/TargetLowering.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/CodeGen/WasmEHFuncInfo.h"
40 #include "llvm/CodeGen/WinEHFuncInfo.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/IR/Attributes.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSlotTracker.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/MC/SectionKind.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/DOTGraphTraits.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/GraphWriter.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <iterator>
73 #include <string>
74 #include <utility>
75 #include <vector>
76 
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "codegen"
80 
81 static cl::opt<unsigned> AlignAllFunctions(
82     "align-all-functions",
83     cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
84              "means align on 16B boundaries)."),
85     cl::init(0), cl::Hidden);
86 
87 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
88   using P = MachineFunctionProperties::Property;
89 
90   switch(Prop) {
91   case P::FailedISel: return "FailedISel";
92   case P::IsSSA: return "IsSSA";
93   case P::Legalized: return "Legalized";
94   case P::NoPHIs: return "NoPHIs";
95   case P::NoVRegs: return "NoVRegs";
96   case P::RegBankSelected: return "RegBankSelected";
97   case P::Selected: return "Selected";
98   case P::TracksLiveness: return "TracksLiveness";
99   }
100   llvm_unreachable("Invalid machine function property");
101 }
102 
103 // Pin the vtable to this file.
104 void MachineFunction::Delegate::anchor() {}
105 
106 void MachineFunctionProperties::print(raw_ostream &OS) const {
107   const char *Separator = "";
108   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
109     if (!Properties[I])
110       continue;
111     OS << Separator << getPropertyName(static_cast<Property>(I));
112     Separator = ", ";
113   }
114 }
115 
116 //===----------------------------------------------------------------------===//
117 // MachineFunction implementation
118 //===----------------------------------------------------------------------===//
119 
120 // Out-of-line virtual method.
121 MachineFunctionInfo::~MachineFunctionInfo() = default;
122 
123 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
124   MBB->getParent()->DeleteMachineBasicBlock(MBB);
125 }
126 
127 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
128                                            const Function &F) {
129   if (F.hasFnAttribute(Attribute::StackAlignment))
130     return F.getFnStackAlignment();
131   return STI->getFrameLowering()->getStackAlignment();
132 }
133 
134 MachineFunction::MachineFunction(const Function &F,
135                                  const LLVMTargetMachine &Target,
136                                  const TargetSubtargetInfo &STI,
137                                  unsigned FunctionNum, MachineModuleInfo &mmi)
138     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
139   FunctionNumber = FunctionNum;
140   init();
141 }
142 
143 void MachineFunction::handleInsertion(MachineInstr &MI) {
144   if (TheDelegate)
145     TheDelegate->MF_HandleInsertion(MI);
146 }
147 
148 void MachineFunction::handleRemoval(MachineInstr &MI) {
149   if (TheDelegate)
150     TheDelegate->MF_HandleRemoval(MI);
151 }
152 
153 void MachineFunction::init() {
154   // Assume the function starts in SSA form with correct liveness.
155   Properties.set(MachineFunctionProperties::Property::IsSSA);
156   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
157   if (STI->getRegisterInfo())
158     RegInfo = new (Allocator) MachineRegisterInfo(this);
159   else
160     RegInfo = nullptr;
161 
162   MFInfo = nullptr;
163   // We can realign the stack if the target supports it and the user hasn't
164   // explicitly asked us not to.
165   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
166                       !F.hasFnAttribute("no-realign-stack");
167   FrameInfo = new (Allocator) MachineFrameInfo(
168       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
169       /*ForcedRealign=*/CanRealignSP &&
170           F.hasFnAttribute(Attribute::StackAlignment));
171 
172   if (F.hasFnAttribute(Attribute::StackAlignment))
173     FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
174 
175   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
176   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
177 
178   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
179   // FIXME: Use Function::hasOptSize().
180   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
181     Alignment = std::max(Alignment,
182                          STI->getTargetLowering()->getPrefFunctionAlignment());
183 
184   if (AlignAllFunctions)
185     Alignment = Align(1ULL << AlignAllFunctions);
186 
187   JumpTableInfo = nullptr;
188 
189   if (isFuncletEHPersonality(classifyEHPersonality(
190           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
191     WinEHInfo = new (Allocator) WinEHFuncInfo();
192   }
193 
194   if (isScopedEHPersonality(classifyEHPersonality(
195           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
196     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
197   }
198 
199   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
200          "Can't create a MachineFunction using a Module with a "
201          "Target-incompatible DataLayout attached\n");
202 
203   PSVManager =
204     std::make_unique<PseudoSourceValueManager>(*(getSubtarget().
205                                                   getInstrInfo()));
206 }
207 
208 MachineFunction::~MachineFunction() {
209   clear();
210 }
211 
212 void MachineFunction::clear() {
213   Properties.reset();
214   // Don't call destructors on MachineInstr and MachineOperand. All of their
215   // memory comes from the BumpPtrAllocator which is about to be purged.
216   //
217   // Do call MachineBasicBlock destructors, it contains std::vectors.
218   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
219     I->Insts.clearAndLeakNodesUnsafely();
220   MBBNumbering.clear();
221 
222   InstructionRecycler.clear(Allocator);
223   OperandRecycler.clear(Allocator);
224   BasicBlockRecycler.clear(Allocator);
225   CodeViewAnnotations.clear();
226   VariableDbgInfos.clear();
227   if (RegInfo) {
228     RegInfo->~MachineRegisterInfo();
229     Allocator.Deallocate(RegInfo);
230   }
231   if (MFInfo) {
232     MFInfo->~MachineFunctionInfo();
233     Allocator.Deallocate(MFInfo);
234   }
235 
236   FrameInfo->~MachineFrameInfo();
237   Allocator.Deallocate(FrameInfo);
238 
239   ConstantPool->~MachineConstantPool();
240   Allocator.Deallocate(ConstantPool);
241 
242   if (JumpTableInfo) {
243     JumpTableInfo->~MachineJumpTableInfo();
244     Allocator.Deallocate(JumpTableInfo);
245   }
246 
247   if (WinEHInfo) {
248     WinEHInfo->~WinEHFuncInfo();
249     Allocator.Deallocate(WinEHInfo);
250   }
251 
252   if (WasmEHInfo) {
253     WasmEHInfo->~WasmEHFuncInfo();
254     Allocator.Deallocate(WasmEHInfo);
255   }
256 }
257 
258 const DataLayout &MachineFunction::getDataLayout() const {
259   return F.getParent()->getDataLayout();
260 }
261 
262 /// Get the JumpTableInfo for this function.
263 /// If it does not already exist, allocate one.
264 MachineJumpTableInfo *MachineFunction::
265 getOrCreateJumpTableInfo(unsigned EntryKind) {
266   if (JumpTableInfo) return JumpTableInfo;
267 
268   JumpTableInfo = new (Allocator)
269     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
270   return JumpTableInfo;
271 }
272 
273 DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
274   if (&FPType == &APFloat::IEEEsingle()) {
275     Attribute Attr = F.getFnAttribute("denormal-fp-math-f32");
276     StringRef Val = Attr.getValueAsString();
277     if (!Val.empty())
278       return parseDenormalFPAttribute(Val);
279 
280     // If the f32 variant of the attribute isn't specified, try to use the
281     // generic one.
282   }
283 
284   // TODO: Should probably avoid the connection to the IR and store directly
285   // in the MachineFunction.
286   Attribute Attr = F.getFnAttribute("denormal-fp-math");
287 
288   // FIXME: This should assume IEEE behavior on an unspecified
289   // attribute. However, the one current user incorrectly assumes a non-IEEE
290   // target by default.
291   StringRef Val = Attr.getValueAsString();
292   if (Val.empty())
293     return DenormalMode::getInvalid();
294 
295   return parseDenormalFPAttribute(Val);
296 }
297 
298 /// Should we be emitting segmented stack stuff for the function
299 bool MachineFunction::shouldSplitStack() const {
300   return getFunction().hasFnAttribute("split-stack");
301 }
302 
303 LLVM_NODISCARD unsigned
304 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
305   FrameInstructions.push_back(Inst);
306   return FrameInstructions.size() - 1;
307 }
308 
309 /// This discards all of the MachineBasicBlock numbers and recomputes them.
310 /// This guarantees that the MBB numbers are sequential, dense, and match the
311 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
312 /// is specified, only that block and those after it are renumbered.
313 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
314   if (empty()) { MBBNumbering.clear(); return; }
315   MachineFunction::iterator MBBI, E = end();
316   if (MBB == nullptr)
317     MBBI = begin();
318   else
319     MBBI = MBB->getIterator();
320 
321   // Figure out the block number this should have.
322   unsigned BlockNo = 0;
323   if (MBBI != begin())
324     BlockNo = std::prev(MBBI)->getNumber() + 1;
325 
326   for (; MBBI != E; ++MBBI, ++BlockNo) {
327     if (MBBI->getNumber() != (int)BlockNo) {
328       // Remove use of the old number.
329       if (MBBI->getNumber() != -1) {
330         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
331                "MBB number mismatch!");
332         MBBNumbering[MBBI->getNumber()] = nullptr;
333       }
334 
335       // If BlockNo is already taken, set that block's number to -1.
336       if (MBBNumbering[BlockNo])
337         MBBNumbering[BlockNo]->setNumber(-1);
338 
339       MBBNumbering[BlockNo] = &*MBBI;
340       MBBI->setNumber(BlockNo);
341     }
342   }
343 
344   // Okay, all the blocks are renumbered.  If we have compactified the block
345   // numbering, shrink MBBNumbering now.
346   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
347   MBBNumbering.resize(BlockNo);
348 }
349 
350 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
351 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
352                                                   const DebugLoc &DL,
353                                                   bool NoImp) {
354   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
355     MachineInstr(*this, MCID, DL, NoImp);
356 }
357 
358 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
359 /// identical in all ways except the instruction has no parent, prev, or next.
360 MachineInstr *
361 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
362   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
363              MachineInstr(*this, *Orig);
364 }
365 
366 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
367     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
368   MachineInstr *FirstClone = nullptr;
369   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
370   while (true) {
371     MachineInstr *Cloned = CloneMachineInstr(&*I);
372     MBB.insert(InsertBefore, Cloned);
373     if (FirstClone == nullptr) {
374       FirstClone = Cloned;
375     } else {
376       Cloned->bundleWithPred();
377     }
378 
379     if (!I->isBundledWithSucc())
380       break;
381     ++I;
382   }
383   return *FirstClone;
384 }
385 
386 /// Delete the given MachineInstr.
387 ///
388 /// This function also serves as the MachineInstr destructor - the real
389 /// ~MachineInstr() destructor must be empty.
390 void
391 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
392   // Verify that a call site info is at valid state. This assertion should
393   // be triggered during the implementation of support for the
394   // call site info of a new architecture. If the assertion is triggered,
395   // back trace will tell where to insert a call to updateCallSiteInfo().
396   assert((!MI->isCall(MachineInstr::IgnoreBundle) ||
397           CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
398          "Call site info was not updated!");
399   // Strip it for parts. The operand array and the MI object itself are
400   // independently recyclable.
401   if (MI->Operands)
402     deallocateOperandArray(MI->CapOperands, MI->Operands);
403   // Don't call ~MachineInstr() which must be trivial anyway because
404   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
405   // destructors.
406   InstructionRecycler.Deallocate(Allocator, MI);
407 }
408 
409 /// Allocate a new MachineBasicBlock. Use this instead of
410 /// `new MachineBasicBlock'.
411 MachineBasicBlock *
412 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
413   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
414              MachineBasicBlock(*this, bb);
415 }
416 
417 /// Delete the given MachineBasicBlock.
418 void
419 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
420   assert(MBB->getParent() == this && "MBB parent mismatch!");
421   MBB->~MachineBasicBlock();
422   BasicBlockRecycler.Deallocate(Allocator, MBB);
423 }
424 
425 MachineMemOperand *MachineFunction::getMachineMemOperand(
426     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
427     unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
428     SyncScope::ID SSID, AtomicOrdering Ordering,
429     AtomicOrdering FailureOrdering) {
430   return new (Allocator)
431       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
432                         SSID, Ordering, FailureOrdering);
433 }
434 
435 MachineMemOperand *
436 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
437                                       int64_t Offset, uint64_t Size) {
438   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
439 
440   // If there is no pointer value, the offset isn't tracked so we need to adjust
441   // the base alignment.
442   unsigned Align = PtrInfo.V.isNull()
443                        ? MinAlign(MMO->getBaseAlignment(), Offset)
444                        : MMO->getBaseAlignment();
445 
446   return new (Allocator)
447       MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
448                         Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
449                         MMO->getOrdering(), MMO->getFailureOrdering());
450 }
451 
452 MachineMemOperand *
453 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
454                                       const AAMDNodes &AAInfo) {
455   MachinePointerInfo MPI = MMO->getValue() ?
456              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
457              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
458 
459   return new (Allocator)
460              MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
461                                MMO->getBaseAlignment(), AAInfo,
462                                MMO->getRanges(), MMO->getSyncScopeID(),
463                                MMO->getOrdering(), MMO->getFailureOrdering());
464 }
465 
466 MachineMemOperand *
467 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
468                                       MachineMemOperand::Flags Flags) {
469   return new (Allocator) MachineMemOperand(
470       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlignment(),
471       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
472       MMO->getOrdering(), MMO->getFailureOrdering());
473 }
474 
475 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
476     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
477     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
478   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
479                                          PostInstrSymbol, HeapAllocMarker);
480 }
481 
482 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
483   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
484   llvm::copy(Name, Dest);
485   Dest[Name.size()] = 0;
486   return Dest;
487 }
488 
489 uint32_t *MachineFunction::allocateRegMask() {
490   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
491   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
492   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
493   memset(Mask, 0, Size * sizeof(Mask[0]));
494   return Mask;
495 }
496 
497 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
498   int* AllocMask = Allocator.Allocate<int>(Mask.size());
499   copy(Mask, AllocMask);
500   return {AllocMask, Mask.size()};
501 }
502 
503 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
504 LLVM_DUMP_METHOD void MachineFunction::dump() const {
505   print(dbgs());
506 }
507 #endif
508 
509 StringRef MachineFunction::getName() const {
510   return getFunction().getName();
511 }
512 
513 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
514   OS << "# Machine code for function " << getName() << ": ";
515   getProperties().print(OS);
516   OS << '\n';
517 
518   // Print Frame Information
519   FrameInfo->print(*this, OS);
520 
521   // Print JumpTable Information
522   if (JumpTableInfo)
523     JumpTableInfo->print(OS);
524 
525   // Print Constant Pool
526   ConstantPool->print(OS);
527 
528   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
529 
530   if (RegInfo && !RegInfo->livein_empty()) {
531     OS << "Function Live Ins: ";
532     for (MachineRegisterInfo::livein_iterator
533          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
534       OS << printReg(I->first, TRI);
535       if (I->second)
536         OS << " in " << printReg(I->second, TRI);
537       if (std::next(I) != E)
538         OS << ", ";
539     }
540     OS << '\n';
541   }
542 
543   ModuleSlotTracker MST(getFunction().getParent());
544   MST.incorporateFunction(getFunction());
545   for (const auto &BB : *this) {
546     OS << '\n';
547     // If we print the whole function, print it at its most verbose level.
548     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
549   }
550 
551   OS << "\n# End machine code for function " << getName() << ".\n\n";
552 }
553 
554 /// True if this function needs frame moves for debug or exceptions.
555 bool MachineFunction::needsFrameMoves() const {
556   return getMMI().hasDebugInfo() ||
557          getTarget().Options.ForceDwarfFrameSection ||
558          F.needsUnwindTableEntry();
559 }
560 
561 namespace llvm {
562 
563   template<>
564   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
565     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
566 
567     static std::string getGraphName(const MachineFunction *F) {
568       return ("CFG for '" + F->getName() + "' function").str();
569     }
570 
571     std::string getNodeLabel(const MachineBasicBlock *Node,
572                              const MachineFunction *Graph) {
573       std::string OutStr;
574       {
575         raw_string_ostream OSS(OutStr);
576 
577         if (isSimple()) {
578           OSS << printMBBReference(*Node);
579           if (const BasicBlock *BB = Node->getBasicBlock())
580             OSS << ": " << BB->getName();
581         } else
582           Node->print(OSS);
583       }
584 
585       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
586 
587       // Process string output to make it nicer...
588       for (unsigned i = 0; i != OutStr.length(); ++i)
589         if (OutStr[i] == '\n') {                            // Left justify
590           OutStr[i] = '\\';
591           OutStr.insert(OutStr.begin()+i+1, 'l');
592         }
593       return OutStr;
594     }
595   };
596 
597 } // end namespace llvm
598 
599 void MachineFunction::viewCFG() const
600 {
601 #ifndef NDEBUG
602   ViewGraph(this, "mf" + getName());
603 #else
604   errs() << "MachineFunction::viewCFG is only available in debug builds on "
605          << "systems with Graphviz or gv!\n";
606 #endif // NDEBUG
607 }
608 
609 void MachineFunction::viewCFGOnly() const
610 {
611 #ifndef NDEBUG
612   ViewGraph(this, "mf" + getName(), true);
613 #else
614   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
615          << "systems with Graphviz or gv!\n";
616 #endif // NDEBUG
617 }
618 
619 /// Add the specified physical register as a live-in value and
620 /// create a corresponding virtual register for it.
621 unsigned MachineFunction::addLiveIn(unsigned PReg,
622                                     const TargetRegisterClass *RC) {
623   MachineRegisterInfo &MRI = getRegInfo();
624   unsigned VReg = MRI.getLiveInVirtReg(PReg);
625   if (VReg) {
626     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
627     (void)VRegRC;
628     // A physical register can be added several times.
629     // Between two calls, the register class of the related virtual register
630     // may have been constrained to match some operation constraints.
631     // In that case, check that the current register class includes the
632     // physical register and is a sub class of the specified RC.
633     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
634                              RC->hasSubClassEq(VRegRC))) &&
635             "Register class mismatch!");
636     return VReg;
637   }
638   VReg = MRI.createVirtualRegister(RC);
639   MRI.addLiveIn(PReg, VReg);
640   return VReg;
641 }
642 
643 /// Return the MCSymbol for the specified non-empty jump table.
644 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
645 /// normal 'L' label is returned.
646 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
647                                         bool isLinkerPrivate) const {
648   const DataLayout &DL = getDataLayout();
649   assert(JumpTableInfo && "No jump tables");
650   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
651 
652   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
653                                      : DL.getPrivateGlobalPrefix();
654   SmallString<60> Name;
655   raw_svector_ostream(Name)
656     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
657   return Ctx.getOrCreateSymbol(Name);
658 }
659 
660 /// Return a function-local symbol to represent the PIC base.
661 MCSymbol *MachineFunction::getPICBaseSymbol() const {
662   const DataLayout &DL = getDataLayout();
663   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
664                                Twine(getFunctionNumber()) + "$pb");
665 }
666 
667 /// \name Exception Handling
668 /// \{
669 
670 LandingPadInfo &
671 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
672   unsigned N = LandingPads.size();
673   for (unsigned i = 0; i < N; ++i) {
674     LandingPadInfo &LP = LandingPads[i];
675     if (LP.LandingPadBlock == LandingPad)
676       return LP;
677   }
678 
679   LandingPads.push_back(LandingPadInfo(LandingPad));
680   return LandingPads[N];
681 }
682 
683 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
684                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
685   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
686   LP.BeginLabels.push_back(BeginLabel);
687   LP.EndLabels.push_back(EndLabel);
688 }
689 
690 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
691   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
692   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
693   LP.LandingPadLabel = LandingPadLabel;
694 
695   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
696   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
697     if (const auto *PF =
698             dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
699       getMMI().addPersonality(PF);
700 
701     if (LPI->isCleanup())
702       addCleanup(LandingPad);
703 
704     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
705     //        correct, but we need to do it this way because of how the DWARF EH
706     //        emitter processes the clauses.
707     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
708       Value *Val = LPI->getClause(I - 1);
709       if (LPI->isCatch(I - 1)) {
710         addCatchTypeInfo(LandingPad,
711                          dyn_cast<GlobalValue>(Val->stripPointerCasts()));
712       } else {
713         // Add filters in a list.
714         auto *CVal = cast<Constant>(Val);
715         SmallVector<const GlobalValue *, 4> FilterList;
716         for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
717              II != IE; ++II)
718           FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
719 
720         addFilterTypeInfo(LandingPad, FilterList);
721       }
722     }
723 
724   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
725     for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
726       Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
727       addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
728     }
729 
730   } else {
731     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
732   }
733 
734   return LandingPadLabel;
735 }
736 
737 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
738                                        ArrayRef<const GlobalValue *> TyInfo) {
739   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
740   for (unsigned N = TyInfo.size(); N; --N)
741     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
742 }
743 
744 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
745                                         ArrayRef<const GlobalValue *> TyInfo) {
746   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
747   std::vector<unsigned> IdsInFilter(TyInfo.size());
748   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
749     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
750   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
751 }
752 
753 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
754                                       bool TidyIfNoBeginLabels) {
755   for (unsigned i = 0; i != LandingPads.size(); ) {
756     LandingPadInfo &LandingPad = LandingPads[i];
757     if (LandingPad.LandingPadLabel &&
758         !LandingPad.LandingPadLabel->isDefined() &&
759         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
760       LandingPad.LandingPadLabel = nullptr;
761 
762     // Special case: we *should* emit LPs with null LP MBB. This indicates
763     // "nounwind" case.
764     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
765       LandingPads.erase(LandingPads.begin() + i);
766       continue;
767     }
768 
769     if (TidyIfNoBeginLabels) {
770       for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
771         MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
772         MCSymbol *EndLabel = LandingPad.EndLabels[j];
773         if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
774             (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
775           continue;
776 
777         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
778         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
779         --j;
780         --e;
781       }
782 
783       // Remove landing pads with no try-ranges.
784       if (LandingPads[i].BeginLabels.empty()) {
785         LandingPads.erase(LandingPads.begin() + i);
786         continue;
787       }
788     }
789 
790     // If there is no landing pad, ensure that the list of typeids is empty.
791     // If the only typeid is a cleanup, this is the same as having no typeids.
792     if (!LandingPad.LandingPadBlock ||
793         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
794       LandingPad.TypeIds.clear();
795     ++i;
796   }
797 }
798 
799 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
800   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
801   LP.TypeIds.push_back(0);
802 }
803 
804 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
805                                          const Function *Filter,
806                                          const BlockAddress *RecoverBA) {
807   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
808   SEHHandler Handler;
809   Handler.FilterOrFinally = Filter;
810   Handler.RecoverBA = RecoverBA;
811   LP.SEHHandlers.push_back(Handler);
812 }
813 
814 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
815                                            const Function *Cleanup) {
816   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
817   SEHHandler Handler;
818   Handler.FilterOrFinally = Cleanup;
819   Handler.RecoverBA = nullptr;
820   LP.SEHHandlers.push_back(Handler);
821 }
822 
823 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
824                                             ArrayRef<unsigned> Sites) {
825   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
826 }
827 
828 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
829   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
830     if (TypeInfos[i] == TI) return i + 1;
831 
832   TypeInfos.push_back(TI);
833   return TypeInfos.size();
834 }
835 
836 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
837   // If the new filter coincides with the tail of an existing filter, then
838   // re-use the existing filter.  Folding filters more than this requires
839   // re-ordering filters and/or their elements - probably not worth it.
840   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
841        E = FilterEnds.end(); I != E; ++I) {
842     unsigned i = *I, j = TyIds.size();
843 
844     while (i && j)
845       if (FilterIds[--i] != TyIds[--j])
846         goto try_next;
847 
848     if (!j)
849       // The new filter coincides with range [i, end) of the existing filter.
850       return -(1 + i);
851 
852 try_next:;
853   }
854 
855   // Add the new filter.
856   int FilterID = -(1 + FilterIds.size());
857   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
858   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
859   FilterEnds.push_back(FilterIds.size());
860   FilterIds.push_back(0); // terminator
861   return FilterID;
862 }
863 
864 MachineFunction::CallSiteInfoMap::iterator
865 MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
866   assert(MI->isCandidateForCallSiteEntry() &&
867          "Call site info refers only to call (MI) candidates");
868 
869   if (!Target.Options.EnableDebugEntryValues)
870     return CallSitesInfo.end();
871   return CallSitesInfo.find(MI);
872 }
873 
874 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
875                                        const MachineInstr *New) {
876   assert(Old->isCandidateForCallSiteEntry() &&
877          "Call site info refers only to call (MI) candidates");
878 
879   if (!New->isCandidateForCallSiteEntry())
880     return eraseCallSiteInfo(Old);
881 
882   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(Old);
883   if (CSIt == CallSitesInfo.end())
884     return;
885 
886   CallSiteInfo CSInfo = std::move(CSIt->second);
887   CallSitesInfo.erase(CSIt);
888   CallSitesInfo[New] = CSInfo;
889 }
890 
891 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
892   assert(MI->isCandidateForCallSiteEntry() &&
893          "Call site info refers only to call (MI) candidates");
894   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(MI);
895   if (CSIt == CallSitesInfo.end())
896     return;
897   CallSitesInfo.erase(CSIt);
898 }
899 
900 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
901                                        const MachineInstr *New) {
902   assert(Old->isCandidateForCallSiteEntry() &&
903          "Call site info refers only to call (MI) candidates");
904 
905   if (!New->isCandidateForCallSiteEntry())
906     return eraseCallSiteInfo(Old);
907 
908   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(Old);
909   if (CSIt == CallSitesInfo.end())
910     return;
911 
912   CallSiteInfo CSInfo = CSIt->second;
913   CallSitesInfo[New] = CSInfo;
914 }
915 
916 /// \}
917 
918 //===----------------------------------------------------------------------===//
919 //  MachineJumpTableInfo implementation
920 //===----------------------------------------------------------------------===//
921 
922 /// Return the size of each entry in the jump table.
923 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
924   // The size of a jump table entry is 4 bytes unless the entry is just the
925   // address of a block, in which case it is the pointer size.
926   switch (getEntryKind()) {
927   case MachineJumpTableInfo::EK_BlockAddress:
928     return TD.getPointerSize();
929   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
930     return 8;
931   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
932   case MachineJumpTableInfo::EK_LabelDifference32:
933   case MachineJumpTableInfo::EK_Custom32:
934     return 4;
935   case MachineJumpTableInfo::EK_Inline:
936     return 0;
937   }
938   llvm_unreachable("Unknown jump table encoding!");
939 }
940 
941 /// Return the alignment of each entry in the jump table.
942 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
943   // The alignment of a jump table entry is the alignment of int32 unless the
944   // entry is just the address of a block, in which case it is the pointer
945   // alignment.
946   switch (getEntryKind()) {
947   case MachineJumpTableInfo::EK_BlockAddress:
948     return TD.getPointerABIAlignment(0).value();
949   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
950     return TD.getABIIntegerTypeAlignment(64).value();
951   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
952   case MachineJumpTableInfo::EK_LabelDifference32:
953   case MachineJumpTableInfo::EK_Custom32:
954     return TD.getABIIntegerTypeAlignment(32).value();
955   case MachineJumpTableInfo::EK_Inline:
956     return 1;
957   }
958   llvm_unreachable("Unknown jump table encoding!");
959 }
960 
961 /// Create a new jump table entry in the jump table info.
962 unsigned MachineJumpTableInfo::createJumpTableIndex(
963                                const std::vector<MachineBasicBlock*> &DestBBs) {
964   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
965   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
966   return JumpTables.size()-1;
967 }
968 
969 /// If Old is the target of any jump tables, update the jump tables to branch
970 /// to New instead.
971 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
972                                                   MachineBasicBlock *New) {
973   assert(Old != New && "Not making a change?");
974   bool MadeChange = false;
975   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
976     ReplaceMBBInJumpTable(i, Old, New);
977   return MadeChange;
978 }
979 
980 /// If Old is a target of the jump tables, update the jump table to branch to
981 /// New instead.
982 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
983                                                  MachineBasicBlock *Old,
984                                                  MachineBasicBlock *New) {
985   assert(Old != New && "Not making a change?");
986   bool MadeChange = false;
987   MachineJumpTableEntry &JTE = JumpTables[Idx];
988   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
989     if (JTE.MBBs[j] == Old) {
990       JTE.MBBs[j] = New;
991       MadeChange = true;
992     }
993   return MadeChange;
994 }
995 
996 void MachineJumpTableInfo::print(raw_ostream &OS) const {
997   if (JumpTables.empty()) return;
998 
999   OS << "Jump Tables:\n";
1000 
1001   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1002     OS << printJumpTableEntryReference(i) << ':';
1003     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
1004       OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
1005     if (i != e)
1006       OS << '\n';
1007   }
1008 
1009   OS << '\n';
1010 }
1011 
1012 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1013 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1014 #endif
1015 
1016 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1017   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1018 }
1019 
1020 //===----------------------------------------------------------------------===//
1021 //  MachineConstantPool implementation
1022 //===----------------------------------------------------------------------===//
1023 
1024 void MachineConstantPoolValue::anchor() {}
1025 
1026 Type *MachineConstantPoolEntry::getType() const {
1027   if (isMachineConstantPoolEntry())
1028     return Val.MachineCPVal->getType();
1029   return Val.ConstVal->getType();
1030 }
1031 
1032 bool MachineConstantPoolEntry::needsRelocation() const {
1033   if (isMachineConstantPoolEntry())
1034     return true;
1035   return Val.ConstVal->needsRelocation();
1036 }
1037 
1038 SectionKind
1039 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1040   if (needsRelocation())
1041     return SectionKind::getReadOnlyWithRel();
1042   switch (DL->getTypeAllocSize(getType())) {
1043   case 4:
1044     return SectionKind::getMergeableConst4();
1045   case 8:
1046     return SectionKind::getMergeableConst8();
1047   case 16:
1048     return SectionKind::getMergeableConst16();
1049   case 32:
1050     return SectionKind::getMergeableConst32();
1051   default:
1052     return SectionKind::getReadOnly();
1053   }
1054 }
1055 
1056 MachineConstantPool::~MachineConstantPool() {
1057   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1058   // so keep track of which we've deleted to avoid double deletions.
1059   DenseSet<MachineConstantPoolValue*> Deleted;
1060   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1061     if (Constants[i].isMachineConstantPoolEntry()) {
1062       Deleted.insert(Constants[i].Val.MachineCPVal);
1063       delete Constants[i].Val.MachineCPVal;
1064     }
1065   for (DenseSet<MachineConstantPoolValue*>::iterator I =
1066        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
1067        I != E; ++I) {
1068     if (Deleted.count(*I) == 0)
1069       delete *I;
1070   }
1071 }
1072 
1073 /// Test whether the given two constants can be allocated the same constant pool
1074 /// entry.
1075 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1076                                       const DataLayout &DL) {
1077   // Handle the trivial case quickly.
1078   if (A == B) return true;
1079 
1080   // If they have the same type but weren't the same constant, quickly
1081   // reject them.
1082   if (A->getType() == B->getType()) return false;
1083 
1084   // We can't handle structs or arrays.
1085   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1086       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1087     return false;
1088 
1089   // For now, only support constants with the same size.
1090   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1091   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1092     return false;
1093 
1094   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1095 
1096   // Try constant folding a bitcast of both instructions to an integer.  If we
1097   // get two identical ConstantInt's, then we are good to share them.  We use
1098   // the constant folding APIs to do this so that we get the benefit of
1099   // DataLayout.
1100   if (isa<PointerType>(A->getType()))
1101     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1102                                 const_cast<Constant *>(A), IntTy, DL);
1103   else if (A->getType() != IntTy)
1104     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1105                                 IntTy, DL);
1106   if (isa<PointerType>(B->getType()))
1107     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1108                                 const_cast<Constant *>(B), IntTy, DL);
1109   else if (B->getType() != IntTy)
1110     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1111                                 IntTy, DL);
1112 
1113   return A == B;
1114 }
1115 
1116 /// Create a new entry in the constant pool or return an existing one.
1117 /// User must specify the log2 of the minimum required alignment for the object.
1118 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1119                                                    unsigned Alignment) {
1120   assert(Alignment && "Alignment must be specified!");
1121   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1122 
1123   // Check to see if we already have this constant.
1124   //
1125   // FIXME, this could be made much more efficient for large constant pools.
1126   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1127     if (!Constants[i].isMachineConstantPoolEntry() &&
1128         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1129       if ((unsigned)Constants[i].getAlignment() < Alignment)
1130         Constants[i].Alignment = Alignment;
1131       return i;
1132     }
1133 
1134   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1135   return Constants.size()-1;
1136 }
1137 
1138 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1139                                                    unsigned Alignment) {
1140   assert(Alignment && "Alignment must be specified!");
1141   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1142 
1143   // Check to see if we already have this constant.
1144   //
1145   // FIXME, this could be made much more efficient for large constant pools.
1146   int Idx = V->getExistingMachineCPValue(this, Alignment);
1147   if (Idx != -1) {
1148     MachineCPVsSharingEntries.insert(V);
1149     return (unsigned)Idx;
1150   }
1151 
1152   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1153   return Constants.size()-1;
1154 }
1155 
1156 void MachineConstantPool::print(raw_ostream &OS) const {
1157   if (Constants.empty()) return;
1158 
1159   OS << "Constant Pool:\n";
1160   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1161     OS << "  cp#" << i << ": ";
1162     if (Constants[i].isMachineConstantPoolEntry())
1163       Constants[i].Val.MachineCPVal->print(OS);
1164     else
1165       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1166     OS << ", align=" << Constants[i].getAlignment();
1167     OS << "\n";
1168   }
1169 }
1170 
1171 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1172 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1173 #endif
1174