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