xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision c15c68abdc6f1afece637bdedba808676191a8e6)
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   return parseDenormalFPAttribute(Attr.getValueAsString());
288 }
289 
290 /// Should we be emitting segmented stack stuff for the function
291 bool MachineFunction::shouldSplitStack() const {
292   return getFunction().hasFnAttribute("split-stack");
293 }
294 
295 LLVM_NODISCARD unsigned
296 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
297   FrameInstructions.push_back(Inst);
298   return FrameInstructions.size() - 1;
299 }
300 
301 /// This discards all of the MachineBasicBlock numbers and recomputes them.
302 /// This guarantees that the MBB numbers are sequential, dense, and match the
303 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
304 /// is specified, only that block and those after it are renumbered.
305 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
306   if (empty()) { MBBNumbering.clear(); return; }
307   MachineFunction::iterator MBBI, E = end();
308   if (MBB == nullptr)
309     MBBI = begin();
310   else
311     MBBI = MBB->getIterator();
312 
313   // Figure out the block number this should have.
314   unsigned BlockNo = 0;
315   if (MBBI != begin())
316     BlockNo = std::prev(MBBI)->getNumber() + 1;
317 
318   for (; MBBI != E; ++MBBI, ++BlockNo) {
319     if (MBBI->getNumber() != (int)BlockNo) {
320       // Remove use of the old number.
321       if (MBBI->getNumber() != -1) {
322         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
323                "MBB number mismatch!");
324         MBBNumbering[MBBI->getNumber()] = nullptr;
325       }
326 
327       // If BlockNo is already taken, set that block's number to -1.
328       if (MBBNumbering[BlockNo])
329         MBBNumbering[BlockNo]->setNumber(-1);
330 
331       MBBNumbering[BlockNo] = &*MBBI;
332       MBBI->setNumber(BlockNo);
333     }
334   }
335 
336   // Okay, all the blocks are renumbered.  If we have compactified the block
337   // numbering, shrink MBBNumbering now.
338   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
339   MBBNumbering.resize(BlockNo);
340 }
341 
342 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
343 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
344                                                   const DebugLoc &DL,
345                                                   bool NoImp) {
346   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
347     MachineInstr(*this, MCID, DL, NoImp);
348 }
349 
350 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
351 /// identical in all ways except the instruction has no parent, prev, or next.
352 MachineInstr *
353 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
354   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
355              MachineInstr(*this, *Orig);
356 }
357 
358 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
359     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
360   MachineInstr *FirstClone = nullptr;
361   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
362   while (true) {
363     MachineInstr *Cloned = CloneMachineInstr(&*I);
364     MBB.insert(InsertBefore, Cloned);
365     if (FirstClone == nullptr) {
366       FirstClone = Cloned;
367     } else {
368       Cloned->bundleWithPred();
369     }
370 
371     if (!I->isBundledWithSucc())
372       break;
373     ++I;
374   }
375   return *FirstClone;
376 }
377 
378 /// Delete the given MachineInstr.
379 ///
380 /// This function also serves as the MachineInstr destructor - the real
381 /// ~MachineInstr() destructor must be empty.
382 void
383 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
384   // Verify that a call site info is at valid state. This assertion should
385   // be triggered during the implementation of support for the
386   // call site info of a new architecture. If the assertion is triggered,
387   // back trace will tell where to insert a call to updateCallSiteInfo().
388   assert((!MI->isCandidateForCallSiteEntry() ||
389           CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
390          "Call site info was not updated!");
391   // Strip it for parts. The operand array and the MI object itself are
392   // independently recyclable.
393   if (MI->Operands)
394     deallocateOperandArray(MI->CapOperands, MI->Operands);
395   // Don't call ~MachineInstr() which must be trivial anyway because
396   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
397   // destructors.
398   InstructionRecycler.Deallocate(Allocator, MI);
399 }
400 
401 /// Allocate a new MachineBasicBlock. Use this instead of
402 /// `new MachineBasicBlock'.
403 MachineBasicBlock *
404 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
405   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
406              MachineBasicBlock(*this, bb);
407 }
408 
409 /// Delete the given MachineBasicBlock.
410 void
411 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
412   assert(MBB->getParent() == this && "MBB parent mismatch!");
413   MBB->~MachineBasicBlock();
414   BasicBlockRecycler.Deallocate(Allocator, MBB);
415 }
416 
417 MachineMemOperand *MachineFunction::getMachineMemOperand(
418     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
419     unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
420     SyncScope::ID SSID, AtomicOrdering Ordering,
421     AtomicOrdering FailureOrdering) {
422   return new (Allocator)
423       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
424                         SSID, Ordering, FailureOrdering);
425 }
426 
427 MachineMemOperand *
428 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
429                                       int64_t Offset, uint64_t Size) {
430   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
431 
432   // If there is no pointer value, the offset isn't tracked so we need to adjust
433   // the base alignment.
434   unsigned Align = PtrInfo.V.isNull()
435                        ? MinAlign(MMO->getBaseAlignment(), Offset)
436                        : MMO->getBaseAlignment();
437 
438   return new (Allocator)
439       MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
440                         Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
441                         MMO->getOrdering(), MMO->getFailureOrdering());
442 }
443 
444 MachineMemOperand *
445 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
446                                       const AAMDNodes &AAInfo) {
447   MachinePointerInfo MPI = MMO->getValue() ?
448              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
449              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
450 
451   return new (Allocator)
452              MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
453                                MMO->getBaseAlignment(), AAInfo,
454                                MMO->getRanges(), MMO->getSyncScopeID(),
455                                MMO->getOrdering(), MMO->getFailureOrdering());
456 }
457 
458 MachineMemOperand *
459 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
460                                       MachineMemOperand::Flags Flags) {
461   return new (Allocator) MachineMemOperand(
462       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlignment(),
463       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
464       MMO->getOrdering(), MMO->getFailureOrdering());
465 }
466 
467 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
468     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
469     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
470   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
471                                          PostInstrSymbol, HeapAllocMarker);
472 }
473 
474 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
475   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
476   llvm::copy(Name, Dest);
477   Dest[Name.size()] = 0;
478   return Dest;
479 }
480 
481 uint32_t *MachineFunction::allocateRegMask() {
482   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
483   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
484   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
485   memset(Mask, 0, Size * sizeof(Mask[0]));
486   return Mask;
487 }
488 
489 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
490   int* AllocMask = Allocator.Allocate<int>(Mask.size());
491   copy(Mask, AllocMask);
492   return {AllocMask, Mask.size()};
493 }
494 
495 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
496 LLVM_DUMP_METHOD void MachineFunction::dump() const {
497   print(dbgs());
498 }
499 #endif
500 
501 StringRef MachineFunction::getName() const {
502   return getFunction().getName();
503 }
504 
505 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
506   OS << "# Machine code for function " << getName() << ": ";
507   getProperties().print(OS);
508   OS << '\n';
509 
510   // Print Frame Information
511   FrameInfo->print(*this, OS);
512 
513   // Print JumpTable Information
514   if (JumpTableInfo)
515     JumpTableInfo->print(OS);
516 
517   // Print Constant Pool
518   ConstantPool->print(OS);
519 
520   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
521 
522   if (RegInfo && !RegInfo->livein_empty()) {
523     OS << "Function Live Ins: ";
524     for (MachineRegisterInfo::livein_iterator
525          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
526       OS << printReg(I->first, TRI);
527       if (I->second)
528         OS << " in " << printReg(I->second, TRI);
529       if (std::next(I) != E)
530         OS << ", ";
531     }
532     OS << '\n';
533   }
534 
535   ModuleSlotTracker MST(getFunction().getParent());
536   MST.incorporateFunction(getFunction());
537   for (const auto &BB : *this) {
538     OS << '\n';
539     // If we print the whole function, print it at its most verbose level.
540     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
541   }
542 
543   OS << "\n# End machine code for function " << getName() << ".\n\n";
544 }
545 
546 /// True if this function needs frame moves for debug or exceptions.
547 bool MachineFunction::needsFrameMoves() const {
548   return getMMI().hasDebugInfo() ||
549          getTarget().Options.ForceDwarfFrameSection ||
550          F.needsUnwindTableEntry();
551 }
552 
553 namespace llvm {
554 
555   template<>
556   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
557     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
558 
559     static std::string getGraphName(const MachineFunction *F) {
560       return ("CFG for '" + F->getName() + "' function").str();
561     }
562 
563     std::string getNodeLabel(const MachineBasicBlock *Node,
564                              const MachineFunction *Graph) {
565       std::string OutStr;
566       {
567         raw_string_ostream OSS(OutStr);
568 
569         if (isSimple()) {
570           OSS << printMBBReference(*Node);
571           if (const BasicBlock *BB = Node->getBasicBlock())
572             OSS << ": " << BB->getName();
573         } else
574           Node->print(OSS);
575       }
576 
577       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
578 
579       // Process string output to make it nicer...
580       for (unsigned i = 0; i != OutStr.length(); ++i)
581         if (OutStr[i] == '\n') {                            // Left justify
582           OutStr[i] = '\\';
583           OutStr.insert(OutStr.begin()+i+1, 'l');
584         }
585       return OutStr;
586     }
587   };
588 
589 } // end namespace llvm
590 
591 void MachineFunction::viewCFG() const
592 {
593 #ifndef NDEBUG
594   ViewGraph(this, "mf" + getName());
595 #else
596   errs() << "MachineFunction::viewCFG is only available in debug builds on "
597          << "systems with Graphviz or gv!\n";
598 #endif // NDEBUG
599 }
600 
601 void MachineFunction::viewCFGOnly() const
602 {
603 #ifndef NDEBUG
604   ViewGraph(this, "mf" + getName(), true);
605 #else
606   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
607          << "systems with Graphviz or gv!\n";
608 #endif // NDEBUG
609 }
610 
611 /// Add the specified physical register as a live-in value and
612 /// create a corresponding virtual register for it.
613 unsigned MachineFunction::addLiveIn(unsigned PReg,
614                                     const TargetRegisterClass *RC) {
615   MachineRegisterInfo &MRI = getRegInfo();
616   unsigned VReg = MRI.getLiveInVirtReg(PReg);
617   if (VReg) {
618     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
619     (void)VRegRC;
620     // A physical register can be added several times.
621     // Between two calls, the register class of the related virtual register
622     // may have been constrained to match some operation constraints.
623     // In that case, check that the current register class includes the
624     // physical register and is a sub class of the specified RC.
625     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
626                              RC->hasSubClassEq(VRegRC))) &&
627             "Register class mismatch!");
628     return VReg;
629   }
630   VReg = MRI.createVirtualRegister(RC);
631   MRI.addLiveIn(PReg, VReg);
632   return VReg;
633 }
634 
635 /// Return the MCSymbol for the specified non-empty jump table.
636 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
637 /// normal 'L' label is returned.
638 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
639                                         bool isLinkerPrivate) const {
640   const DataLayout &DL = getDataLayout();
641   assert(JumpTableInfo && "No jump tables");
642   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
643 
644   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
645                                      : DL.getPrivateGlobalPrefix();
646   SmallString<60> Name;
647   raw_svector_ostream(Name)
648     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
649   return Ctx.getOrCreateSymbol(Name);
650 }
651 
652 /// Return a function-local symbol to represent the PIC base.
653 MCSymbol *MachineFunction::getPICBaseSymbol() const {
654   const DataLayout &DL = getDataLayout();
655   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
656                                Twine(getFunctionNumber()) + "$pb");
657 }
658 
659 /// \name Exception Handling
660 /// \{
661 
662 LandingPadInfo &
663 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
664   unsigned N = LandingPads.size();
665   for (unsigned i = 0; i < N; ++i) {
666     LandingPadInfo &LP = LandingPads[i];
667     if (LP.LandingPadBlock == LandingPad)
668       return LP;
669   }
670 
671   LandingPads.push_back(LandingPadInfo(LandingPad));
672   return LandingPads[N];
673 }
674 
675 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
676                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
677   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
678   LP.BeginLabels.push_back(BeginLabel);
679   LP.EndLabels.push_back(EndLabel);
680 }
681 
682 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
683   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
684   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
685   LP.LandingPadLabel = LandingPadLabel;
686 
687   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
688   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
689     if (const auto *PF =
690             dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
691       getMMI().addPersonality(PF);
692 
693     if (LPI->isCleanup())
694       addCleanup(LandingPad);
695 
696     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
697     //        correct, but we need to do it this way because of how the DWARF EH
698     //        emitter processes the clauses.
699     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
700       Value *Val = LPI->getClause(I - 1);
701       if (LPI->isCatch(I - 1)) {
702         addCatchTypeInfo(LandingPad,
703                          dyn_cast<GlobalValue>(Val->stripPointerCasts()));
704       } else {
705         // Add filters in a list.
706         auto *CVal = cast<Constant>(Val);
707         SmallVector<const GlobalValue *, 4> FilterList;
708         for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
709              II != IE; ++II)
710           FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
711 
712         addFilterTypeInfo(LandingPad, FilterList);
713       }
714     }
715 
716   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
717     for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
718       Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
719       addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
720     }
721 
722   } else {
723     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
724   }
725 
726   return LandingPadLabel;
727 }
728 
729 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
730                                        ArrayRef<const GlobalValue *> TyInfo) {
731   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
732   for (unsigned N = TyInfo.size(); N; --N)
733     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
734 }
735 
736 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
737                                         ArrayRef<const GlobalValue *> TyInfo) {
738   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
739   std::vector<unsigned> IdsInFilter(TyInfo.size());
740   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
741     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
742   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
743 }
744 
745 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
746                                       bool TidyIfNoBeginLabels) {
747   for (unsigned i = 0; i != LandingPads.size(); ) {
748     LandingPadInfo &LandingPad = LandingPads[i];
749     if (LandingPad.LandingPadLabel &&
750         !LandingPad.LandingPadLabel->isDefined() &&
751         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
752       LandingPad.LandingPadLabel = nullptr;
753 
754     // Special case: we *should* emit LPs with null LP MBB. This indicates
755     // "nounwind" case.
756     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
757       LandingPads.erase(LandingPads.begin() + i);
758       continue;
759     }
760 
761     if (TidyIfNoBeginLabels) {
762       for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
763         MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
764         MCSymbol *EndLabel = LandingPad.EndLabels[j];
765         if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
766             (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
767           continue;
768 
769         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
770         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
771         --j;
772         --e;
773       }
774 
775       // Remove landing pads with no try-ranges.
776       if (LandingPads[i].BeginLabels.empty()) {
777         LandingPads.erase(LandingPads.begin() + i);
778         continue;
779       }
780     }
781 
782     // If there is no landing pad, ensure that the list of typeids is empty.
783     // If the only typeid is a cleanup, this is the same as having no typeids.
784     if (!LandingPad.LandingPadBlock ||
785         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
786       LandingPad.TypeIds.clear();
787     ++i;
788   }
789 }
790 
791 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
792   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
793   LP.TypeIds.push_back(0);
794 }
795 
796 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
797                                          const Function *Filter,
798                                          const BlockAddress *RecoverBA) {
799   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
800   SEHHandler Handler;
801   Handler.FilterOrFinally = Filter;
802   Handler.RecoverBA = RecoverBA;
803   LP.SEHHandlers.push_back(Handler);
804 }
805 
806 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
807                                            const Function *Cleanup) {
808   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
809   SEHHandler Handler;
810   Handler.FilterOrFinally = Cleanup;
811   Handler.RecoverBA = nullptr;
812   LP.SEHHandlers.push_back(Handler);
813 }
814 
815 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
816                                             ArrayRef<unsigned> Sites) {
817   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
818 }
819 
820 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
821   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
822     if (TypeInfos[i] == TI) return i + 1;
823 
824   TypeInfos.push_back(TI);
825   return TypeInfos.size();
826 }
827 
828 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
829   // If the new filter coincides with the tail of an existing filter, then
830   // re-use the existing filter.  Folding filters more than this requires
831   // re-ordering filters and/or their elements - probably not worth it.
832   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
833        E = FilterEnds.end(); I != E; ++I) {
834     unsigned i = *I, j = TyIds.size();
835 
836     while (i && j)
837       if (FilterIds[--i] != TyIds[--j])
838         goto try_next;
839 
840     if (!j)
841       // The new filter coincides with range [i, end) of the existing filter.
842       return -(1 + i);
843 
844 try_next:;
845   }
846 
847   // Add the new filter.
848   int FilterID = -(1 + FilterIds.size());
849   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
850   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
851   FilterEnds.push_back(FilterIds.size());
852   FilterIds.push_back(0); // terminator
853   return FilterID;
854 }
855 
856 MachineFunction::CallSiteInfoMap::iterator
857 MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
858   assert(MI->isCandidateForCallSiteEntry() &&
859          "Call site info refers only to call (MI) candidates");
860 
861   if (!Target.Options.EmitCallSiteInfo)
862     return CallSitesInfo.end();
863   return CallSitesInfo.find(MI);
864 }
865 
866 /// Return the call machine instruction or find a call within bundle.
867 static const MachineInstr *getCallInstr(const MachineInstr *MI) {
868   if (!MI->isBundle())
869     return MI;
870 
871   for (auto &BMI : make_range(getBundleStart(MI->getIterator()),
872                               getBundleEnd(MI->getIterator())))
873     if (BMI.isCandidateForCallSiteEntry())
874       return &BMI;
875 
876   llvm_unreachable("Unexpected bundle without a call site candidate");
877 }
878 
879 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
880   assert(MI->shouldUpdateCallSiteInfo() &&
881          "Call site info refers only to call (MI) candidates or "
882          "candidates inside bundles");
883 
884   const MachineInstr *CallMI = getCallInstr(MI);
885   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
886   if (CSIt == CallSitesInfo.end())
887     return;
888   CallSitesInfo.erase(CSIt);
889 }
890 
891 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
892                                        const MachineInstr *New) {
893   assert(Old->shouldUpdateCallSiteInfo() &&
894          "Call site info refers only to call (MI) candidates or "
895          "candidates inside bundles");
896 
897   if (!New->isCandidateForCallSiteEntry())
898     return eraseCallSiteInfo(Old);
899 
900   const MachineInstr *OldCallMI = getCallInstr(Old);
901   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
902   if (CSIt == CallSitesInfo.end())
903     return;
904 
905   CallSiteInfo CSInfo = CSIt->second;
906   CallSitesInfo[New] = CSInfo;
907 }
908 
909 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
910                                        const MachineInstr *New) {
911   assert(Old->shouldUpdateCallSiteInfo() &&
912          "Call site info refers only to call (MI) candidates or "
913          "candidates inside bundles");
914 
915   if (!New->isCandidateForCallSiteEntry())
916     return eraseCallSiteInfo(Old);
917 
918   const MachineInstr *OldCallMI = getCallInstr(Old);
919   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
920   if (CSIt == CallSitesInfo.end())
921     return;
922 
923   CallSiteInfo CSInfo = std::move(CSIt->second);
924   CallSitesInfo.erase(CSIt);
925   CallSitesInfo[New] = CSInfo;
926 }
927 
928 /// \}
929 
930 //===----------------------------------------------------------------------===//
931 //  MachineJumpTableInfo implementation
932 //===----------------------------------------------------------------------===//
933 
934 /// Return the size of each entry in the jump table.
935 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
936   // The size of a jump table entry is 4 bytes unless the entry is just the
937   // address of a block, in which case it is the pointer size.
938   switch (getEntryKind()) {
939   case MachineJumpTableInfo::EK_BlockAddress:
940     return TD.getPointerSize();
941   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
942     return 8;
943   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
944   case MachineJumpTableInfo::EK_LabelDifference32:
945   case MachineJumpTableInfo::EK_Custom32:
946     return 4;
947   case MachineJumpTableInfo::EK_Inline:
948     return 0;
949   }
950   llvm_unreachable("Unknown jump table encoding!");
951 }
952 
953 /// Return the alignment of each entry in the jump table.
954 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
955   // The alignment of a jump table entry is the alignment of int32 unless the
956   // entry is just the address of a block, in which case it is the pointer
957   // alignment.
958   switch (getEntryKind()) {
959   case MachineJumpTableInfo::EK_BlockAddress:
960     return TD.getPointerABIAlignment(0).value();
961   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
962     return TD.getABIIntegerTypeAlignment(64).value();
963   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
964   case MachineJumpTableInfo::EK_LabelDifference32:
965   case MachineJumpTableInfo::EK_Custom32:
966     return TD.getABIIntegerTypeAlignment(32).value();
967   case MachineJumpTableInfo::EK_Inline:
968     return 1;
969   }
970   llvm_unreachable("Unknown jump table encoding!");
971 }
972 
973 /// Create a new jump table entry in the jump table info.
974 unsigned MachineJumpTableInfo::createJumpTableIndex(
975                                const std::vector<MachineBasicBlock*> &DestBBs) {
976   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
977   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
978   return JumpTables.size()-1;
979 }
980 
981 /// If Old is the target of any jump tables, update the jump tables to branch
982 /// to New instead.
983 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
984                                                   MachineBasicBlock *New) {
985   assert(Old != New && "Not making a change?");
986   bool MadeChange = false;
987   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
988     ReplaceMBBInJumpTable(i, Old, New);
989   return MadeChange;
990 }
991 
992 /// If Old is a target of the jump tables, update the jump table to branch to
993 /// New instead.
994 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
995                                                  MachineBasicBlock *Old,
996                                                  MachineBasicBlock *New) {
997   assert(Old != New && "Not making a change?");
998   bool MadeChange = false;
999   MachineJumpTableEntry &JTE = JumpTables[Idx];
1000   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
1001     if (JTE.MBBs[j] == Old) {
1002       JTE.MBBs[j] = New;
1003       MadeChange = true;
1004     }
1005   return MadeChange;
1006 }
1007 
1008 void MachineJumpTableInfo::print(raw_ostream &OS) const {
1009   if (JumpTables.empty()) return;
1010 
1011   OS << "Jump Tables:\n";
1012 
1013   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1014     OS << printJumpTableEntryReference(i) << ':';
1015     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
1016       OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
1017     if (i != e)
1018       OS << '\n';
1019   }
1020 
1021   OS << '\n';
1022 }
1023 
1024 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1025 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1026 #endif
1027 
1028 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1029   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1030 }
1031 
1032 //===----------------------------------------------------------------------===//
1033 //  MachineConstantPool implementation
1034 //===----------------------------------------------------------------------===//
1035 
1036 void MachineConstantPoolValue::anchor() {}
1037 
1038 Type *MachineConstantPoolEntry::getType() const {
1039   if (isMachineConstantPoolEntry())
1040     return Val.MachineCPVal->getType();
1041   return Val.ConstVal->getType();
1042 }
1043 
1044 bool MachineConstantPoolEntry::needsRelocation() const {
1045   if (isMachineConstantPoolEntry())
1046     return true;
1047   return Val.ConstVal->needsRelocation();
1048 }
1049 
1050 SectionKind
1051 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1052   if (needsRelocation())
1053     return SectionKind::getReadOnlyWithRel();
1054   switch (DL->getTypeAllocSize(getType())) {
1055   case 4:
1056     return SectionKind::getMergeableConst4();
1057   case 8:
1058     return SectionKind::getMergeableConst8();
1059   case 16:
1060     return SectionKind::getMergeableConst16();
1061   case 32:
1062     return SectionKind::getMergeableConst32();
1063   default:
1064     return SectionKind::getReadOnly();
1065   }
1066 }
1067 
1068 MachineConstantPool::~MachineConstantPool() {
1069   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1070   // so keep track of which we've deleted to avoid double deletions.
1071   DenseSet<MachineConstantPoolValue*> Deleted;
1072   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1073     if (Constants[i].isMachineConstantPoolEntry()) {
1074       Deleted.insert(Constants[i].Val.MachineCPVal);
1075       delete Constants[i].Val.MachineCPVal;
1076     }
1077   for (DenseSet<MachineConstantPoolValue*>::iterator I =
1078        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
1079        I != E; ++I) {
1080     if (Deleted.count(*I) == 0)
1081       delete *I;
1082   }
1083 }
1084 
1085 /// Test whether the given two constants can be allocated the same constant pool
1086 /// entry.
1087 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1088                                       const DataLayout &DL) {
1089   // Handle the trivial case quickly.
1090   if (A == B) return true;
1091 
1092   // If they have the same type but weren't the same constant, quickly
1093   // reject them.
1094   if (A->getType() == B->getType()) return false;
1095 
1096   // We can't handle structs or arrays.
1097   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1098       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1099     return false;
1100 
1101   // For now, only support constants with the same size.
1102   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1103   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1104     return false;
1105 
1106   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1107 
1108   // Try constant folding a bitcast of both instructions to an integer.  If we
1109   // get two identical ConstantInt's, then we are good to share them.  We use
1110   // the constant folding APIs to do this so that we get the benefit of
1111   // DataLayout.
1112   if (isa<PointerType>(A->getType()))
1113     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1114                                 const_cast<Constant *>(A), IntTy, DL);
1115   else if (A->getType() != IntTy)
1116     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1117                                 IntTy, DL);
1118   if (isa<PointerType>(B->getType()))
1119     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1120                                 const_cast<Constant *>(B), IntTy, DL);
1121   else if (B->getType() != IntTy)
1122     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1123                                 IntTy, DL);
1124 
1125   return A == B;
1126 }
1127 
1128 /// Create a new entry in the constant pool or return an existing one.
1129 /// User must specify the log2 of the minimum required alignment for the object.
1130 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1131                                                    unsigned Alignment) {
1132   assert(Alignment && "Alignment must be specified!");
1133   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1134 
1135   // Check to see if we already have this constant.
1136   //
1137   // FIXME, this could be made much more efficient for large constant pools.
1138   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1139     if (!Constants[i].isMachineConstantPoolEntry() &&
1140         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1141       if ((unsigned)Constants[i].getAlignment() < Alignment)
1142         Constants[i].Alignment = Alignment;
1143       return i;
1144     }
1145 
1146   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1147   return Constants.size()-1;
1148 }
1149 
1150 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1151                                                    unsigned Alignment) {
1152   assert(Alignment && "Alignment must be specified!");
1153   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1154 
1155   // Check to see if we already have this constant.
1156   //
1157   // FIXME, this could be made much more efficient for large constant pools.
1158   int Idx = V->getExistingMachineCPValue(this, Alignment);
1159   if (Idx != -1) {
1160     MachineCPVsSharingEntries.insert(V);
1161     return (unsigned)Idx;
1162   }
1163 
1164   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1165   return Constants.size()-1;
1166 }
1167 
1168 void MachineConstantPool::print(raw_ostream &OS) const {
1169   if (Constants.empty()) return;
1170 
1171   OS << "Constant Pool:\n";
1172   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1173     OS << "  cp#" << i << ": ";
1174     if (Constants[i].isMachineConstantPoolEntry())
1175       Constants[i].Val.MachineCPVal->print(OS);
1176     else
1177       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1178     OS << ", align=" << Constants[i].getAlignment();
1179     OS << "\n";
1180   }
1181 }
1182 
1183 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1184 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1185 #endif
1186