Bug Summary

File:lib/CodeGen/AsmPrinter/AsmPrinter.cpp
Warning:line 2480, column 44
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name AsmPrinter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn361465/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/lib/CodeGen/AsmPrinter -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn361465=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-24-031927-21217-1 -x c++ /build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

1//===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
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// This file implements the AsmPrinter class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/AsmPrinter.h"
14#include "CodeViewDebug.h"
15#include "DwarfDebug.h"
16#include "DwarfException.h"
17#include "WasmException.h"
18#include "WinCFGuard.h"
19#include "WinException.h"
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/Triple.h"
30#include "llvm/ADT/Twine.h"
31#include "llvm/Analysis/ConstantFolding.h"
32#include "llvm/Analysis/EHPersonalities.h"
33#include "llvm/Analysis/OptimizationRemarkEmitter.h"
34#include "llvm/BinaryFormat/COFF.h"
35#include "llvm/BinaryFormat/Dwarf.h"
36#include "llvm/BinaryFormat/ELF.h"
37#include "llvm/CodeGen/GCMetadata.h"
38#include "llvm/CodeGen/GCMetadataPrinter.h"
39#include "llvm/CodeGen/GCStrategy.h"
40#include "llvm/CodeGen/MachineBasicBlock.h"
41#include "llvm/CodeGen/MachineConstantPool.h"
42#include "llvm/CodeGen/MachineDominators.h"
43#include "llvm/CodeGen/MachineFrameInfo.h"
44#include "llvm/CodeGen/MachineFunction.h"
45#include "llvm/CodeGen/MachineFunctionPass.h"
46#include "llvm/CodeGen/MachineInstr.h"
47#include "llvm/CodeGen/MachineInstrBundle.h"
48#include "llvm/CodeGen/MachineJumpTableInfo.h"
49#include "llvm/CodeGen/MachineLoopInfo.h"
50#include "llvm/CodeGen/MachineMemOperand.h"
51#include "llvm/CodeGen/MachineModuleInfo.h"
52#include "llvm/CodeGen/MachineModuleInfoImpls.h"
53#include "llvm/CodeGen/MachineOperand.h"
54#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
55#include "llvm/CodeGen/StackMaps.h"
56#include "llvm/CodeGen/TargetFrameLowering.h"
57#include "llvm/CodeGen/TargetInstrInfo.h"
58#include "llvm/CodeGen/TargetLowering.h"
59#include "llvm/CodeGen/TargetOpcodes.h"
60#include "llvm/CodeGen/TargetRegisterInfo.h"
61#include "llvm/IR/BasicBlock.h"
62#include "llvm/IR/Comdat.h"
63#include "llvm/IR/Constant.h"
64#include "llvm/IR/Constants.h"
65#include "llvm/IR/DataLayout.h"
66#include "llvm/IR/DebugInfoMetadata.h"
67#include "llvm/IR/DerivedTypes.h"
68#include "llvm/IR/Function.h"
69#include "llvm/IR/GlobalAlias.h"
70#include "llvm/IR/GlobalIFunc.h"
71#include "llvm/IR/GlobalIndirectSymbol.h"
72#include "llvm/IR/GlobalObject.h"
73#include "llvm/IR/GlobalValue.h"
74#include "llvm/IR/GlobalVariable.h"
75#include "llvm/IR/Instruction.h"
76#include "llvm/IR/Mangler.h"
77#include "llvm/IR/Metadata.h"
78#include "llvm/IR/Module.h"
79#include "llvm/IR/Operator.h"
80#include "llvm/IR/RemarkStreamer.h"
81#include "llvm/IR/Type.h"
82#include "llvm/IR/Value.h"
83#include "llvm/MC/MCAsmInfo.h"
84#include "llvm/MC/MCCodePadder.h"
85#include "llvm/MC/MCContext.h"
86#include "llvm/MC/MCDirectives.h"
87#include "llvm/MC/MCDwarf.h"
88#include "llvm/MC/MCExpr.h"
89#include "llvm/MC/MCInst.h"
90#include "llvm/MC/MCSection.h"
91#include "llvm/MC/MCSectionCOFF.h"
92#include "llvm/MC/MCSectionELF.h"
93#include "llvm/MC/MCSectionMachO.h"
94#include "llvm/MC/MCStreamer.h"
95#include "llvm/MC/MCSubtargetInfo.h"
96#include "llvm/MC/MCSymbol.h"
97#include "llvm/MC/MCSymbolELF.h"
98#include "llvm/MC/MCTargetOptions.h"
99#include "llvm/MC/MCValue.h"
100#include "llvm/MC/SectionKind.h"
101#include "llvm/Pass.h"
102#include "llvm/Remarks/Remark.h"
103#include "llvm/Support/Casting.h"
104#include "llvm/Support/CommandLine.h"
105#include "llvm/Support/Compiler.h"
106#include "llvm/Support/ErrorHandling.h"
107#include "llvm/Support/Format.h"
108#include "llvm/Support/MathExtras.h"
109#include "llvm/Support/Path.h"
110#include "llvm/Support/TargetRegistry.h"
111#include "llvm/Support/Timer.h"
112#include "llvm/Support/raw_ostream.h"
113#include "llvm/Target/TargetLoweringObjectFile.h"
114#include "llvm/Target/TargetMachine.h"
115#include "llvm/Target/TargetOptions.h"
116#include <algorithm>
117#include <cassert>
118#include <cinttypes>
119#include <cstdint>
120#include <iterator>
121#include <limits>
122#include <memory>
123#include <string>
124#include <utility>
125#include <vector>
126
127using namespace llvm;
128
129#define DEBUG_TYPE"asm-printer" "asm-printer"
130
131static const char *const DWARFGroupName = "dwarf";
132static const char *const DWARFGroupDescription = "DWARF Emission";
133static const char *const DbgTimerName = "emit";
134static const char *const DbgTimerDescription = "Debug Info Emission";
135static const char *const EHTimerName = "write_exception";
136static const char *const EHTimerDescription = "DWARF Exception Writer";
137static const char *const CFGuardName = "Control Flow Guard";
138static const char *const CFGuardDescription = "Control Flow Guard Tables";
139static const char *const CodeViewLineTablesGroupName = "linetables";
140static const char *const CodeViewLineTablesGroupDescription =
141 "CodeView Line Tables";
142
143STATISTIC(EmittedInsts, "Number of machine instrs printed")static llvm::Statistic EmittedInsts = {"asm-printer", "EmittedInsts"
, "Number of machine instrs printed", {0}, {false}}
;
144
145static cl::opt<bool> EnableRemarksSection(
146 "remarks-section",
147 cl::desc("Emit a section containing remark diagnostics metadata"),
148 cl::init(false));
149
150char AsmPrinter::ID = 0;
151
152using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>;
153
154static gcp_map_type &getGCMap(void *&P) {
155 if (!P)
156 P = new gcp_map_type();
157 return *(gcp_map_type*)P;
158}
159
160/// getGVAlignmentLog2 - Return the alignment to use for the specified global
161/// value in log2 form. This rounds up to the preferred alignment if possible
162/// and legal.
163static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
164 unsigned InBits = 0) {
165 unsigned NumBits = 0;
166 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
167 NumBits = DL.getPreferredAlignmentLog(GVar);
168
169 // If InBits is specified, round it to it.
170 if (InBits > NumBits)
171 NumBits = InBits;
172
173 // If the GV has a specified alignment, take it into account.
174 if (GV->getAlignment() == 0)
175 return NumBits;
176
177 unsigned GVAlign = Log2_32(GV->getAlignment());
178
179 // If the GVAlign is larger than NumBits, or if we are required to obey
180 // NumBits because the GV has an assigned section, obey it.
181 if (GVAlign > NumBits || GV->hasSection())
182 NumBits = GVAlign;
183 return NumBits;
184}
185
186AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
187 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
188 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
189 VerboseAsm = OutStreamer->isVerboseAsm();
190}
191
192AsmPrinter::~AsmPrinter() {
193 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized")((!DD && Handlers.empty() && "Debug/EH info didn't get finalized"
) ? static_cast<void> (0) : __assert_fail ("!DD && Handlers.empty() && \"Debug/EH info didn't get finalized\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 193, __PRETTY_FUNCTION__))
;
194
195 if (GCMetadataPrinters) {
196 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
197
198 delete &GCMap;
199 GCMetadataPrinters = nullptr;
200 }
201}
202
203bool AsmPrinter::isPositionIndependent() const {
204 return TM.isPositionIndependent();
205}
206
207/// getFunctionNumber - Return a unique ID for the current function.
208unsigned AsmPrinter::getFunctionNumber() const {
209 return MF->getFunctionNumber();
210}
211
212const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
213 return *TM.getObjFileLowering();
214}
215
216const DataLayout &AsmPrinter::getDataLayout() const {
217 return MMI->getModule()->getDataLayout();
218}
219
220// Do not use the cached DataLayout because some client use it without a Module
221// (dsymutil, llvm-dwarfdump).
222unsigned AsmPrinter::getPointerSize() const {
223 return TM.getPointerSize(0); // FIXME: Default address space
224}
225
226const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
227 assert(MF && "getSubtargetInfo requires a valid MachineFunction!")((MF && "getSubtargetInfo requires a valid MachineFunction!"
) ? static_cast<void> (0) : __assert_fail ("MF && \"getSubtargetInfo requires a valid MachineFunction!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 227, __PRETTY_FUNCTION__))
;
228 return MF->getSubtarget<MCSubtargetInfo>();
229}
230
231void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
232 S.EmitInstruction(Inst, getSubtargetInfo());
233}
234
235void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
236 assert(DD && "Dwarf debug file is not defined.")((DD && "Dwarf debug file is not defined.") ? static_cast
<void> (0) : __assert_fail ("DD && \"Dwarf debug file is not defined.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 236, __PRETTY_FUNCTION__))
;
237 assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode.")((OutStreamer->hasRawTextSupport() && "Expected assembly output mode."
) ? static_cast<void> (0) : __assert_fail ("OutStreamer->hasRawTextSupport() && \"Expected assembly output mode.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 237, __PRETTY_FUNCTION__))
;
238 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
239}
240
241/// getCurrentSection() - Return the current section we are emitting to.
242const MCSection *AsmPrinter::getCurrentSection() const {
243 return OutStreamer->getCurrentSectionOnly();
244}
245
246void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
247 AU.setPreservesAll();
248 MachineFunctionPass::getAnalysisUsage(AU);
249 AU.addRequired<MachineModuleInfo>();
250 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
251 AU.addRequired<GCModuleInfo>();
252}
253
254bool AsmPrinter::doInitialization(Module &M) {
255 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
256
257 // Initialize TargetLoweringObjectFile.
258 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
259 .Initialize(OutContext, TM);
260
261 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
262 .getModuleMetadata(M);
263
264 OutStreamer->InitSections(false);
265
266 // Emit the version-min deployment target directive if needed.
267 //
268 // FIXME: If we end up with a collection of these sorts of Darwin-specific
269 // or ELF-specific things, it may make sense to have a platform helper class
270 // that will work with the target helper class. For now keep it here, as the
271 // alternative is duplicated code in each of the target asm printers that
272 // use the directive, where it would need the same conditionalization
273 // anyway.
274 const Triple &Target = TM.getTargetTriple();
275 OutStreamer->EmitVersionForTarget(Target, M.getSDKVersion());
276
277 // Allow the target to emit any magic that it wants at the start of the file.
278 EmitStartOfAsmFile(M);
279
280 // Very minimal debug info. It is ignored if we emit actual debug info. If we
281 // don't, this at least helps the user find where a global came from.
282 if (MAI->hasSingleParameterDotFile()) {
283 // .file "foo.c"
284 OutStreamer->EmitFileDirective(
285 llvm::sys::path::filename(M.getSourceFileName()));
286 }
287
288 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
289 assert(MI && "AsmPrinter didn't require GCModuleInfo?")((MI && "AsmPrinter didn't require GCModuleInfo?") ? static_cast
<void> (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 289, __PRETTY_FUNCTION__))
;
290 for (auto &I : *MI)
291 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
292 MP->beginAssembly(M, *MI, *this);
293
294 // Emit module-level inline asm if it exists.
295 if (!M.getModuleInlineAsm().empty()) {
296 // We're at the module level. Construct MCSubtarget from the default CPU
297 // and target triple.
298 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
299 TM.getTargetTriple().str(), TM.getTargetCPU(),
300 TM.getTargetFeatureString()));
301 OutStreamer->AddComment("Start of file scope inline assembly");
302 OutStreamer->AddBlankLine();
303 EmitInlineAsm(M.getModuleInlineAsm()+"\n",
304 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
305 OutStreamer->AddComment("End of file scope inline assembly");
306 OutStreamer->AddBlankLine();
307 }
308
309 if (MAI->doesSupportDebugInformation()) {
310 bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
311 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
312 Handlers.emplace_back(llvm::make_unique<CodeViewDebug>(this),
313 DbgTimerName, DbgTimerDescription,
314 CodeViewLineTablesGroupName,
315 CodeViewLineTablesGroupDescription);
316 }
317 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
318 DD = new DwarfDebug(this, &M);
319 DD->beginModule();
320 Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
321 DbgTimerDescription, DWARFGroupName,
322 DWARFGroupDescription);
323 }
324 }
325
326 switch (MAI->getExceptionHandlingType()) {
327 case ExceptionHandling::SjLj:
328 case ExceptionHandling::DwarfCFI:
329 case ExceptionHandling::ARM:
330 isCFIMoveForDebugging = true;
331 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
332 break;
333 for (auto &F: M.getFunctionList()) {
334 // If the module contains any function with unwind data,
335 // .eh_frame has to be emitted.
336 // Ignore functions that won't get emitted.
337 if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) {
338 isCFIMoveForDebugging = false;
339 break;
340 }
341 }
342 break;
343 default:
344 isCFIMoveForDebugging = false;
345 break;
346 }
347
348 EHStreamer *ES = nullptr;
349 switch (MAI->getExceptionHandlingType()) {
350 case ExceptionHandling::None:
351 break;
352 case ExceptionHandling::SjLj:
353 case ExceptionHandling::DwarfCFI:
354 ES = new DwarfCFIException(this);
355 break;
356 case ExceptionHandling::ARM:
357 ES = new ARMException(this);
358 break;
359 case ExceptionHandling::WinEH:
360 switch (MAI->getWinEHEncodingType()) {
361 default: llvm_unreachable("unsupported unwinding information encoding")::llvm::llvm_unreachable_internal("unsupported unwinding information encoding"
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 361)
;
362 case WinEH::EncodingType::Invalid:
363 break;
364 case WinEH::EncodingType::X86:
365 case WinEH::EncodingType::Itanium:
366 ES = new WinException(this);
367 break;
368 }
369 break;
370 case ExceptionHandling::Wasm:
371 ES = new WasmException(this);
372 break;
373 }
374 if (ES)
375 Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
376 EHTimerDescription, DWARFGroupName,
377 DWARFGroupDescription);
378
379 if (mdconst::extract_or_null<ConstantInt>(
380 MMI->getModule()->getModuleFlag("cfguardtable")))
381 Handlers.emplace_back(llvm::make_unique<WinCFGuard>(this), CFGuardName,
382 CFGuardDescription, DWARFGroupName,
383 DWARFGroupDescription);
384
385 return false;
386}
387
388static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
389 if (!MAI.hasWeakDefCanBeHiddenDirective())
390 return false;
391
392 return GV->canBeOmittedFromSymbolTable();
393}
394
395void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
396 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
397 switch (Linkage) {
398 case GlobalValue::CommonLinkage:
399 case GlobalValue::LinkOnceAnyLinkage:
400 case GlobalValue::LinkOnceODRLinkage:
401 case GlobalValue::WeakAnyLinkage:
402 case GlobalValue::WeakODRLinkage:
403 if (MAI->hasWeakDefDirective()) {
404 // .globl _foo
405 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
406
407 if (!canBeHidden(GV, *MAI))
408 // .weak_definition _foo
409 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
410 else
411 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
412 } else if (MAI->hasLinkOnceDirective()) {
413 // .globl _foo
414 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
415 //NOTE: linkonce is handled by the section the symbol was assigned to.
416 } else {
417 // .weak _foo
418 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
419 }
420 return;
421 case GlobalValue::ExternalLinkage:
422 // If external, declare as a global symbol: .globl _foo
423 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
424 return;
425 case GlobalValue::PrivateLinkage:
426 case GlobalValue::InternalLinkage:
427 return;
428 case GlobalValue::AppendingLinkage:
429 case GlobalValue::AvailableExternallyLinkage:
430 case GlobalValue::ExternalWeakLinkage:
431 llvm_unreachable("Should never emit this")::llvm::llvm_unreachable_internal("Should never emit this", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 431)
;
432 }
433 llvm_unreachable("Unknown linkage type!")::llvm::llvm_unreachable_internal("Unknown linkage type!", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 433)
;
434}
435
436void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
437 const GlobalValue *GV) const {
438 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
439}
440
441MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
442 return TM.getSymbol(GV);
443}
444
445/// EmitGlobalVariable - Emit the specified global variable to the .s file.
446void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
447 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
2
Assuming the condition is false
448 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&((!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
"No emulated TLS variables in the common section") ? static_cast
<void> (0) : __assert_fail ("!(IsEmuTLSVar && GV->hasCommonLinkage()) && \"No emulated TLS variables in the common section\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 449, __PRETTY_FUNCTION__))
3
'?' condition is true
449 "No emulated TLS variables in the common section")((!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
"No emulated TLS variables in the common section") ? static_cast
<void> (0) : __assert_fail ("!(IsEmuTLSVar && GV->hasCommonLinkage()) && \"No emulated TLS variables in the common section\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 449, __PRETTY_FUNCTION__))
;
450
451 // Never emit TLS variable xyz in emulated TLS model.
452 // The initialization value is in __emutls_t.xyz instead of xyz.
453 if (IsEmuTLSVar)
4
Taking false branch
454 return;
455
456 if (GV->hasInitializer()) {
5
Taking false branch
457 // Check to see if this is a special global used by LLVM, if so, emit it.
458 if (EmitSpecialLLVMGlobal(GV))
459 return;
460
461 // Skip the emission of global equivalents. The symbol can be emitted later
462 // on by emitGlobalGOTEquivs in case it turns out to be needed.
463 if (GlobalGOTEquivs.count(getSymbol(GV)))
464 return;
465
466 if (isVerbose()) {
467 // When printing the control variable __emutls_v.*,
468 // we don't need to print the original TLS variable name.
469 GV->printAsOperand(OutStreamer->GetCommentOS(),
470 /*PrintType=*/false, GV->getParent());
471 OutStreamer->GetCommentOS() << '\n';
472 }
473 }
474
475 MCSymbol *GVSym = getSymbol(GV);
476 MCSymbol *EmittedSym = GVSym;
477
478 // getOrCreateEmuTLSControlSym only creates the symbol with name and default
479 // attributes.
480 // GV's or GVSym's attributes will be used for the EmittedSym.
481 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
6
Assuming the condition is false
482
483 if (!GV->hasInitializer()) // External globals require no extra code.
7
Taking false branch
484 return;
485
486 GVSym->redefineIfPossible();
487 if (GVSym->isDefined() || GVSym->isVariable())
8
Taking false branch
488 report_fatal_error("symbol '" + Twine(GVSym->getName()) +
489 "' is already defined");
490
491 if (MAI->hasDotTypeDotSizeDirective())
9
Assuming the condition is false
10
Taking false branch
492 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
493
494 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
495
496 const DataLayout &DL = GV->getParent()->getDataLayout();
497 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
498
499 // If the alignment is specified, we *must* obey it. Overaligning a global
500 // with a specified alignment is a prompt way to break globals emitted to
501 // sections and expected to be contiguous (e.g. ObjC metadata).
502 unsigned AlignLog = getGVAlignmentLog2(GV, DL);
503
504 for (const HandlerInfo &HI : Handlers) {
11
Assuming '__begin1' is equal to '__end1'
505 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
506 HI.TimerGroupName, HI.TimerGroupDescription,
507 TimePassesIsEnabled);
508 HI.Handler->setSymbolSize(GVSym, Size);
509 }
510
511 // Handle common symbols
512 if (GVKind.isCommon()) {
12
Taking false branch
513 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
514 unsigned Align = 1 << AlignLog;
515 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
516 Align = 0;
517
518 // .comm _foo, 42, 4
519 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
520 return;
521 }
522
523 // Determine to which section this global should be emitted.
524 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
525
526 // If we have a bss global going to a section that supports the
527 // zerofill directive, do so here.
528 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
529 TheSection->isVirtualSection()) {
530 if (Size == 0)
531 Size = 1; // zerofill of 0 bytes is undefined.
532 unsigned Align = 1 << AlignLog;
533 EmitLinkage(GV, GVSym);
534 // .zerofill __DATA, __bss, _foo, 400, 5
535 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
536 return;
537 }
538
539 // If this is a BSS local symbol and we are emitting in the BSS
540 // section use .lcomm/.comm directive.
541 if (GVKind.isBSSLocal() &&
542 getObjFileLowering().getBSSSection() == TheSection) {
543 if (Size == 0)
544 Size = 1; // .comm Foo, 0 is undefined, avoid it.
545 unsigned Align = 1 << AlignLog;
546
547 // Use .lcomm only if it supports user-specified alignment.
548 // Otherwise, while it would still be correct to use .lcomm in some
549 // cases (e.g. when Align == 1), the external assembler might enfore
550 // some -unknown- default alignment behavior, which could cause
551 // spurious differences between external and integrated assembler.
552 // Prefer to simply fall back to .local / .comm in this case.
553 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
554 // .lcomm _foo, 42
555 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
556 return;
557 }
558
559 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
560 Align = 0;
561
562 // .local _foo
563 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
564 // .comm _foo, 42, 4
565 OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
566 return;
567 }
568
569 // Handle thread local data for mach-o which requires us to output an
570 // additional structure of data and mangle the original symbol so that we
571 // can reference it later.
572 //
573 // TODO: This should become an "emit thread local global" method on TLOF.
574 // All of this macho specific stuff should be sunk down into TLOFMachO and
575 // stuff like "TLSExtraDataSection" should no longer be part of the parent
576 // TLOF class. This will also make it more obvious that stuff like
577 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
578 // specific code.
579 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
580 // Emit the .tbss symbol
581 MCSymbol *MangSym =
582 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
583
584 if (GVKind.isThreadBSS()) {
585 TheSection = getObjFileLowering().getTLSBSSSection();
586 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
587 } else if (GVKind.isThreadData()) {
588 OutStreamer->SwitchSection(TheSection);
589
590 EmitAlignment(AlignLog, GV);
591 OutStreamer->EmitLabel(MangSym);
592
593 EmitGlobalConstant(GV->getParent()->getDataLayout(),
594 GV->getInitializer());
595 }
596
597 OutStreamer->AddBlankLine();
598
599 // Emit the variable struct for the runtime.
600 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
601
602 OutStreamer->SwitchSection(TLVSect);
603 // Emit the linkage here.
604 EmitLinkage(GV, GVSym);
605 OutStreamer->EmitLabel(GVSym);
606
607 // Three pointers in size:
608 // - __tlv_bootstrap - used to make sure support exists
609 // - spare pointer, used when mapped by the runtime
610 // - pointer to mangled symbol above with initializer
611 unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
612 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
613 PtrSize);
614 OutStreamer->EmitIntValue(0, PtrSize);
615 OutStreamer->EmitSymbolValue(MangSym, PtrSize);
616
617 OutStreamer->AddBlankLine();
618 return;
619 }
620
621 MCSymbol *EmittedInitSym = GVSym;
622
623 OutStreamer->SwitchSection(TheSection);
624
625 EmitLinkage(GV, EmittedInitSym);
626 EmitAlignment(AlignLog, GV);
627
628 OutStreamer->EmitLabel(EmittedInitSym);
629
630 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
13
Calling 'AsmPrinter::EmitGlobalConstant'
631
632 if (MAI->hasDotTypeDotSizeDirective())
633 // .size foo, 42
634 OutStreamer->emitELFSize(EmittedInitSym,
635 MCConstantExpr::create(Size, OutContext));
636
637 OutStreamer->AddBlankLine();
638}
639
640/// Emit the directive and value for debug thread local expression
641///
642/// \p Value - The value to emit.
643/// \p Size - The size of the integer (in bytes) to emit.
644void AsmPrinter::EmitDebugValue(const MCExpr *Value, unsigned Size) const {
645 OutStreamer->EmitValue(Value, Size);
646}
647
648/// EmitFunctionHeader - This method emits the header for the current
649/// function.
650void AsmPrinter::EmitFunctionHeader() {
651 const Function &F = MF->getFunction();
652
653 if (isVerbose())
654 OutStreamer->GetCommentOS()
655 << "-- Begin function "
656 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
657
658 // Print out constants referenced by the function
659 EmitConstantPool();
660
661 // Print the 'header' of function.
662 OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(&F, TM));
663 EmitVisibility(CurrentFnSym, F.getVisibility());
664
665 EmitLinkage(&F, CurrentFnSym);
666 if (MAI->hasFunctionAlignment())
667 EmitAlignment(MF->getAlignment(), &F);
668
669 if (MAI->hasDotTypeDotSizeDirective())
670 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
671
672 if (F.hasFnAttribute(Attribute::Cold))
673 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_Cold);
674
675 if (isVerbose()) {
676 F.printAsOperand(OutStreamer->GetCommentOS(),
677 /*PrintType=*/false, F.getParent());
678 OutStreamer->GetCommentOS() << '\n';
679 }
680
681 // Emit the prefix data.
682 if (F.hasPrefixData()) {
683 if (MAI->hasSubsectionsViaSymbols()) {
684 // Preserving prefix data on platforms which use subsections-via-symbols
685 // is a bit tricky. Here we introduce a symbol for the prefix data
686 // and use the .alt_entry attribute to mark the function's real entry point
687 // as an alternative entry point to the prefix-data symbol.
688 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
689 OutStreamer->EmitLabel(PrefixSym);
690
691 EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
692
693 // Emit an .alt_entry directive for the actual function symbol.
694 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
695 } else {
696 EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
697 }
698 }
699
700 // Emit the CurrentFnSym. This is a virtual function to allow targets to
701 // do their wild and crazy things as required.
702 EmitFunctionEntryLabel();
703
704 // If the function had address-taken blocks that got deleted, then we have
705 // references to the dangling symbols. Emit them at the start of the function
706 // so that we don't get references to undefined symbols.
707 std::vector<MCSymbol*> DeadBlockSyms;
708 MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
709 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
710 OutStreamer->AddComment("Address taken block that was later removed");
711 OutStreamer->EmitLabel(DeadBlockSyms[i]);
712 }
713
714 if (CurrentFnBegin) {
715 if (MAI->useAssignmentForEHBegin()) {
716 MCSymbol *CurPos = OutContext.createTempSymbol();
717 OutStreamer->EmitLabel(CurPos);
718 OutStreamer->EmitAssignment(CurrentFnBegin,
719 MCSymbolRefExpr::create(CurPos, OutContext));
720 } else {
721 OutStreamer->EmitLabel(CurrentFnBegin);
722 }
723 }
724
725 // Emit pre-function debug and/or EH information.
726 for (const HandlerInfo &HI : Handlers) {
727 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
728 HI.TimerGroupDescription, TimePassesIsEnabled);
729 HI.Handler->beginFunction(MF);
730 }
731
732 // Emit the prologue data.
733 if (F.hasPrologueData())
734 EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
735}
736
737/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
738/// function. This can be overridden by targets as required to do custom stuff.
739void AsmPrinter::EmitFunctionEntryLabel() {
740 CurrentFnSym->redefineIfPossible();
741
742 // The function label could have already been emitted if two symbols end up
743 // conflicting due to asm renaming. Detect this and emit an error.
744 if (CurrentFnSym->isVariable())
745 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
746 "' is a protected alias");
747 if (CurrentFnSym->isDefined())
748 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
749 "' label emitted multiple times to assembly file");
750
751 return OutStreamer->EmitLabel(CurrentFnSym);
752}
753
754/// emitComments - Pretty-print comments for instructions.
755static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
756 const MachineFunction *MF = MI.getMF();
757 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
758
759 // Check for spills and reloads
760
761 // We assume a single instruction only has a spill or reload, not
762 // both.
763 Optional<unsigned> Size;
764 if ((Size = MI.getRestoreSize(TII))) {
765 CommentOS << *Size << "-byte Reload\n";
766 } else if ((Size = MI.getFoldedRestoreSize(TII))) {
767 if (*Size)
768 CommentOS << *Size << "-byte Folded Reload\n";
769 } else if ((Size = MI.getSpillSize(TII))) {
770 CommentOS << *Size << "-byte Spill\n";
771 } else if ((Size = MI.getFoldedSpillSize(TII))) {
772 if (*Size)
773 CommentOS << *Size << "-byte Folded Spill\n";
774 }
775
776 // Check for spill-induced copies
777 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
778 CommentOS << " Reload Reuse\n";
779}
780
781/// emitImplicitDef - This method emits the specified machine instruction
782/// that is an implicit def.
783void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
784 unsigned RegNo = MI->getOperand(0).getReg();
785
786 SmallString<128> Str;
787 raw_svector_ostream OS(Str);
788 OS << "implicit-def: "
789 << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
790
791 OutStreamer->AddComment(OS.str());
792 OutStreamer->AddBlankLine();
793}
794
795static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
796 std::string Str;
797 raw_string_ostream OS(Str);
798 OS << "kill:";
799 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
800 const MachineOperand &Op = MI->getOperand(i);
801 assert(Op.isReg() && "KILL instruction must have only register operands")((Op.isReg() && "KILL instruction must have only register operands"
) ? static_cast<void> (0) : __assert_fail ("Op.isReg() && \"KILL instruction must have only register operands\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 801, __PRETTY_FUNCTION__))
;
802 OS << ' ' << (Op.isDef() ? "def " : "killed ")
803 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
804 }
805 AP.OutStreamer->AddComment(OS.str());
806 AP.OutStreamer->AddBlankLine();
807}
808
809/// emitDebugValueComment - This method handles the target-independent form
810/// of DBG_VALUE, returning true if it was able to do so. A false return
811/// means the target will need to handle MI in EmitInstruction.
812static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
813 // This code handles only the 4-operand target-independent form.
814 if (MI->getNumOperands() != 4)
815 return false;
816
817 SmallString<128> Str;
818 raw_svector_ostream OS(Str);
819 OS << "DEBUG_VALUE: ";
820
821 const DILocalVariable *V = MI->getDebugVariable();
822 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
823 StringRef Name = SP->getName();
824 if (!Name.empty())
825 OS << Name << ":";
826 }
827 OS << V->getName();
828 OS << " <- ";
829
830 // The second operand is only an offset if it's an immediate.
831 bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
832 int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0;
833 const DIExpression *Expr = MI->getDebugExpression();
834 if (Expr->getNumElements()) {
835 OS << '[';
836 bool NeedSep = false;
837 for (auto Op : Expr->expr_ops()) {
838 if (NeedSep)
839 OS << ", ";
840 else
841 NeedSep = true;
842 OS << dwarf::OperationEncodingString(Op.getOp());
843 for (unsigned I = 0; I < Op.getNumArgs(); ++I)
844 OS << ' ' << Op.getArg(I);
845 }
846 OS << "] ";
847 }
848
849 // Register or immediate value. Register 0 means undef.
850 if (MI->getOperand(0).isFPImm()) {
851 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
852 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
853 OS << (double)APF.convertToFloat();
854 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
855 OS << APF.convertToDouble();
856 } else {
857 // There is no good way to print long double. Convert a copy to
858 // double. Ah well, it's only a comment.
859 bool ignored;
860 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
861 &ignored);
862 OS << "(long double) " << APF.convertToDouble();
863 }
864 } else if (MI->getOperand(0).isImm()) {
865 OS << MI->getOperand(0).getImm();
866 } else if (MI->getOperand(0).isCImm()) {
867 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
868 } else {
869 unsigned Reg;
870 if (MI->getOperand(0).isReg()) {
871 Reg = MI->getOperand(0).getReg();
872 } else {
873 assert(MI->getOperand(0).isFI() && "Unknown operand type")((MI->getOperand(0).isFI() && "Unknown operand type"
) ? static_cast<void> (0) : __assert_fail ("MI->getOperand(0).isFI() && \"Unknown operand type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 873, __PRETTY_FUNCTION__))
;
874 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
875 Offset += TFI->getFrameIndexReference(*AP.MF,
876 MI->getOperand(0).getIndex(), Reg);
877 MemLoc = true;
878 }
879 if (Reg == 0) {
880 // Suppress offset, it is not meaningful here.
881 OS << "undef";
882 // NOTE: Want this comment at start of line, don't emit with AddComment.
883 AP.OutStreamer->emitRawComment(OS.str());
884 return true;
885 }
886 if (MemLoc)
887 OS << '[';
888 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
889 }
890
891 if (MemLoc)
892 OS << '+' << Offset << ']';
893
894 // NOTE: Want this comment at start of line, don't emit with AddComment.
895 AP.OutStreamer->emitRawComment(OS.str());
896 return true;
897}
898
899/// This method handles the target-independent form of DBG_LABEL, returning
900/// true if it was able to do so. A false return means the target will need
901/// to handle MI in EmitInstruction.
902static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
903 if (MI->getNumOperands() != 1)
904 return false;
905
906 SmallString<128> Str;
907 raw_svector_ostream OS(Str);
908 OS << "DEBUG_LABEL: ";
909
910 const DILabel *V = MI->getDebugLabel();
911 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
912 StringRef Name = SP->getName();
913 if (!Name.empty())
914 OS << Name << ":";
915 }
916 OS << V->getName();
917
918 // NOTE: Want this comment at start of line, don't emit with AddComment.
919 AP.OutStreamer->emitRawComment(OS.str());
920 return true;
921}
922
923AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() const {
924 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
925 MF->getFunction().needsUnwindTableEntry())
926 return CFI_M_EH;
927
928 if (MMI->hasDebugInfo())
929 return CFI_M_Debug;
930
931 return CFI_M_None;
932}
933
934bool AsmPrinter::needsSEHMoves() {
935 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
936}
937
938void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
939 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
940 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
941 ExceptionHandlingType != ExceptionHandling::ARM)
942 return;
943
944 if (needsCFIMoves() == CFI_M_None)
945 return;
946
947 // If there is no "real" instruction following this CFI instruction, skip
948 // emitting it; it would be beyond the end of the function's FDE range.
949 auto *MBB = MI.getParent();
950 auto I = std::next(MI.getIterator());
951 while (I != MBB->end() && I->isTransient())
952 ++I;
953 if (I == MBB->instr_end() &&
954 MBB->getReverseIterator() == MBB->getParent()->rbegin())
955 return;
956
957 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
958 unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
959 const MCCFIInstruction &CFI = Instrs[CFIIndex];
960 emitCFIInstruction(CFI);
961}
962
963void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
964 // The operands are the MCSymbol and the frame offset of the allocation.
965 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
966 int FrameOffset = MI.getOperand(1).getImm();
967
968 // Emit a symbol assignment.
969 OutStreamer->EmitAssignment(FrameAllocSym,
970 MCConstantExpr::create(FrameOffset, OutContext));
971}
972
973void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
974 if (!MF.getTarget().Options.EmitStackSizeSection)
975 return;
976
977 MCSection *StackSizeSection =
978 getObjFileLowering().getStackSizesSection(*getCurrentSection());
979 if (!StackSizeSection)
980 return;
981
982 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
983 // Don't emit functions with dynamic stack allocations.
984 if (FrameInfo.hasVarSizedObjects())
985 return;
986
987 OutStreamer->PushSection();
988 OutStreamer->SwitchSection(StackSizeSection);
989
990 const MCSymbol *FunctionSymbol = getFunctionBegin();
991 uint64_t StackSize = FrameInfo.getStackSize();
992 OutStreamer->EmitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
993 OutStreamer->EmitULEB128IntValue(StackSize);
994
995 OutStreamer->PopSection();
996}
997
998static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF,
999 MachineModuleInfo *MMI) {
1000 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo())
1001 return true;
1002
1003 // We might emit an EH table that uses function begin and end labels even if
1004 // we don't have any landingpads.
1005 if (!MF.getFunction().hasPersonalityFn())
1006 return false;
1007 return !isNoOpWithoutInvoke(
1008 classifyEHPersonality(MF.getFunction().getPersonalityFn()));
1009}
1010
1011/// EmitFunctionBody - This method emits the body and trailer for a
1012/// function.
1013void AsmPrinter::EmitFunctionBody() {
1014 EmitFunctionHeader();
1015
1016 // Emit target-specific gunk before the function body.
1017 EmitFunctionBodyStart();
1018
1019 bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
1020
1021 if (isVerbose()) {
1022 // Get MachineDominatorTree or compute it on the fly if it's unavailable
1023 MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1024 if (!MDT) {
1025 OwnedMDT = make_unique<MachineDominatorTree>();
1026 OwnedMDT->getBase().recalculate(*MF);
1027 MDT = OwnedMDT.get();
1028 }
1029
1030 // Get MachineLoopInfo or compute it on the fly if it's unavailable
1031 MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1032 if (!MLI) {
1033 OwnedMLI = make_unique<MachineLoopInfo>();
1034 OwnedMLI->getBase().analyze(MDT->getBase());
1035 MLI = OwnedMLI.get();
1036 }
1037 }
1038
1039 // Print out code for the function.
1040 bool HasAnyRealCode = false;
1041 int NumInstsInFunction = 0;
1042 for (auto &MBB : *MF) {
1043 // Print a label for the basic block.
1044 EmitBasicBlockStart(MBB);
1045 for (auto &MI : MBB) {
1046 // Print the assembly for the instruction.
1047 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1048 !MI.isDebugInstr()) {
1049 HasAnyRealCode = true;
1050 ++NumInstsInFunction;
1051 }
1052
1053 // If there is a pre-instruction symbol, emit a label for it here.
1054 if (MCSymbol *S = MI.getPreInstrSymbol())
1055 OutStreamer->EmitLabel(S);
1056
1057 if (ShouldPrintDebugScopes) {
1058 for (const HandlerInfo &HI : Handlers) {
1059 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1060 HI.TimerGroupName, HI.TimerGroupDescription,
1061 TimePassesIsEnabled);
1062 HI.Handler->beginInstruction(&MI);
1063 }
1064 }
1065
1066 if (isVerbose())
1067 emitComments(MI, OutStreamer->GetCommentOS());
1068
1069 switch (MI.getOpcode()) {
1070 case TargetOpcode::CFI_INSTRUCTION:
1071 emitCFIInstruction(MI);
1072 break;
1073 case TargetOpcode::LOCAL_ESCAPE:
1074 emitFrameAlloc(MI);
1075 break;
1076 case TargetOpcode::ANNOTATION_LABEL:
1077 case TargetOpcode::EH_LABEL:
1078 case TargetOpcode::GC_LABEL:
1079 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
1080 break;
1081 case TargetOpcode::INLINEASM:
1082 case TargetOpcode::INLINEASM_BR:
1083 EmitInlineAsm(&MI);
1084 break;
1085 case TargetOpcode::DBG_VALUE:
1086 if (isVerbose()) {
1087 if (!emitDebugValueComment(&MI, *this))
1088 EmitInstruction(&MI);
1089 }
1090 break;
1091 case TargetOpcode::DBG_LABEL:
1092 if (isVerbose()) {
1093 if (!emitDebugLabelComment(&MI, *this))
1094 EmitInstruction(&MI);
1095 }
1096 break;
1097 case TargetOpcode::IMPLICIT_DEF:
1098 if (isVerbose()) emitImplicitDef(&MI);
1099 break;
1100 case TargetOpcode::KILL:
1101 if (isVerbose()) emitKill(&MI, *this);
1102 break;
1103 default:
1104 EmitInstruction(&MI);
1105 break;
1106 }
1107
1108 // If there is a post-instruction symbol, emit a label for it here.
1109 if (MCSymbol *S = MI.getPostInstrSymbol())
1110 OutStreamer->EmitLabel(S);
1111
1112 if (ShouldPrintDebugScopes) {
1113 for (const HandlerInfo &HI : Handlers) {
1114 NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1115 HI.TimerGroupName, HI.TimerGroupDescription,
1116 TimePassesIsEnabled);
1117 HI.Handler->endInstruction();
1118 }
1119 }
1120 }
1121
1122 EmitBasicBlockEnd(MBB);
1123 }
1124
1125 EmittedInsts += NumInstsInFunction;
1126 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE"asm-printer", "InstructionCount",
1127 MF->getFunction().getSubprogram(),
1128 &MF->front());
1129 R << ore::NV("NumInstructions", NumInstsInFunction)
1130 << " instructions in function";
1131 ORE->emit(R);
1132
1133 // If the function is empty and the object file uses .subsections_via_symbols,
1134 // then we need to emit *something* to the function body to prevent the
1135 // labels from collapsing together. Just emit a noop.
1136 // Similarly, don't emit empty functions on Windows either. It can lead to
1137 // duplicate entries (two functions with the same RVA) in the Guard CF Table
1138 // after linking, causing the kernel not to load the binary:
1139 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1140 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1141 const Triple &TT = TM.getTargetTriple();
1142 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1143 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1144 MCInst Noop;
1145 MF->getSubtarget().getInstrInfo()->getNoop(Noop);
1146
1147 // Targets can opt-out of emitting the noop here by leaving the opcode
1148 // unspecified.
1149 if (Noop.getOpcode()) {
1150 OutStreamer->AddComment("avoids zero-length function");
1151 OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
1152 }
1153 }
1154
1155 const Function &F = MF->getFunction();
1156 for (const auto &BB : F) {
1157 if (!BB.hasAddressTaken())
1158 continue;
1159 MCSymbol *Sym = GetBlockAddressSymbol(&BB);
1160 if (Sym->isDefined())
1161 continue;
1162 OutStreamer->AddComment("Address of block that was removed by CodeGen");
1163 OutStreamer->EmitLabel(Sym);
1164 }
1165
1166 // Emit target-specific gunk after the function body.
1167 EmitFunctionBodyEnd();
1168
1169 if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) ||
1170 MAI->hasDotTypeDotSizeDirective()) {
1171 // Create a symbol for the end of function.
1172 CurrentFnEnd = createTempSymbol("func_end");
1173 OutStreamer->EmitLabel(CurrentFnEnd);
1174 }
1175
1176 // If the target wants a .size directive for the size of the function, emit
1177 // it.
1178 if (MAI->hasDotTypeDotSizeDirective()) {
1179 // We can get the size as difference between the function label and the
1180 // temp label.
1181 const MCExpr *SizeExp = MCBinaryExpr::createSub(
1182 MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1183 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
1184 OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1185 }
1186
1187 for (const HandlerInfo &HI : Handlers) {
1188 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1189 HI.TimerGroupDescription, TimePassesIsEnabled);
1190 HI.Handler->markFunctionEnd();
1191 }
1192
1193 // Print out jump tables referenced by the function.
1194 EmitJumpTableInfo();
1195
1196 // Emit post-function debug and/or EH information.
1197 for (const HandlerInfo &HI : Handlers) {
1198 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1199 HI.TimerGroupDescription, TimePassesIsEnabled);
1200 HI.Handler->endFunction(MF);
1201 }
1202
1203 // Emit section containing stack size metadata.
1204 emitStackSizeSection(*MF);
1205
1206 if (isVerbose())
1207 OutStreamer->GetCommentOS() << "-- End function\n";
1208
1209 OutStreamer->AddBlankLine();
1210}
1211
1212/// Compute the number of Global Variables that uses a Constant.
1213static unsigned getNumGlobalVariableUses(const Constant *C) {
1214 if (!C)
1215 return 0;
1216
1217 if (isa<GlobalVariable>(C))
1218 return 1;
1219
1220 unsigned NumUses = 0;
1221 for (auto *CU : C->users())
1222 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1223
1224 return NumUses;
1225}
1226
1227/// Only consider global GOT equivalents if at least one user is a
1228/// cstexpr inside an initializer of another global variables. Also, don't
1229/// handle cstexpr inside instructions. During global variable emission,
1230/// candidates are skipped and are emitted later in case at least one cstexpr
1231/// isn't replaced by a PC relative GOT entry access.
1232static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
1233 unsigned &NumGOTEquivUsers) {
1234 // Global GOT equivalents are unnamed private globals with a constant
1235 // pointer initializer to another global symbol. They must point to a
1236 // GlobalVariable or Function, i.e., as GlobalValue.
1237 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1238 !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1239 !isa<GlobalValue>(GV->getOperand(0)))
1240 return false;
1241
1242 // To be a got equivalent, at least one of its users need to be a constant
1243 // expression used by another global variable.
1244 for (auto *U : GV->users())
1245 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1246
1247 return NumGOTEquivUsers > 0;
1248}
1249
1250/// Unnamed constant global variables solely contaning a pointer to
1251/// another globals variable is equivalent to a GOT table entry; it contains the
1252/// the address of another symbol. Optimize it and replace accesses to these
1253/// "GOT equivalents" by using the GOT entry for the final global instead.
1254/// Compute GOT equivalent candidates among all global variables to avoid
1255/// emitting them if possible later on, after it use is replaced by a GOT entry
1256/// access.
1257void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
1258 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1259 return;
1260
1261 for (const auto &G : M.globals()) {
1262 unsigned NumGOTEquivUsers = 0;
1263 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1264 continue;
1265
1266 const MCSymbol *GOTEquivSym = getSymbol(&G);
1267 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1268 }
1269}
1270
1271/// Constant expressions using GOT equivalent globals may not be eligible
1272/// for PC relative GOT entry conversion, in such cases we need to emit such
1273/// globals we previously omitted in EmitGlobalVariable.
1274void AsmPrinter::emitGlobalGOTEquivs() {
1275 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1276 return;
1277
1278 SmallVector<const GlobalVariable *, 8> FailedCandidates;
1279 for (auto &I : GlobalGOTEquivs) {
1280 const GlobalVariable *GV = I.second.first;
1281 unsigned Cnt = I.second.second;
1282 if (Cnt)
1283 FailedCandidates.push_back(GV);
1284 }
1285 GlobalGOTEquivs.clear();
1286
1287 for (auto *GV : FailedCandidates)
1288 EmitGlobalVariable(GV);
1289}
1290
1291void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1292 const GlobalIndirectSymbol& GIS) {
1293 MCSymbol *Name = getSymbol(&GIS);
1294
1295 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1296 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1297 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1298 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1299 else
1300 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage")((GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"
) ? static_cast<void> (0) : __assert_fail ("GIS.hasLocalLinkage() && \"Invalid alias or ifunc linkage\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1300, __PRETTY_FUNCTION__))
;
1301
1302 bool IsFunction = GIS.getType()->getPointerElementType()->isFunctionTy();
1303
1304 // Treat bitcasts of functions as functions also. This is important at least
1305 // on WebAssembly where object and function addresses can't alias each other.
1306 if (!IsFunction)
1307 if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol()))
1308 if (CE->getOpcode() == Instruction::BitCast)
1309 IsFunction =
1310 CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1311
1312 // Set the symbol type to function if the alias has a function type.
1313 // This affects codegen when the aliasee is not a function.
1314 if (IsFunction) {
1315 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1316 if (isa<GlobalIFunc>(GIS))
1317 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
1318 }
1319
1320 EmitVisibility(Name, GIS.getVisibility());
1321
1322 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1323
1324 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1325 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
1326
1327 // Emit the directives as assignments aka .set:
1328 OutStreamer->EmitAssignment(Name, Expr);
1329
1330 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1331 // If the aliasee does not correspond to a symbol in the output, i.e. the
1332 // alias is not of an object or the aliased object is private, then set the
1333 // size of the alias symbol from the type of the alias. We don't do this in
1334 // other situations as the alias and aliasee having differing types but same
1335 // size may be intentional.
1336 const GlobalObject *BaseObject = GA->getBaseObject();
1337 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1338 (!BaseObject || BaseObject->hasPrivateLinkage())) {
1339 const DataLayout &DL = M.getDataLayout();
1340 uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1341 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1342 }
1343 }
1344}
1345
1346void AsmPrinter::emitRemarksSection(Module &M) {
1347 RemarkStreamer *RS = M.getContext().getRemarkStreamer();
1348 if (!RS)
1349 return;
1350
1351 // Switch to the right section: .remarks/__remarks.
1352 MCSection *RemarksSection =
1353 OutContext.getObjectFileInfo()->getRemarksSection();
1354 OutStreamer->SwitchSection(RemarksSection);
1355
1356 // Emit the magic number.
1357 OutStreamer->EmitBytes(remarks::Magic);
1358 // Explicitly emit a '\0'.
1359 OutStreamer->EmitIntValue(/*Value=*/0, /*Size=*/1);
1360
1361 // Emit the version number: little-endian uint64_t.
1362 // The version number is located at the offset 0x0 in the section.
1363 std::array<char, 8> Version;
1364 support::endian::write64le(Version.data(), remarks::Version);
1365 OutStreamer->EmitBinaryData(StringRef(Version.data(), Version.size()));
1366
1367 // Emit the string table in the section.
1368 // Note: we need to use the streamer here to emit it in the section. We can't
1369 // just use the serialize function with a raw_ostream because of the way
1370 // MCStreamers work.
1371 const remarks::StringTable &StrTab = RS->getStringTable();
1372 std::vector<StringRef> StrTabStrings = StrTab.serialize();
1373 uint64_t StrTabSize = StrTab.SerializedSize;
1374 // Emit the total size of the string table (the size itself excluded):
1375 // little-endian uint64_t.
1376 // The total size is located after the version number.
1377 std::array<char, 8> StrTabSizeBuf;
1378 support::endian::write64le(StrTabSizeBuf.data(), StrTabSize);
1379 OutStreamer->EmitBinaryData(
1380 StringRef(StrTabSizeBuf.data(), StrTabSizeBuf.size()));
1381 // Emit a list of null-terminated strings.
1382 // Note: the order is important here: the ID used in the remarks corresponds
1383 // to the position of the string in the section.
1384 for (StringRef Str : StrTabStrings) {
1385 OutStreamer->EmitBytes(Str);
1386 // Explicitly emit a '\0'.
1387 OutStreamer->EmitIntValue(/*Value=*/0, /*Size=*/1);
1388 }
1389
1390 // Emit the null-terminated absolute path to the remark file.
1391 // The path is located at the offset 0x4 in the section.
1392 StringRef FilenameRef = RS->getFilename();
1393 SmallString<128> Filename = FilenameRef;
1394 sys::fs::make_absolute(Filename);
1395 assert(!Filename.empty() && "The filename can't be empty.")((!Filename.empty() && "The filename can't be empty."
) ? static_cast<void> (0) : __assert_fail ("!Filename.empty() && \"The filename can't be empty.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1395, __PRETTY_FUNCTION__))
;
1396 OutStreamer->EmitBytes(Filename);
1397 // Explicitly emit a '\0'.
1398 OutStreamer->EmitIntValue(/*Value=*/0, /*Size=*/1);
1399}
1400
1401bool AsmPrinter::doFinalization(Module &M) {
1402 // Set the MachineFunction to nullptr so that we can catch attempted
1403 // accesses to MF specific features at the module level and so that
1404 // we can conditionalize accesses based on whether or not it is nullptr.
1405 MF = nullptr;
1406
1407 // Gather all GOT equivalent globals in the module. We really need two
1408 // passes over the globals: one to compute and another to avoid its emission
1409 // in EmitGlobalVariable, otherwise we would not be able to handle cases
1410 // where the got equivalent shows up before its use.
1411 computeGlobalGOTEquivs(M);
1412
1413 // Emit global variables.
1414 for (const auto &G : M.globals())
1415 EmitGlobalVariable(&G);
1
Calling 'AsmPrinter::EmitGlobalVariable'
1416
1417 // Emit remaining GOT equivalent globals.
1418 emitGlobalGOTEquivs();
1419
1420 // Emit visibility info for declarations
1421 for (const Function &F : M) {
1422 if (!F.isDeclarationForLinker())
1423 continue;
1424 GlobalValue::VisibilityTypes V = F.getVisibility();
1425 if (V == GlobalValue::DefaultVisibility)
1426 continue;
1427
1428 MCSymbol *Name = getSymbol(&F);
1429 EmitVisibility(Name, V, false);
1430 }
1431
1432 // Emit the remarks section contents.
1433 // FIXME: Figure out when is the safest time to emit this section. It should
1434 // not come after debug info.
1435 if (EnableRemarksSection)
1436 emitRemarksSection(M);
1437
1438 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1439
1440 TLOF.emitModuleMetadata(*OutStreamer, M);
1441
1442 if (TM.getTargetTriple().isOSBinFormatELF()) {
1443 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1444
1445 // Output stubs for external and common global variables.
1446 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
1447 if (!Stubs.empty()) {
1448 OutStreamer->SwitchSection(TLOF.getDataSection());
1449 const DataLayout &DL = M.getDataLayout();
1450
1451 EmitAlignment(Log2_32(DL.getPointerSize()));
1452 for (const auto &Stub : Stubs) {
1453 OutStreamer->EmitLabel(Stub.first);
1454 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1455 DL.getPointerSize());
1456 }
1457 }
1458 }
1459
1460 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1461 MachineModuleInfoCOFF &MMICOFF =
1462 MMI->getObjFileInfo<MachineModuleInfoCOFF>();
1463
1464 // Output stubs for external and common global variables.
1465 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
1466 if (!Stubs.empty()) {
1467 const DataLayout &DL = M.getDataLayout();
1468
1469 for (const auto &Stub : Stubs) {
1470 SmallString<256> SectionName = StringRef(".rdata$");
1471 SectionName += Stub.first->getName();
1472 OutStreamer->SwitchSection(OutContext.getCOFFSection(
1473 SectionName,
1474 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
1475 COFF::IMAGE_SCN_LNK_COMDAT,
1476 SectionKind::getReadOnly(), Stub.first->getName(),
1477 COFF::IMAGE_COMDAT_SELECT_ANY));
1478 EmitAlignment(Log2_32(DL.getPointerSize()));
1479 OutStreamer->EmitSymbolAttribute(Stub.first, MCSA_Global);
1480 OutStreamer->EmitLabel(Stub.first);
1481 OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1482 DL.getPointerSize());
1483 }
1484 }
1485 }
1486
1487 // Finalize debug and EH information.
1488 for (const HandlerInfo &HI : Handlers) {
1489 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1490 HI.TimerGroupDescription, TimePassesIsEnabled);
1491 HI.Handler->endModule();
1492 }
1493 Handlers.clear();
1494 DD = nullptr;
1495
1496 // If the target wants to know about weak references, print them all.
1497 if (MAI->getWeakRefDirective()) {
1498 // FIXME: This is not lazy, it would be nice to only print weak references
1499 // to stuff that is actually used. Note that doing so would require targets
1500 // to notice uses in operands (due to constant exprs etc). This should
1501 // happen with the MC stuff eventually.
1502
1503 // Print out module-level global objects here.
1504 for (const auto &GO : M.global_objects()) {
1505 if (!GO.hasExternalWeakLinkage())
1506 continue;
1507 OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1508 }
1509 }
1510
1511 OutStreamer->AddBlankLine();
1512
1513 // Print aliases in topological order, that is, for each alias a = b,
1514 // b must be printed before a.
1515 // This is because on some targets (e.g. PowerPC) linker expects aliases in
1516 // such an order to generate correct TOC information.
1517 SmallVector<const GlobalAlias *, 16> AliasStack;
1518 SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
1519 for (const auto &Alias : M.aliases()) {
1520 for (const GlobalAlias *Cur = &Alias; Cur;
1521 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1522 if (!AliasVisited.insert(Cur).second)
1523 break;
1524 AliasStack.push_back(Cur);
1525 }
1526 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1527 emitGlobalIndirectSymbol(M, *AncestorAlias);
1528 AliasStack.clear();
1529 }
1530 for (const auto &IFunc : M.ifuncs())
1531 emitGlobalIndirectSymbol(M, IFunc);
1532
1533 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1534 assert(MI && "AsmPrinter didn't require GCModuleInfo?")((MI && "AsmPrinter didn't require GCModuleInfo?") ? static_cast
<void> (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1534, __PRETTY_FUNCTION__))
;
1535 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1536 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1537 MP->finishAssembly(M, *MI, *this);
1538
1539 // Emit llvm.ident metadata in an '.ident' directive.
1540 EmitModuleIdents(M);
1541
1542 // Emit bytes for llvm.commandline metadata.
1543 EmitModuleCommandLines(M);
1544
1545 // Emit __morestack address if needed for indirect calls.
1546 if (MMI->usesMorestackAddr()) {
1547 unsigned Align = 1;
1548 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1549 getDataLayout(), SectionKind::getReadOnly(),
1550 /*C=*/nullptr, Align);
1551 OutStreamer->SwitchSection(ReadOnlySection);
1552
1553 MCSymbol *AddrSymbol =
1554 OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1555 OutStreamer->EmitLabel(AddrSymbol);
1556
1557 unsigned PtrSize = MAI->getCodePointerSize();
1558 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1559 PtrSize);
1560 }
1561
1562 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1563 // split-stack is used.
1564 if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
1565 OutStreamer->SwitchSection(
1566 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1567 if (MMI->hasNosplitStack())
1568 OutStreamer->SwitchSection(
1569 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1570 }
1571
1572 // If we don't have any trampolines, then we don't require stack memory
1573 // to be executable. Some targets have a directive to declare this.
1574 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1575 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1576 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1577 OutStreamer->SwitchSection(S);
1578
1579 if (TM.getTargetTriple().isOSBinFormatCOFF()) {
1580 // Emit /EXPORT: flags for each exported global as necessary.
1581 const auto &TLOF = getObjFileLowering();
1582 std::string Flags;
1583
1584 for (const GlobalValue &GV : M.global_values()) {
1585 raw_string_ostream OS(Flags);
1586 TLOF.emitLinkerFlagsForGlobal(OS, &GV);
1587 OS.flush();
1588 if (!Flags.empty()) {
1589 OutStreamer->SwitchSection(TLOF.getDrectveSection());
1590 OutStreamer->EmitBytes(Flags);
1591 }
1592 Flags.clear();
1593 }
1594
1595 // Emit /INCLUDE: flags for each used global as necessary.
1596 if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1597 assert(LU->hasInitializer() &&((LU->hasInitializer() && "expected llvm.used to have an initializer"
) ? static_cast<void> (0) : __assert_fail ("LU->hasInitializer() && \"expected llvm.used to have an initializer\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1598, __PRETTY_FUNCTION__))
1598 "expected llvm.used to have an initializer")((LU->hasInitializer() && "expected llvm.used to have an initializer"
) ? static_cast<void> (0) : __assert_fail ("LU->hasInitializer() && \"expected llvm.used to have an initializer\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1598, __PRETTY_FUNCTION__))
;
1599 assert(isa<ArrayType>(LU->getValueType()) &&((isa<ArrayType>(LU->getValueType()) && "expected llvm.used to be an array type"
) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(LU->getValueType()) && \"expected llvm.used to be an array type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1600, __PRETTY_FUNCTION__))
1600 "expected llvm.used to be an array type")((isa<ArrayType>(LU->getValueType()) && "expected llvm.used to be an array type"
) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(LU->getValueType()) && \"expected llvm.used to be an array type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1600, __PRETTY_FUNCTION__))
;
1601 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1602 for (const Value *Op : A->operands()) {
1603 const auto *GV =
1604 cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
1605 // Global symbols with internal or private linkage are not visible to
1606 // the linker, and thus would cause an error when the linker tried to
1607 // preserve the symbol due to the `/include:` directive.
1608 if (GV->hasLocalLinkage())
1609 continue;
1610
1611 raw_string_ostream OS(Flags);
1612 TLOF.emitLinkerFlagsForUsed(OS, GV);
1613 OS.flush();
1614
1615 if (!Flags.empty()) {
1616 OutStreamer->SwitchSection(TLOF.getDrectveSection());
1617 OutStreamer->EmitBytes(Flags);
1618 }
1619 Flags.clear();
1620 }
1621 }
1622 }
1623 }
1624
1625 if (TM.Options.EmitAddrsig) {
1626 // Emit address-significance attributes for all globals.
1627 OutStreamer->EmitAddrsig();
1628 for (const GlobalValue &GV : M.global_values())
1629 if (!GV.use_empty() && !GV.isThreadLocal() &&
1630 !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
1631 !GV.hasAtLeastLocalUnnamedAddr())
1632 OutStreamer->EmitAddrsigSym(getSymbol(&GV));
1633 }
1634
1635 // Allow the target to emit any magic that it wants at the end of the file,
1636 // after everything else has gone out.
1637 EmitEndOfAsmFile(M);
1638
1639 MMI = nullptr;
1640
1641 OutStreamer->Finish();
1642 OutStreamer->reset();
1643 OwnedMLI.reset();
1644 OwnedMDT.reset();
1645
1646 return false;
1647}
1648
1649MCSymbol *AsmPrinter::getCurExceptionSym() {
1650 if (!CurExceptionSym)
1651 CurExceptionSym = createTempSymbol("exception");
1652 return CurExceptionSym;
1653}
1654
1655void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1656 this->MF = &MF;
1657 // Get the function symbol.
1658 CurrentFnSym = getSymbol(&MF.getFunction());
1659 CurrentFnSymForSize = CurrentFnSym;
1660 CurrentFnBegin = nullptr;
1661 CurExceptionSym = nullptr;
1662 bool NeedsLocalForSize = MAI->needsLocalForSize();
1663 if (needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
1664 MF.getTarget().Options.EmitStackSizeSection) {
1665 CurrentFnBegin = createTempSymbol("func_begin");
1666 if (NeedsLocalForSize)
1667 CurrentFnSymForSize = CurrentFnBegin;
1668 }
1669
1670 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1671}
1672
1673namespace {
1674
1675// Keep track the alignment, constpool entries per Section.
1676 struct SectionCPs {
1677 MCSection *S;
1678 unsigned Alignment;
1679 SmallVector<unsigned, 4> CPEs;
1680
1681 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1682 };
1683
1684} // end anonymous namespace
1685
1686/// EmitConstantPool - Print to the current output stream assembly
1687/// representations of the constants in the constant pool MCP. This is
1688/// used to print out constants which have been "spilled to memory" by
1689/// the code generator.
1690void AsmPrinter::EmitConstantPool() {
1691 const MachineConstantPool *MCP = MF->getConstantPool();
1692 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1693 if (CP.empty()) return;
1694
1695 // Calculate sections for constant pool entries. We collect entries to go into
1696 // the same section together to reduce amount of section switch statements.
1697 SmallVector<SectionCPs, 4> CPSections;
1698 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1699 const MachineConstantPoolEntry &CPE = CP[i];
1700 unsigned Align = CPE.getAlignment();
1701
1702 SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1703
1704 const Constant *C = nullptr;
1705 if (!CPE.isMachineConstantPoolEntry())
1706 C = CPE.Val.ConstVal;
1707
1708 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
1709 Kind, C, Align);
1710
1711 // The number of sections are small, just do a linear search from the
1712 // last section to the first.
1713 bool Found = false;
1714 unsigned SecIdx = CPSections.size();
1715 while (SecIdx != 0) {
1716 if (CPSections[--SecIdx].S == S) {
1717 Found = true;
1718 break;
1719 }
1720 }
1721 if (!Found) {
1722 SecIdx = CPSections.size();
1723 CPSections.push_back(SectionCPs(S, Align));
1724 }
1725
1726 if (Align > CPSections[SecIdx].Alignment)
1727 CPSections[SecIdx].Alignment = Align;
1728 CPSections[SecIdx].CPEs.push_back(i);
1729 }
1730
1731 // Now print stuff into the calculated sections.
1732 const MCSection *CurSection = nullptr;
1733 unsigned Offset = 0;
1734 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1735 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1736 unsigned CPI = CPSections[i].CPEs[j];
1737 MCSymbol *Sym = GetCPISymbol(CPI);
1738 if (!Sym->isUndefined())
1739 continue;
1740
1741 if (CurSection != CPSections[i].S) {
1742 OutStreamer->SwitchSection(CPSections[i].S);
1743 EmitAlignment(Log2_32(CPSections[i].Alignment));
1744 CurSection = CPSections[i].S;
1745 Offset = 0;
1746 }
1747
1748 MachineConstantPoolEntry CPE = CP[CPI];
1749
1750 // Emit inter-object padding for alignment.
1751 unsigned AlignMask = CPE.getAlignment() - 1;
1752 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1753 OutStreamer->EmitZeros(NewOffset - Offset);
1754
1755 Type *Ty = CPE.getType();
1756 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1757
1758 OutStreamer->EmitLabel(Sym);
1759 if (CPE.isMachineConstantPoolEntry())
1760 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1761 else
1762 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
1763 }
1764 }
1765}
1766
1767/// EmitJumpTableInfo - Print assembly representations of the jump tables used
1768/// by the current function to the current output stream.
1769void AsmPrinter::EmitJumpTableInfo() {
1770 const DataLayout &DL = MF->getDataLayout();
1771 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1772 if (!MJTI) return;
1773 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1774 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1775 if (JT.empty()) return;
1776
1777 // Pick the directive to use to print the jump table entries, and switch to
1778 // the appropriate section.
1779 const Function &F = MF->getFunction();
1780 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1781 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1782 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
1783 F);
1784 if (JTInDiffSection) {
1785 // Drop it in the readonly section.
1786 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
1787 OutStreamer->SwitchSection(ReadOnlySection);
1788 }
1789
1790 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
1791
1792 // Jump tables in code sections are marked with a data_region directive
1793 // where that's supported.
1794 if (!JTInDiffSection)
1795 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1796
1797 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1798 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1799
1800 // If this jump table was deleted, ignore it.
1801 if (JTBBs.empty()) continue;
1802
1803 // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1804 /// emit a .set directive for each unique entry.
1805 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1806 MAI->doesSetDirectiveSuppressReloc()) {
1807 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1808 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1809 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1810 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1811 const MachineBasicBlock *MBB = JTBBs[ii];
1812 if (!EmittedSets.insert(MBB).second)
1813 continue;
1814
1815 // .set LJTSet, LBB32-base
1816 const MCExpr *LHS =
1817 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1818 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1819 MCBinaryExpr::createSub(LHS, Base,
1820 OutContext));
1821 }
1822 }
1823
1824 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1825 // before each jump table. The first label is never referenced, but tells
1826 // the assembler and linker the extents of the jump table object. The
1827 // second label is actually referenced by the code.
1828 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1829 // FIXME: This doesn't have to have any specific name, just any randomly
1830 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1831 OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1832
1833 OutStreamer->EmitLabel(GetJTISymbol(JTI));
1834
1835 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1836 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1837 }
1838 if (!JTInDiffSection)
1839 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1840}
1841
1842/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1843/// current stream.
1844void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1845 const MachineBasicBlock *MBB,
1846 unsigned UID) const {
1847 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block")((MBB && MBB->getNumber() >= 0 && "Invalid basic block"
) ? static_cast<void> (0) : __assert_fail ("MBB && MBB->getNumber() >= 0 && \"Invalid basic block\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1847, __PRETTY_FUNCTION__))
;
1848 const MCExpr *Value = nullptr;
1849 switch (MJTI->getEntryKind()) {
1850 case MachineJumpTableInfo::EK_Inline:
1851 llvm_unreachable("Cannot emit EK_Inline jump table entry")::llvm::llvm_unreachable_internal("Cannot emit EK_Inline jump table entry"
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1851)
;
1852 case MachineJumpTableInfo::EK_Custom32:
1853 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
1854 MJTI, MBB, UID, OutContext);
1855 break;
1856 case MachineJumpTableInfo::EK_BlockAddress:
1857 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1858 // .word LBB123
1859 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1860 break;
1861 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1862 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1863 // with a relocation as gp-relative, e.g.:
1864 // .gprel32 LBB123
1865 MCSymbol *MBBSym = MBB->getSymbol();
1866 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1867 return;
1868 }
1869
1870 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1871 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1872 // with a relocation as gp-relative, e.g.:
1873 // .gpdword LBB123
1874 MCSymbol *MBBSym = MBB->getSymbol();
1875 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1876 return;
1877 }
1878
1879 case MachineJumpTableInfo::EK_LabelDifference32: {
1880 // Each entry is the address of the block minus the address of the jump
1881 // table. This is used for PIC jump tables where gprel32 is not supported.
1882 // e.g.:
1883 // .word LBB123 - LJTI1_2
1884 // If the .set directive avoids relocations, this is emitted as:
1885 // .set L4_5_set_123, LBB123 - LJTI1_2
1886 // .word L4_5_set_123
1887 if (MAI->doesSetDirectiveSuppressReloc()) {
1888 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1889 OutContext);
1890 break;
1891 }
1892 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1893 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1894 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1895 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1896 break;
1897 }
1898 }
1899
1900 assert(Value && "Unknown entry kind!")((Value && "Unknown entry kind!") ? static_cast<void
> (0) : __assert_fail ("Value && \"Unknown entry kind!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1900, __PRETTY_FUNCTION__))
;
1901
1902 unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1903 OutStreamer->EmitValue(Value, EntrySize);
1904}
1905
1906/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1907/// special global used by LLVM. If so, emit it and return true, otherwise
1908/// do nothing and return false.
1909bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1910 if (GV->getName() == "llvm.used") {
1911 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1912 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1913 return true;
1914 }
1915
1916 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1917 if (GV->getSection() == "llvm.metadata" ||
1918 GV->hasAvailableExternallyLinkage())
1919 return true;
1920
1921 if (!GV->hasAppendingLinkage()) return false;
1922
1923 assert(GV->hasInitializer() && "Not a special LLVM global!")((GV->hasInitializer() && "Not a special LLVM global!"
) ? static_cast<void> (0) : __assert_fail ("GV->hasInitializer() && \"Not a special LLVM global!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 1923, __PRETTY_FUNCTION__))
;
1924
1925 if (GV->getName() == "llvm.global_ctors") {
1926 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1927 /* isCtor */ true);
1928
1929 return true;
1930 }
1931
1932 if (GV->getName() == "llvm.global_dtors") {
1933 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1934 /* isCtor */ false);
1935
1936 return true;
1937 }
1938
1939 report_fatal_error("unknown special variable");
1940}
1941
1942/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1943/// global in the specified llvm.used list.
1944void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1945 // Should be an array of 'i8*'.
1946 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1947 const GlobalValue *GV =
1948 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1949 if (GV)
1950 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1951 }
1952}
1953
1954namespace {
1955
1956struct Structor {
1957 int Priority = 0;
1958 Constant *Func = nullptr;
1959 GlobalValue *ComdatKey = nullptr;
1960
1961 Structor() = default;
1962};
1963
1964} // end anonymous namespace
1965
1966/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1967/// priority.
1968void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1969 bool isCtor) {
1970 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the
1971 // init priority.
1972 if (!isa<ConstantArray>(List)) return;
1973
1974 // Sanity check the structors list.
1975 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1976 if (!InitList) return; // Not an array!
1977 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1978 if (!ETy || ETy->getNumElements() != 3 ||
1979 !isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1980 !isa<PointerType>(ETy->getTypeAtIndex(1U)) ||
1981 !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1982 return; // Not (int, ptr, ptr).
1983
1984 // Gather the structors in a form that's convenient for sorting by priority.
1985 SmallVector<Structor, 8> Structors;
1986 for (Value *O : InitList->operands()) {
1987 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
1988 if (!CS) continue; // Malformed.
1989 if (CS->getOperand(1)->isNullValue())
1990 break; // Found a null terminator, skip the rest.
1991 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1992 if (!Priority) continue; // Malformed.
1993 Structors.push_back(Structor());
1994 Structor &S = Structors.back();
1995 S.Priority = Priority->getLimitedValue(65535);
1996 S.Func = CS->getOperand(1);
1997 if (!CS->getOperand(2)->isNullValue())
1998 S.ComdatKey =
1999 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2000 }
2001
2002 // Emit the function pointers in the target-specific order
2003 unsigned Align = Log2_32(DL.getPointerPrefAlignment());
2004 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2005 return L.Priority < R.Priority;
2006 });
2007 for (Structor &S : Structors) {
2008 const TargetLoweringObjectFile &Obj = getObjFileLowering();
2009 const MCSymbol *KeySym = nullptr;
2010 if (GlobalValue *GV = S.ComdatKey) {
2011 if (GV->isDeclarationForLinker())
2012 // If the associated variable is not defined in this module
2013 // (it might be available_externally, or have been an
2014 // available_externally definition that was dropped by the
2015 // EliminateAvailableExternally pass), some other TU
2016 // will provide its dynamic initializer.
2017 continue;
2018
2019 KeySym = getSymbol(GV);
2020 }
2021 MCSection *OutputSection =
2022 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2023 : Obj.getStaticDtorSection(S.Priority, KeySym));
2024 OutStreamer->SwitchSection(OutputSection);
2025 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2026 EmitAlignment(Align);
2027 EmitXXStructor(DL, S.Func);
2028 }
2029}
2030
2031void AsmPrinter::EmitModuleIdents(Module &M) {
2032 if (!MAI->hasIdentDirective())
2033 return;
2034
2035 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2036 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2037 const MDNode *N = NMD->getOperand(i);
2038 assert(N->getNumOperands() == 1 &&((N->getNumOperands() == 1 && "llvm.ident metadata entry can have only one operand"
) ? static_cast<void> (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.ident metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2039, __PRETTY_FUNCTION__))
2039 "llvm.ident metadata entry can have only one operand")((N->getNumOperands() == 1 && "llvm.ident metadata entry can have only one operand"
) ? static_cast<void> (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.ident metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2039, __PRETTY_FUNCTION__))
;
2040 const MDString *S = cast<MDString>(N->getOperand(0));
2041 OutStreamer->EmitIdent(S->getString());
2042 }
2043 }
2044}
2045
2046void AsmPrinter::EmitModuleCommandLines(Module &M) {
2047 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
2048 if (!CommandLine)
2049 return;
2050
2051 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2052 if (!NMD || !NMD->getNumOperands())
2053 return;
2054
2055 OutStreamer->PushSection();
2056 OutStreamer->SwitchSection(CommandLine);
2057 OutStreamer->EmitZeros(1);
2058 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2059 const MDNode *N = NMD->getOperand(i);
2060 assert(N->getNumOperands() == 1 &&((N->getNumOperands() == 1 && "llvm.commandline metadata entry can have only one operand"
) ? static_cast<void> (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.commandline metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2061, __PRETTY_FUNCTION__))
2061 "llvm.commandline metadata entry can have only one operand")((N->getNumOperands() == 1 && "llvm.commandline metadata entry can have only one operand"
) ? static_cast<void> (0) : __assert_fail ("N->getNumOperands() == 1 && \"llvm.commandline metadata entry can have only one operand\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2061, __PRETTY_FUNCTION__))
;
2062 const MDString *S = cast<MDString>(N->getOperand(0));
2063 OutStreamer->EmitBytes(S->getString());
2064 OutStreamer->EmitZeros(1);
2065 }
2066 OutStreamer->PopSection();
2067}
2068
2069//===--------------------------------------------------------------------===//
2070// Emission and print routines
2071//
2072
2073/// Emit a byte directive and value.
2074///
2075void AsmPrinter::emitInt8(int Value) const {
2076 OutStreamer->EmitIntValue(Value, 1);
2077}
2078
2079/// Emit a short directive and value.
2080void AsmPrinter::emitInt16(int Value) const {
2081 OutStreamer->EmitIntValue(Value, 2);
2082}
2083
2084/// Emit a long directive and value.
2085void AsmPrinter::emitInt32(int Value) const {
2086 OutStreamer->EmitIntValue(Value, 4);
2087}
2088
2089/// Emit a long long directive and value.
2090void AsmPrinter::emitInt64(uint64_t Value) const {
2091 OutStreamer->EmitIntValue(Value, 8);
2092}
2093
2094/// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2095/// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2096/// .set if it avoids relocations.
2097void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
2098 unsigned Size) const {
2099 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2100}
2101
2102/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2103/// where the size in bytes of the directive is specified by Size and Label
2104/// specifies the label. This implicitly uses .set if it is available.
2105void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
2106 unsigned Size,
2107 bool IsSectionRelative) const {
2108 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2109 OutStreamer->EmitCOFFSecRel32(Label, Offset);
2110 if (Size > 4)
2111 OutStreamer->EmitZeros(Size - 4);
2112 return;
2113 }
2114
2115 // Emit Label+Offset (or just Label if Offset is zero)
2116 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2117 if (Offset)
2118 Expr = MCBinaryExpr::createAdd(
2119 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2120
2121 OutStreamer->EmitValue(Expr, Size);
2122}
2123
2124//===----------------------------------------------------------------------===//
2125
2126// EmitAlignment - Emit an alignment directive to the specified power of
2127// two boundary. For example, if you pass in 3 here, you will get an 8
2128// byte alignment. If a global value is specified, and if that global has
2129// an explicit alignment requested, it will override the alignment request
2130// if required for correctness.
2131void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
2132 if (GV)
2133 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
2134
2135 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
2136
2137 assert(NumBits <((NumBits < static_cast<unsigned>(std::numeric_limits
<unsigned>::digits) && "undefined behavior") ? static_cast
<void> (0) : __assert_fail ("NumBits < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2139, __PRETTY_FUNCTION__))
2138 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&((NumBits < static_cast<unsigned>(std::numeric_limits
<unsigned>::digits) && "undefined behavior") ? static_cast
<void> (0) : __assert_fail ("NumBits < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2139, __PRETTY_FUNCTION__))
2139 "undefined behavior")((NumBits < static_cast<unsigned>(std::numeric_limits
<unsigned>::digits) && "undefined behavior") ? static_cast
<void> (0) : __assert_fail ("NumBits < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2139, __PRETTY_FUNCTION__))
;
2140 if (getCurrentSection()->getKind().isText())
2141 OutStreamer->EmitCodeAlignment(1u << NumBits);
2142 else
2143 OutStreamer->EmitValueToAlignment(1u << NumBits);
2144}
2145
2146//===----------------------------------------------------------------------===//
2147// Constant emission.
2148//===----------------------------------------------------------------------===//
2149
2150const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
2151 MCContext &Ctx = OutContext;
2152
2153 if (CV->isNullValue() || isa<UndefValue>(CV))
2154 return MCConstantExpr::create(0, Ctx);
2155
2156 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2157 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2158
2159 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2160 return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2161
2162 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2163 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
2164
2165 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2166 if (!CE) {
2167 llvm_unreachable("Unknown constant value to lower!")::llvm::llvm_unreachable_internal("Unknown constant value to lower!"
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2167)
;
2168 }
2169
2170 switch (CE->getOpcode()) {
2171 default:
2172 // If the code isn't optimized, there may be outstanding folding
2173 // opportunities. Attempt to fold the expression using DataLayout as a
2174 // last resort before giving up.
2175 if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2176 if (C != CE)
2177 return lowerConstant(C);
2178
2179 // Otherwise report the problem to the user.
2180 {
2181 std::string S;
2182 raw_string_ostream OS(S);
2183 OS << "Unsupported expression in static initializer: ";
2184 CE->printAsOperand(OS, /*PrintType=*/false,
2185 !MF ? nullptr : MF->getFunction().getParent());
2186 report_fatal_error(OS.str());
2187 }
2188 case Instruction::GetElementPtr: {
2189 // Generate a symbolic expression for the byte address
2190 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2191 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2192
2193 const MCExpr *Base = lowerConstant(CE->getOperand(0));
2194 if (!OffsetAI)
2195 return Base;
2196
2197 int64_t Offset = OffsetAI.getSExtValue();
2198 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2199 Ctx);
2200 }
2201
2202 case Instruction::Trunc:
2203 // We emit the value and depend on the assembler to truncate the generated
2204 // expression properly. This is important for differences between
2205 // blockaddress labels. Since the two labels are in the same function, it
2206 // is reasonable to treat their delta as a 32-bit value.
2207 LLVM_FALLTHROUGH[[clang::fallthrough]];
2208 case Instruction::BitCast:
2209 return lowerConstant(CE->getOperand(0));
2210
2211 case Instruction::IntToPtr: {
2212 const DataLayout &DL = getDataLayout();
2213
2214 // Handle casts to pointers by changing them into casts to the appropriate
2215 // integer type. This promotes constant folding and simplifies this code.
2216 Constant *Op = CE->getOperand(0);
2217 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2218 false/*ZExt*/);
2219 return lowerConstant(Op);
2220 }
2221
2222 case Instruction::PtrToInt: {
2223 const DataLayout &DL = getDataLayout();
2224
2225 // Support only foldable casts to/from pointers that can be eliminated by
2226 // changing the pointer to the appropriately sized integer type.
2227 Constant *Op = CE->getOperand(0);
2228 Type *Ty = CE->getType();
2229
2230 const MCExpr *OpExpr = lowerConstant(Op);
2231
2232 // We can emit the pointer value into this slot if the slot is an
2233 // integer slot equal to the size of the pointer.
2234 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2235 return OpExpr;
2236
2237 // Otherwise the pointer is smaller than the resultant integer, mask off
2238 // the high bits so we are sure to get a proper truncation if the input is
2239 // a constant expr.
2240 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2241 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2242 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2243 }
2244
2245 case Instruction::Sub: {
2246 GlobalValue *LHSGV;
2247 APInt LHSOffset;
2248 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2249 getDataLayout())) {
2250 GlobalValue *RHSGV;
2251 APInt RHSOffset;
2252 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2253 getDataLayout())) {
2254 const MCExpr *RelocExpr =
2255 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2256 if (!RelocExpr)
2257 RelocExpr = MCBinaryExpr::createSub(
2258 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
2259 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2260 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2261 if (Addend != 0)
2262 RelocExpr = MCBinaryExpr::createAdd(
2263 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2264 return RelocExpr;
2265 }
2266 }
2267 }
2268 // else fallthrough
2269 LLVM_FALLTHROUGH[[clang::fallthrough]];
2270
2271 // The MC library also has a right-shift operator, but it isn't consistently
2272 // signed or unsigned between different targets.
2273 case Instruction::Add:
2274 case Instruction::Mul:
2275 case Instruction::SDiv:
2276 case Instruction::SRem:
2277 case Instruction::Shl:
2278 case Instruction::And:
2279 case Instruction::Or:
2280 case Instruction::Xor: {
2281 const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2282 const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2283 switch (CE->getOpcode()) {
2284 default: llvm_unreachable("Unknown binary operator constant cast expr")::llvm::llvm_unreachable_internal("Unknown binary operator constant cast expr"
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2284)
;
2285 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2286 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2287 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2288 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2289 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2290 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2291 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2292 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2293 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2294 }
2295 }
2296 }
2297}
2298
2299static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2300 AsmPrinter &AP,
2301 const Constant *BaseCV = nullptr,
2302 uint64_t Offset = 0);
2303
2304static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2305static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2306
2307/// isRepeatedByteSequence - Determine whether the given value is
2308/// composed of a repeated sequence of identical bytes and return the
2309/// byte value. If it is not a repeated sequence, return -1.
2310static int isRepeatedByteSequence(const ConstantDataSequential *V) {
2311 StringRef Data = V->getRawDataValues();
2312 assert(!Data.empty() && "Empty aggregates should be CAZ node")((!Data.empty() && "Empty aggregates should be CAZ node"
) ? static_cast<void> (0) : __assert_fail ("!Data.empty() && \"Empty aggregates should be CAZ node\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2312, __PRETTY_FUNCTION__))
;
2313 char C = Data[0];
2314 for (unsigned i = 1, e = Data.size(); i != e; ++i)
2315 if (Data[i] != C) return -1;
2316 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2317}
2318
2319/// isRepeatedByteSequence - Determine whether the given value is
2320/// composed of a repeated sequence of identical bytes and return the
2321/// byte value. If it is not a repeated sequence, return -1.
2322static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2323 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2324 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2325 assert(Size % 8 == 0)((Size % 8 == 0) ? static_cast<void> (0) : __assert_fail
("Size % 8 == 0", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2325, __PRETTY_FUNCTION__))
;
2326
2327 // Extend the element to take zero padding into account.
2328 APInt Value = CI->getValue().zextOrSelf(Size);
2329 if (!Value.isSplat(8))
2330 return -1;
2331
2332 return Value.zextOrTrunc(8).getZExtValue();
2333 }
2334 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2335 // Make sure all array elements are sequences of the same repeated
2336 // byte.
2337 assert(CA->getNumOperands() != 0 && "Should be a CAZ")((CA->getNumOperands() != 0 && "Should be a CAZ") ?
static_cast<void> (0) : __assert_fail ("CA->getNumOperands() != 0 && \"Should be a CAZ\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2337, __PRETTY_FUNCTION__))
;
2338 Constant *Op0 = CA->getOperand(0);
2339 int Byte = isRepeatedByteSequence(Op0, DL);
2340 if (Byte == -1)
2341 return -1;
2342
2343 // All array elements must be equal.
2344 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2345 if (CA->getOperand(i) != Op0)
2346 return -1;
2347 return Byte;
2348 }
2349
2350 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2351 return isRepeatedByteSequence(CDS);
2352
2353 return -1;
2354}
2355
2356static void emitGlobalConstantDataSequential(const DataLayout &DL,
2357 const ConstantDataSequential *CDS,
2358 AsmPrinter &AP) {
2359 // See if we can aggregate this into a .fill, if so, emit it as such.
2360 int Value = isRepeatedByteSequence(CDS, DL);
2361 if (Value != -1) {
2362 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2363 // Don't emit a 1-byte object as a .fill.
2364 if (Bytes > 1)
2365 return AP.OutStreamer->emitFill(Bytes, Value);
2366 }
2367
2368 // If this can be emitted with .ascii/.asciz, emit it as such.
2369 if (CDS->isString())
2370 return AP.OutStreamer->EmitBytes(CDS->getAsString());
2371
2372 // Otherwise, emit the values in successive locations.
2373 unsigned ElementByteSize = CDS->getElementByteSize();
2374 if (isa<IntegerType>(CDS->getElementType())) {
2375 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2376 if (AP.isVerbose())
2377 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64"l" "x" "\n",
2378 CDS->getElementAsInteger(i));
2379 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
2380 ElementByteSize);
2381 }
2382 } else {
2383 Type *ET = CDS->getElementType();
2384 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2385 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
2386 }
2387
2388 unsigned Size = DL.getTypeAllocSize(CDS->getType());
2389 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2390 CDS->getNumElements();
2391 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!")((EmittedSize <= Size && "Size cannot be less than EmittedSize!"
) ? static_cast<void> (0) : __assert_fail ("EmittedSize <= Size && \"Size cannot be less than EmittedSize!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2391, __PRETTY_FUNCTION__))
;
2392 if (unsigned Padding = Size - EmittedSize)
2393 AP.OutStreamer->EmitZeros(Padding);
2394}
2395
2396static void emitGlobalConstantArray(const DataLayout &DL,
2397 const ConstantArray *CA, AsmPrinter &AP,
2398 const Constant *BaseCV, uint64_t Offset) {
2399 // See if we can aggregate some values. Make sure it can be
2400 // represented as a series of bytes of the constant value.
2401 int Value = isRepeatedByteSequence(CA, DL);
2402
2403 if (Value != -1) {
2404 uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2405 AP.OutStreamer->emitFill(Bytes, Value);
2406 }
2407 else {
2408 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2409 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2410 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2411 }
2412 }
2413}
2414
2415static void emitGlobalConstantVector(const DataLayout &DL,
2416 const ConstantVector *CV, AsmPrinter &AP) {
2417 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2418 emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2419
2420 unsigned Size = DL.getTypeAllocSize(CV->getType());
2421 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2422 CV->getType()->getNumElements();
2423 if (unsigned Padding = Size - EmittedSize)
2424 AP.OutStreamer->EmitZeros(Padding);
2425}
2426
2427static void emitGlobalConstantStruct(const DataLayout &DL,
2428 const ConstantStruct *CS, AsmPrinter &AP,
2429 const Constant *BaseCV, uint64_t Offset) {
2430 // Print the fields in successive locations. Pad to align if needed!
2431 unsigned Size = DL.getTypeAllocSize(CS->getType());
2432 const StructLayout *Layout = DL.getStructLayout(CS->getType());
2433 uint64_t SizeSoFar = 0;
2434 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2435 const Constant *Field = CS->getOperand(i);
2436
2437 // Print the actual field value.
2438 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2439
2440 // Check if padding is needed and insert one or more 0s.
2441 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2442 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2443 - Layout->getElementOffset(i)) - FieldSize;
2444 SizeSoFar += FieldSize + PadSize;
2445
2446 // Insert padding - this may include padding to increase the size of the
2447 // current field up to the ABI size (if the struct is not packed) as well
2448 // as padding to ensure that the next field starts at the right offset.
2449 AP.OutStreamer->EmitZeros(PadSize);
2450 }
2451 assert(SizeSoFar == Layout->getSizeInBytes() &&((SizeSoFar == Layout->getSizeInBytes() && "Layout of constant struct may be incorrect!"
) ? static_cast<void> (0) : __assert_fail ("SizeSoFar == Layout->getSizeInBytes() && \"Layout of constant struct may be incorrect!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2452, __PRETTY_FUNCTION__))
2452 "Layout of constant struct may be incorrect!")((SizeSoFar == Layout->getSizeInBytes() && "Layout of constant struct may be incorrect!"
) ? static_cast<void> (0) : __assert_fail ("SizeSoFar == Layout->getSizeInBytes() && \"Layout of constant struct may be incorrect!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2452, __PRETTY_FUNCTION__))
;
2453}
2454
2455static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2456 APInt API = APF.bitcastToAPInt();
2457
2458 // First print a comment with what we think the original floating-point value
2459 // should have been.
2460 if (AP.isVerbose()) {
28
Assuming the condition is true
29
Taking true branch
2461 SmallString<8> StrVal;
2462 APF.toString(StrVal);
2463
2464 if (ET)
30
Assuming 'ET' is null
31
Assuming pointer value is null
32
Taking false branch
2465 ET->print(AP.OutStreamer->GetCommentOS());
2466 else
2467 AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2468 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2469 }
2470
2471 // Now iterate through the APInt chunks, emitting them in endian-correct
2472 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2473 // floats).
2474 unsigned NumBytes = API.getBitWidth() / 8;
2475 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2476 const uint64_t *p = API.getRawData();
2477
2478 // PPC's long double has odd notions of endianness compared to how LLVM
2479 // handles it: p[0] goes first for *big* endian on PPC.
2480 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
33
Assuming the condition is true
34
Called C++ object pointer is null
2481 int Chunk = API.getNumWords() - 1;
2482
2483 if (TrailingBytes)
2484 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2485
2486 for (; Chunk >= 0; --Chunk)
2487 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2488 } else {
2489 unsigned Chunk;
2490 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2491 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2492
2493 if (TrailingBytes)
2494 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2495 }
2496
2497 // Emit the tail padding for the long double.
2498 const DataLayout &DL = AP.getDataLayout();
2499 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2500}
2501
2502static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2503 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
23
Calling 'Value::getType'
25
Returning from 'Value::getType'
26
Passing value via 2nd parameter 'ET'
27
Calling 'emitGlobalConstantFP'
2504}
2505
2506static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
2507 const DataLayout &DL = AP.getDataLayout();
2508 unsigned BitWidth = CI->getBitWidth();
2509
2510 // Copy the value as we may massage the layout for constants whose bit width
2511 // is not a multiple of 64-bits.
2512 APInt Realigned(CI->getValue());
2513 uint64_t ExtraBits = 0;
2514 unsigned ExtraBitsSize = BitWidth & 63;
2515
2516 if (ExtraBitsSize) {
2517 // The bit width of the data is not a multiple of 64-bits.
2518 // The extra bits are expected to be at the end of the chunk of the memory.
2519 // Little endian:
2520 // * Nothing to be done, just record the extra bits to emit.
2521 // Big endian:
2522 // * Record the extra bits to emit.
2523 // * Realign the raw data to emit the chunks of 64-bits.
2524 if (DL.isBigEndian()) {
2525 // Basically the structure of the raw data is a chunk of 64-bits cells:
2526 // 0 1 BitWidth / 64
2527 // [chunk1][chunk2] ... [chunkN].
2528 // The most significant chunk is chunkN and it should be emitted first.
2529 // However, due to the alignment issue chunkN contains useless bits.
2530 // Realign the chunks so that they contain only useless information:
2531 // ExtraBits 0 1 (BitWidth / 64) - 1
2532 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2533 ExtraBits = Realigned.getRawData()[0] &
2534 (((uint64_t)-1) >> (64 - ExtraBitsSize));
2535 Realigned.lshrInPlace(ExtraBitsSize);
2536 } else
2537 ExtraBits = Realigned.getRawData()[BitWidth / 64];
2538 }
2539
2540 // We don't expect assemblers to support integer data directives
2541 // for more than 64 bits, so we emit the data in at most 64-bit
2542 // quantities at a time.
2543 const uint64_t *RawData = Realigned.getRawData();
2544 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2545 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2546 AP.OutStreamer->EmitIntValue(Val, 8);
2547 }
2548
2549 if (ExtraBitsSize) {
2550 // Emit the extra bits after the 64-bits chunks.
2551
2552 // Emit a directive that fills the expected size.
2553 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2554 Size -= (BitWidth / 64) * 8;
2555 assert(Size && Size * 8 >= ExtraBitsSize &&((Size && Size * 8 >= ExtraBitsSize && (ExtraBits
& (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits
&& "Directive too small for extra bits.") ? static_cast
<void> (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2557, __PRETTY_FUNCTION__))
2556 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))((Size && Size * 8 >= ExtraBitsSize && (ExtraBits
& (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits
&& "Directive too small for extra bits.") ? static_cast
<void> (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2557, __PRETTY_FUNCTION__))
2557 == ExtraBits && "Directive too small for extra bits.")((Size && Size * 8 >= ExtraBitsSize && (ExtraBits
& (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits
&& "Directive too small for extra bits.") ? static_cast
<void> (0) : __assert_fail ("Size && Size * 8 >= ExtraBitsSize && (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) == ExtraBits && \"Directive too small for extra bits.\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2557, __PRETTY_FUNCTION__))
;
2558 AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2559 }
2560}
2561
2562/// Transform a not absolute MCExpr containing a reference to a GOT
2563/// equivalent global, by a target specific GOT pc relative access to the
2564/// final symbol.
2565static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2566 const Constant *BaseCst,
2567 uint64_t Offset) {
2568 // The global @foo below illustrates a global that uses a got equivalent.
2569 //
2570 // @bar = global i32 42
2571 // @gotequiv = private unnamed_addr constant i32* @bar
2572 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2573 // i64 ptrtoint (i32* @foo to i64))
2574 // to i32)
2575 //
2576 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2577 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2578 // form:
2579 //
2580 // foo = cstexpr, where
2581 // cstexpr := <gotequiv> - "." + <cst>
2582 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2583 //
2584 // After canonicalization by evaluateAsRelocatable `ME` turns into:
2585 //
2586 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2587 // gotpcrelcst := <offset from @foo base> + <cst>
2588 MCValue MV;
2589 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2590 return;
2591 const MCSymbolRefExpr *SymA = MV.getSymA();
2592 if (!SymA)
2593 return;
2594
2595 // Check that GOT equivalent symbol is cached.
2596 const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2597 if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2598 return;
2599
2600 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2601 if (!BaseGV)
2602 return;
2603
2604 // Check for a valid base symbol
2605 const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2606 const MCSymbolRefExpr *SymB = MV.getSymB();
2607
2608 if (!SymB || BaseSym != &SymB->getSymbol())
2609 return;
2610
2611 // Make sure to match:
2612 //
2613 // gotpcrelcst := <offset from @foo base> + <cst>
2614 //
2615 // If gotpcrelcst is positive it means that we can safely fold the pc rel
2616 // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2617 // if the target knows how to encode it.
2618 int64_t GOTPCRelCst = Offset + MV.getConstant();
2619 if (GOTPCRelCst < 0)
2620 return;
2621 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2622 return;
2623
2624 // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2625 //
2626 // bar:
2627 // .long 42
2628 // gotequiv:
2629 // .quad bar
2630 // foo:
2631 // .long gotequiv - "." + <cst>
2632 //
2633 // is replaced by the target specific equivalent to:
2634 //
2635 // bar:
2636 // .long 42
2637 // foo:
2638 // .long bar@GOTPCREL+<gotpcrelcst>
2639 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2640 const GlobalVariable *GV = Result.first;
2641 int NumUses = (int)Result.second;
2642 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2643 const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2644 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
2645 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2646
2647 // Update GOT equivalent usage information
2648 --NumUses;
2649 if (NumUses >= 0)
2650 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2651}
2652
2653static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2654 AsmPrinter &AP, const Constant *BaseCV,
2655 uint64_t Offset) {
2656 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2657
2658 // Globals with sub-elements such as combinations of arrays and structs
2659 // are handled recursively by emitGlobalConstantImpl. Keep track of the
2660 // constant symbol base and the current position with BaseCV and Offset.
2661 if (!BaseCV && CV->hasOneUse())
17
Taking false branch
2662 BaseCV = dyn_cast<Constant>(CV->user_back());
2663
2664 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
18
Taking false branch
2665 return AP.OutStreamer->EmitZeros(Size);
2666
2667 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
19
Taking false branch
2668 switch (Size) {
2669 case 1:
2670 case 2:
2671 case 4:
2672 case 8:
2673 if (AP.isVerbose())
2674 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64"l" "x" "\n",
2675 CI->getZExtValue());
2676 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2677 return;
2678 default:
2679 emitGlobalConstantLargeInt(CI, AP);
2680 return;
2681 }
2682 }
2683
2684 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
20
Assuming 'CFP' is non-null
21
Taking true branch
2685 return emitGlobalConstantFP(CFP, AP);
22
Calling 'emitGlobalConstantFP'
2686
2687 if (isa<ConstantPointerNull>(CV)) {
2688 AP.OutStreamer->EmitIntValue(0, Size);
2689 return;
2690 }
2691
2692 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2693 return emitGlobalConstantDataSequential(DL, CDS, AP);
2694
2695 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2696 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2697
2698 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2699 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2700
2701 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2702 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2703 // vectors).
2704 if (CE->getOpcode() == Instruction::BitCast)
2705 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2706
2707 if (Size > 8) {
2708 // If the constant expression's size is greater than 64-bits, then we have
2709 // to emit the value in chunks. Try to constant fold the value and emit it
2710 // that way.
2711 Constant *New = ConstantFoldConstant(CE, DL);
2712 if (New && New != CE)
2713 return emitGlobalConstantImpl(DL, New, AP);
2714 }
2715 }
2716
2717 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2718 return emitGlobalConstantVector(DL, V, AP);
2719
2720 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2721 // thread the streamer with EmitValue.
2722 const MCExpr *ME = AP.lowerConstant(CV);
2723
2724 // Since lowerConstant already folded and got rid of all IR pointer and
2725 // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2726 // directly.
2727 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
2728 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2729
2730 AP.OutStreamer->EmitValue(ME, Size);
2731}
2732
2733/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2734void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
2735 uint64_t Size = DL.getTypeAllocSize(CV->getType());
2736 if (Size)
14
Assuming 'Size' is not equal to 0
15
Taking true branch
2737 emitGlobalConstantImpl(DL, CV, *this);
16
Calling 'emitGlobalConstantImpl'
2738 else if (MAI->hasSubsectionsViaSymbols()) {
2739 // If the global has zero size, emit a single byte so that two labels don't
2740 // look like they are at the same location.
2741 OutStreamer->EmitIntValue(0, 1);
2742 }
2743}
2744
2745void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2746 // Target doesn't support this yet!
2747 llvm_unreachable("Target does not support EmitMachineConstantPoolValue")::llvm::llvm_unreachable_internal("Target does not support EmitMachineConstantPoolValue"
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2747)
;
2748}
2749
2750void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2751 if (Offset > 0)
2752 OS << '+' << Offset;
2753 else if (Offset < 0)
2754 OS << Offset;
2755}
2756
2757//===----------------------------------------------------------------------===//
2758// Symbol Lowering Routines.
2759//===----------------------------------------------------------------------===//
2760
2761MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
2762 return OutContext.createTempSymbol(Name, true);
2763}
2764
2765MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2766 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2767}
2768
2769MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2770 return MMI->getAddrLabelSymbol(BB);
2771}
2772
2773/// GetCPISymbol - Return the symbol for the specified constant pool entry.
2774MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2775 if (getSubtargetInfo().getTargetTriple().isKnownWindowsMSVCEnvironment()) {
2776 const MachineConstantPoolEntry &CPE =
2777 MF->getConstantPool()->getConstants()[CPID];
2778 if (!CPE.isMachineConstantPoolEntry()) {
2779 const DataLayout &DL = MF->getDataLayout();
2780 SectionKind Kind = CPE.getSectionKind(&DL);
2781 const Constant *C = CPE.Val.ConstVal;
2782 unsigned Align = CPE.Alignment;
2783 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
2784 getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) {
2785 if (MCSymbol *Sym = S->getCOMDATSymbol()) {
2786 if (Sym->isUndefined())
2787 OutStreamer->EmitSymbolAttribute(Sym, MCSA_Global);
2788 return Sym;
2789 }
2790 }
2791 }
2792 }
2793
2794 const DataLayout &DL = getDataLayout();
2795 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2796 "CPI" + Twine(getFunctionNumber()) + "_" +
2797 Twine(CPID));
2798}
2799
2800/// GetJTISymbol - Return the symbol for the specified jump table entry.
2801MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2802 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2803}
2804
2805/// GetJTSetSymbol - Return the symbol for the specified jump table .set
2806/// FIXME: privatize to AsmPrinter.
2807MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2808 const DataLayout &DL = getDataLayout();
2809 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
2810 Twine(getFunctionNumber()) + "_" +
2811 Twine(UID) + "_set_" + Twine(MBBID));
2812}
2813
2814MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2815 StringRef Suffix) const {
2816 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2817}
2818
2819/// Return the MCSymbol for the specified ExternalSymbol.
2820MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2821 SmallString<60> NameStr;
2822 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2823 return OutContext.getOrCreateSymbol(NameStr);
2824}
2825
2826/// PrintParentLoopComment - Print comments about parent loops of this one.
2827static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2828 unsigned FunctionNumber) {
2829 if (!Loop) return;
2830 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2831 OS.indent(Loop->getLoopDepth()*2)
2832 << "Parent Loop BB" << FunctionNumber << "_"
2833 << Loop->getHeader()->getNumber()
2834 << " Depth=" << Loop->getLoopDepth() << '\n';
2835}
2836
2837/// PrintChildLoopComment - Print comments about child loops within
2838/// the loop for this basic block, with nesting.
2839static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2840 unsigned FunctionNumber) {
2841 // Add child loop information
2842 for (const MachineLoop *CL : *Loop) {
2843 OS.indent(CL->getLoopDepth()*2)
2844 << "Child Loop BB" << FunctionNumber << "_"
2845 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2846 << '\n';
2847 PrintChildLoopComment(OS, CL, FunctionNumber);
2848 }
2849}
2850
2851/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2852static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2853 const MachineLoopInfo *LI,
2854 const AsmPrinter &AP) {
2855 // Add loop depth information
2856 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2857 if (!Loop) return;
2858
2859 MachineBasicBlock *Header = Loop->getHeader();
2860 assert(Header && "No header for loop")((Header && "No header for loop") ? static_cast<void
> (0) : __assert_fail ("Header && \"No header for loop\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2860, __PRETTY_FUNCTION__))
;
2861
2862 // If this block is not a loop header, just print out what is the loop header
2863 // and return.
2864 if (Header != &MBB) {
2865 AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2866 Twine(AP.getFunctionNumber())+"_" +
2867 Twine(Loop->getHeader()->getNumber())+
2868 " Depth="+Twine(Loop->getLoopDepth()));
2869 return;
2870 }
2871
2872 // Otherwise, it is a loop header. Print out information about child and
2873 // parent loops.
2874 raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2875
2876 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2877
2878 OS << "=>";
2879 OS.indent(Loop->getLoopDepth()*2-2);
2880
2881 OS << "This ";
2882 if (Loop->empty())
2883 OS << "Inner ";
2884 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2885
2886 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2887}
2888
2889void AsmPrinter::setupCodePaddingContext(const MachineBasicBlock &MBB,
2890 MCCodePaddingContext &Context) const {
2891 assert(MF != nullptr && "Machine function must be valid")((MF != nullptr && "Machine function must be valid") ?
static_cast<void> (0) : __assert_fail ("MF != nullptr && \"Machine function must be valid\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2891, __PRETTY_FUNCTION__))
;
2892 Context.IsPaddingActive = !MF->hasInlineAsm() &&
2893 !MF->getFunction().hasOptSize() &&
2894 TM.getOptLevel() != CodeGenOpt::None;
2895 Context.IsBasicBlockReachableViaFallthrough =
2896 std::find(MBB.pred_begin(), MBB.pred_end(), MBB.getPrevNode()) !=
2897 MBB.pred_end();
2898 Context.IsBasicBlockReachableViaBranch =
2899 MBB.pred_size() > 0 && !isBlockOnlyReachableByFallthrough(&MBB);
2900}
2901
2902/// EmitBasicBlockStart - This method prints the label for the specified
2903/// MachineBasicBlock, an alignment (if present) and a comment describing
2904/// it if appropriate.
2905void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
2906 // End the previous funclet and start a new one.
2907 if (MBB.isEHFuncletEntry()) {
2908 for (const HandlerInfo &HI : Handlers) {
2909 HI.Handler->endFunclet();
2910 HI.Handler->beginFunclet(MBB);
2911 }
2912 }
2913
2914 // Emit an alignment directive for this block, if needed.
2915 if (unsigned Align = MBB.getAlignment())
2916 EmitAlignment(Align);
2917 MCCodePaddingContext Context;
2918 setupCodePaddingContext(MBB, Context);
2919 OutStreamer->EmitCodePaddingBasicBlockStart(Context);
2920
2921 // If the block has its address taken, emit any labels that were used to
2922 // reference the block. It is possible that there is more than one label
2923 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2924 // the references were generated.
2925 if (MBB.hasAddressTaken()) {
2926 const BasicBlock *BB = MBB.getBasicBlock();
2927 if (isVerbose())
2928 OutStreamer->AddComment("Block address taken");
2929
2930 // MBBs can have their address taken as part of CodeGen without having
2931 // their corresponding BB's address taken in IR
2932 if (BB->hasAddressTaken())
2933 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2934 OutStreamer->EmitLabel(Sym);
2935 }
2936
2937 // Print some verbose block comments.
2938 if (isVerbose()) {
2939 if (const BasicBlock *BB = MBB.getBasicBlock()) {
2940 if (BB->hasName()) {
2941 BB->printAsOperand(OutStreamer->GetCommentOS(),
2942 /*PrintType=*/false, BB->getModule());
2943 OutStreamer->GetCommentOS() << '\n';
2944 }
2945 }
2946
2947 assert(MLI != nullptr && "MachineLoopInfo should has been computed")((MLI != nullptr && "MachineLoopInfo should has been computed"
) ? static_cast<void> (0) : __assert_fail ("MLI != nullptr && \"MachineLoopInfo should has been computed\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 2947, __PRETTY_FUNCTION__))
;
2948 emitBasicBlockLoopComments(MBB, MLI, *this);
2949 }
2950
2951 // Print the main label for the block.
2952 if (MBB.pred_empty() ||
2953 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry() &&
2954 !MBB.hasLabelMustBeEmitted())) {
2955 if (isVerbose()) {
2956 // NOTE: Want this comment at start of line, don't emit with AddComment.
2957 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
2958 false);
2959 }
2960 } else {
2961 if (isVerbose() && MBB.hasLabelMustBeEmitted())
2962 OutStreamer->AddComment("Label of block must be emitted");
2963 OutStreamer->EmitLabel(MBB.getSymbol());
2964 }
2965}
2966
2967void AsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
2968 MCCodePaddingContext Context;
2969 setupCodePaddingContext(MBB, Context);
2970 OutStreamer->EmitCodePaddingBasicBlockEnd(Context);
2971}
2972
2973void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2974 bool IsDefinition) const {
2975 MCSymbolAttr Attr = MCSA_Invalid;
2976
2977 switch (Visibility) {
2978 default: break;
2979 case GlobalValue::HiddenVisibility:
2980 if (IsDefinition)
2981 Attr = MAI->getHiddenVisibilityAttr();
2982 else
2983 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2984 break;
2985 case GlobalValue::ProtectedVisibility:
2986 Attr = MAI->getProtectedVisibilityAttr();
2987 break;
2988 }
2989
2990 if (Attr != MCSA_Invalid)
2991 OutStreamer->EmitSymbolAttribute(Sym, Attr);
2992}
2993
2994/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2995/// exactly one predecessor and the control transfer mechanism between
2996/// the predecessor and this block is a fall-through.
2997bool AsmPrinter::
2998isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2999 // If this is a landing pad, it isn't a fall through. If it has no preds,
3000 // then nothing falls through to it.
3001 if (MBB->isEHPad() || MBB->pred_empty())
3002 return false;
3003
3004 // If there isn't exactly one predecessor, it can't be a fall through.
3005 if (MBB->pred_size() > 1)
3006 return false;
3007
3008 // The predecessor has to be immediately before this block.
3009 MachineBasicBlock *Pred = *MBB->pred_begin();
3010 if (!Pred->isLayoutSuccessor(MBB))
3011 return false;
3012
3013 // If the block is completely empty, then it definitely does fall through.
3014 if (Pred->empty())
3015 return true;
3016
3017 // Check the terminators in the previous blocks
3018 for (const auto &MI : Pred->terminators()) {
3019 // If it is not a simple branch, we are in a table somewhere.
3020 if (!MI.isBranch() || MI.isIndirectBranch())
3021 return false;
3022
3023 // If we are the operands of one of the branches, this is not a fall
3024 // through. Note that targets with delay slots will usually bundle
3025 // terminators with the delay slot instruction.
3026 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3027 if (OP->isJTI())
3028 return false;
3029 if (OP->isMBB() && OP->getMBB() == MBB)
3030 return false;
3031 }
3032 }
3033
3034 return true;
3035}
3036
3037GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3038 if (!S.usesMetadata())
3039 return nullptr;
3040
3041 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3042 gcp_map_type::iterator GCPI = GCMap.find(&S);
3043 if (GCPI != GCMap.end())
3044 return GCPI->second.get();
3045
3046 auto Name = S.getName();
3047
3048 for (GCMetadataPrinterRegistry::iterator
3049 I = GCMetadataPrinterRegistry::begin(),
3050 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
3051 if (Name == I->getName()) {
3052 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
3053 GMP->S = &S;
3054 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3055 return IterBool.first->second.get();
3056 }
3057
3058 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3059}
3060
3061void AsmPrinter::emitStackMaps(StackMaps &SM) {
3062 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3063 assert(MI && "AsmPrinter didn't require GCModuleInfo?")((MI && "AsmPrinter didn't require GCModuleInfo?") ? static_cast
<void> (0) : __assert_fail ("MI && \"AsmPrinter didn't require GCModuleInfo?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3063, __PRETTY_FUNCTION__))
;
3064 bool NeedsDefault = false;
3065 if (MI->begin() == MI->end())
3066 // No GC strategy, use the default format.
3067 NeedsDefault = true;
3068 else
3069 for (auto &I : *MI) {
3070 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3071 if (MP->emitStackMaps(SM, *this))
3072 continue;
3073 // The strategy doesn't have printer or doesn't emit custom stack maps.
3074 // Use the default format.
3075 NeedsDefault = true;
3076 }
3077
3078 if (NeedsDefault)
3079 SM.serializeToStackMapSection();
3080}
3081
3082/// Pin vtable to this file.
3083AsmPrinterHandler::~AsmPrinterHandler() = default;
3084
3085void AsmPrinterHandler::markFunctionEnd() {}
3086
3087// In the binary's "xray_instr_map" section, an array of these function entries
3088// describes each instrumentation point. When XRay patches your code, the index
3089// into this table will be given to your handler as a patch point identifier.
3090void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out,
3091 const MCSymbol *CurrentFnSym) const {
3092 Out->EmitSymbolValue(Sled, Bytes);
3093 Out->EmitSymbolValue(CurrentFnSym, Bytes);
3094 auto Kind8 = static_cast<uint8_t>(Kind);
3095 Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3096 Out->EmitBinaryData(
3097 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3098 Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3099 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3100 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size")((Padding >= 0 && "Instrumentation map entry > 4 * Word Size"
) ? static_cast<void> (0) : __assert_fail ("Padding >= 0 && \"Instrumentation map entry > 4 * Word Size\""
, "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3100, __PRETTY_FUNCTION__))
;
3101 Out->EmitZeros(Padding);
3102}
3103
3104void AsmPrinter::emitXRayTable() {
3105 if (Sleds.empty())
3106 return;
3107
3108 auto PrevSection = OutStreamer->getCurrentSectionOnly();
3109 const Function &F = MF->getFunction();
3110 MCSection *InstMap = nullptr;
3111 MCSection *FnSledIndex = nullptr;
3112 if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) {
3113 auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym);
3114 assert(Associated != nullptr)((Associated != nullptr) ? static_cast<void> (0) : __assert_fail
("Associated != nullptr", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3114, __PRETTY_FUNCTION__))
;
3115 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3116 std::string GroupName;
3117 if (F.hasComdat()) {
3118 Flags |= ELF::SHF_GROUP;
3119 GroupName = F.getComdat()->getName();
3120 }
3121
3122 auto UniqueID = ++XRayFnUniqueID;
3123 InstMap =
3124 OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
3125 GroupName, UniqueID, Associated);
3126 FnSledIndex =
3127 OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
3128 GroupName, UniqueID, Associated);
3129 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3130 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3131 SectionKind::getReadOnlyWithRel());
3132 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
3133 SectionKind::getReadOnlyWithRel());
3134 } else {
3135 llvm_unreachable("Unsupported target")::llvm::llvm_unreachable_internal("Unsupported target", "/build/llvm-toolchain-snapshot-9~svn361465/lib/CodeGen/AsmPrinter/AsmPrinter.cpp"
, 3135)
;
3136 }
3137
3138 auto WordSizeBytes = MAI->getCodePointerSize();
3139
3140 // Now we switch to the instrumentation map section. Because this is done
3141 // per-function, we are able to create an index entry that will represent the
3142 // range of sleds associated with a function.
3143 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3144 OutStreamer->SwitchSection(InstMap);
3145 OutStreamer->EmitLabel(SledsStart);
3146 for (const auto &Sled : Sleds)
3147 Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
3148 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3149 OutStreamer->EmitLabel(SledsEnd);
3150
3151 // We then emit a single entry in the index per function. We use the symbols
3152 // that bound the instrumentation map as the range for a specific function.
3153 // Each entry here will be 2 * word size aligned, as we're writing down two
3154 // pointers. This should work for both 32-bit and 64-bit platforms.
3155 OutStreamer->SwitchSection(FnSledIndex);
3156 OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
3157 OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
3158 OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
3159 OutStreamer->SwitchSection(PrevSection);
3160 Sleds.clear();
3161}
3162
3163void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
3164 SledKind Kind, uint8_t Version) {
3165 const Function &F = MI.getMF()->getFunction();
3166 auto Attr = F.getFnAttribute("function-instrument");
3167 bool LogArgs = F.hasFnAttribute("xray-log-args");
3168 bool AlwaysInstrument =
3169 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3170 if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3171 Kind = SledKind::LOG_ARGS_ENTER;
3172 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3173 AlwaysInstrument, &F, Version});
3174}
3175
3176uint16_t AsmPrinter::getDwarfVersion() const {
3177 return OutStreamer->getContext().getDwarfVersion();
3178}
3179
3180void AsmPrinter::setDwarfVersion(uint16_t Version) {
3181 OutStreamer->getContext().setDwarfVersion(Version);
3182}

/build/llvm-toolchain-snapshot-9~svn361465/include/llvm/IR/Value.h

1//===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===//
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// This file declares the Value class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_IR_VALUE_H
14#define LLVM_IR_VALUE_H
15
16#include "llvm-c/Types.h"
17#include "llvm/ADT/iterator_range.h"
18#include "llvm/IR/Use.h"
19#include "llvm/Support/CBindingWrapping.h"
20#include "llvm/Support/Casting.h"
21#include <cassert>
22#include <iterator>
23#include <memory>
24
25namespace llvm {
26
27class APInt;
28class Argument;
29class BasicBlock;
30class Constant;
31class ConstantData;
32class ConstantAggregate;
33class DataLayout;
34class Function;
35class GlobalAlias;
36class GlobalIFunc;
37class GlobalIndirectSymbol;
38class GlobalObject;
39class GlobalValue;
40class GlobalVariable;
41class InlineAsm;
42class Instruction;
43class LLVMContext;
44class Module;
45class ModuleSlotTracker;
46class raw_ostream;
47template<typename ValueTy> class StringMapEntry;
48class StringRef;
49class Twine;
50class Type;
51class User;
52
53using ValueName = StringMapEntry<Value *>;
54
55//===----------------------------------------------------------------------===//
56// Value Class
57//===----------------------------------------------------------------------===//
58
59/// LLVM Value Representation
60///
61/// This is a very important LLVM class. It is the base class of all values
62/// computed by a program that may be used as operands to other values. Value is
63/// the super class of other important classes such as Instruction and Function.
64/// All Values have a Type. Type is not a subclass of Value. Some values can
65/// have a name and they belong to some Module. Setting the name on the Value
66/// automatically updates the module's symbol table.
67///
68/// Every value has a "use list" that keeps track of which other Values are
69/// using this Value. A Value can also have an arbitrary number of ValueHandle
70/// objects that watch it and listen to RAUW and Destroy events. See
71/// llvm/IR/ValueHandle.h for details.
72class Value {
73 // The least-significant bit of the first word of Value *must* be zero:
74 // http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm
75 Type *VTy;
76 Use *UseList;
77
78 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
79 friend class ValueHandleBase;
80
81 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
82 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
83
84protected:
85 /// Hold subclass data that can be dropped.
86 ///
87 /// This member is similar to SubclassData, however it is for holding
88 /// information which may be used to aid optimization, but which may be
89 /// cleared to zero without affecting conservative interpretation.
90 unsigned char SubclassOptionalData : 7;
91
92private:
93 /// Hold arbitrary subclass data.
94 ///
95 /// This member is defined by this class, but is not used for anything.
96 /// Subclasses can use it to hold whatever state they find useful. This
97 /// field is initialized to zero by the ctor.
98 unsigned short SubclassData;
99
100protected:
101 /// The number of operands in the subclass.
102 ///
103 /// This member is defined by this class, but not used for anything.
104 /// Subclasses can use it to store their number of operands, if they have
105 /// any.
106 ///
107 /// This is stored here to save space in User on 64-bit hosts. Since most
108 /// instances of Value have operands, 32-bit hosts aren't significantly
109 /// affected.
110 ///
111 /// Note, this should *NOT* be used directly by any class other than User.
112 /// User uses this value to find the Use list.
113 enum : unsigned { NumUserOperandsBits = 28 };
114 unsigned NumUserOperands : NumUserOperandsBits;
115
116 // Use the same type as the bitfield above so that MSVC will pack them.
117 unsigned IsUsedByMD : 1;
118 unsigned HasName : 1;
119 unsigned HasHungOffUses : 1;
120 unsigned HasDescriptor : 1;
121
122private:
123 template <typename UseT> // UseT == 'Use' or 'const Use'
124 class use_iterator_impl
125 : public std::iterator<std::forward_iterator_tag, UseT *> {
126 friend class Value;
127
128 UseT *U;
129
130 explicit use_iterator_impl(UseT *u) : U(u) {}
131
132 public:
133 use_iterator_impl() : U() {}
134
135 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
136 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
137
138 use_iterator_impl &operator++() { // Preincrement
139 assert(U && "Cannot increment end iterator!")((U && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/include/llvm/IR/Value.h"
, 139, __PRETTY_FUNCTION__))
;
140 U = U->getNext();
141 return *this;
142 }
143
144 use_iterator_impl operator++(int) { // Postincrement
145 auto tmp = *this;
146 ++*this;
147 return tmp;
148 }
149
150 UseT &operator*() const {
151 assert(U && "Cannot dereference end iterator!")((U && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/include/llvm/IR/Value.h"
, 151, __PRETTY_FUNCTION__))
;
152 return *U;
153 }
154
155 UseT *operator->() const { return &operator*(); }
156
157 operator use_iterator_impl<const UseT>() const {
158 return use_iterator_impl<const UseT>(U);
159 }
160 };
161
162 template <typename UserTy> // UserTy == 'User' or 'const User'
163 class user_iterator_impl
164 : public std::iterator<std::forward_iterator_tag, UserTy *> {
165 use_iterator_impl<Use> UI;
166 explicit user_iterator_impl(Use *U) : UI(U) {}
167 friend class Value;
168
169 public:
170 user_iterator_impl() = default;
171
172 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
173 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
174
175 /// Returns true if this iterator is equal to user_end() on the value.
176 bool atEnd() const { return *this == user_iterator_impl(); }
177
178 user_iterator_impl &operator++() { // Preincrement
179 ++UI;
180 return *this;
181 }
182
183 user_iterator_impl operator++(int) { // Postincrement
184 auto tmp = *this;
185 ++*this;
186 return tmp;
187 }
188
189 // Retrieve a pointer to the current User.
190 UserTy *operator*() const {
191 return UI->getUser();
192 }
193
194 UserTy *operator->() const { return operator*(); }
195
196 operator user_iterator_impl<const UserTy>() const {
197 return user_iterator_impl<const UserTy>(*UI);
198 }
199
200 Use &getUse() const { return *UI; }
201 };
202
203protected:
204 Value(Type *Ty, unsigned scid);
205
206 /// Value's destructor should be virtual by design, but that would require
207 /// that Value and all of its subclasses have a vtable that effectively
208 /// duplicates the information in the value ID. As a size optimization, the
209 /// destructor has been protected, and the caller should manually call
210 /// deleteValue.
211 ~Value(); // Use deleteValue() to delete a generic Value.
212
213public:
214 Value(const Value &) = delete;
215 Value &operator=(const Value &) = delete;
216
217 /// Delete a pointer to a generic Value.
218 void deleteValue();
219
220 /// Support for debugging, callable in GDB: V->dump()
221 void dump() const;
222
223 /// Implement operator<< on Value.
224 /// @{
225 void print(raw_ostream &O, bool IsForDebug = false) const;
226 void print(raw_ostream &O, ModuleSlotTracker &MST,
227 bool IsForDebug = false) const;
228 /// @}
229
230 /// Print the name of this Value out to the specified raw_ostream.
231 ///
232 /// This is useful when you just want to print 'int %reg126', not the
233 /// instruction that generated it. If you specify a Module for context, then
234 /// even constanst get pretty-printed; for example, the type of a null
235 /// pointer is printed symbolically.
236 /// @{
237 void printAsOperand(raw_ostream &O, bool PrintType = true,
238 const Module *M = nullptr) const;
239 void printAsOperand(raw_ostream &O, bool PrintType,
240 ModuleSlotTracker &MST) const;
241 /// @}
242
243 /// All values are typed, get the type of this value.
244 Type *getType() const { return VTy; }
24
Returning pointer
245
246 /// All values hold a context through their type.
247 LLVMContext &getContext() const;
248
249 // All values can potentially be named.
250 bool hasName() const { return HasName; }
251 ValueName *getValueName() const;
252 void setValueName(ValueName *VN);
253
254private:
255 void destroyValueName();
256 enum class ReplaceMetadataUses { No, Yes };
257 void doRAUW(Value *New, ReplaceMetadataUses);
258 void setNameImpl(const Twine &Name);
259
260public:
261 /// Return a constant reference to the value's name.
262 ///
263 /// This guaranteed to return the same reference as long as the value is not
264 /// modified. If the value has a name, this does a hashtable lookup, so it's
265 /// not free.
266 StringRef getName() const;
267
268 /// Change the name of the value.
269 ///
270 /// Choose a new unique name if the provided name is taken.
271 ///
272 /// \param Name The new name; or "" if the value's name should be removed.
273 void setName(const Twine &Name);
274
275 /// Transfer the name from V to this value.
276 ///
277 /// After taking V's name, sets V's name to empty.
278 ///
279 /// \note It is an error to call V->takeName(V).
280 void takeName(Value *V);
281
282 /// Change all uses of this to point to a new Value.
283 ///
284 /// Go through the uses list for this definition and make each use point to
285 /// "V" instead of "this". After this completes, 'this's use list is
286 /// guaranteed to be empty.
287 void replaceAllUsesWith(Value *V);
288
289 /// Change non-metadata uses of this to point to a new Value.
290 ///
291 /// Go through the uses list for this definition and make each use point to
292 /// "V" instead of "this". This function skips metadata entries in the list.
293 void replaceNonMetadataUsesWith(Value *V);
294
295 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
296 /// make each use point to "V" instead of "this" when the use is outside the
297 /// block. 'This's use list is expected to have at least one element.
298 /// Unlike replaceAllUsesWith this function does not support basic block
299 /// values or constant users.
300 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
301
302 //----------------------------------------------------------------------
303 // Methods for handling the chain of uses of this Value.
304 //
305 // Materializing a function can introduce new uses, so these methods come in
306 // two variants:
307 // The methods that start with materialized_ check the uses that are
308 // currently known given which functions are materialized. Be very careful
309 // when using them since you might not get all uses.
310 // The methods that don't start with materialized_ assert that modules is
311 // fully materialized.
312 void assertModuleIsMaterializedImpl() const;
313 // This indirection exists so we can keep assertModuleIsMaterializedImpl()
314 // around in release builds of Value.cpp to be linked with other code built
315 // in debug mode. But this avoids calling it in any of the release built code.
316 void assertModuleIsMaterialized() const {
317#ifndef NDEBUG
318 assertModuleIsMaterializedImpl();
319#endif
320 }
321
322 bool use_empty() const {
323 assertModuleIsMaterialized();
324 return UseList == nullptr;
325 }
326
327 bool materialized_use_empty() const {
328 return UseList == nullptr;
329 }
330
331 using use_iterator = use_iterator_impl<Use>;
332 using const_use_iterator = use_iterator_impl<const Use>;
333
334 use_iterator materialized_use_begin() { return use_iterator(UseList); }
335 const_use_iterator materialized_use_begin() const {
336 return const_use_iterator(UseList);
337 }
338 use_iterator use_begin() {
339 assertModuleIsMaterialized();
340 return materialized_use_begin();
341 }
342 const_use_iterator use_begin() const {
343 assertModuleIsMaterialized();
344 return materialized_use_begin();
345 }
346 use_iterator use_end() { return use_iterator(); }
347 const_use_iterator use_end() const { return const_use_iterator(); }
348 iterator_range<use_iterator> materialized_uses() {
349 return make_range(materialized_use_begin(), use_end());
350 }
351 iterator_range<const_use_iterator> materialized_uses() const {
352 return make_range(materialized_use_begin(), use_end());
353 }
354 iterator_range<use_iterator> uses() {
355 assertModuleIsMaterialized();
356 return materialized_uses();
357 }
358 iterator_range<const_use_iterator> uses() const {
359 assertModuleIsMaterialized();
360 return materialized_uses();
361 }
362
363 bool user_empty() const {
364 assertModuleIsMaterialized();
365 return UseList == nullptr;
366 }
367
368 using user_iterator = user_iterator_impl<User>;
369 using const_user_iterator = user_iterator_impl<const User>;
370
371 user_iterator materialized_user_begin() { return user_iterator(UseList); }
372 const_user_iterator materialized_user_begin() const {
373 return const_user_iterator(UseList);
374 }
375 user_iterator user_begin() {
376 assertModuleIsMaterialized();
377 return materialized_user_begin();
378 }
379 const_user_iterator user_begin() const {
380 assertModuleIsMaterialized();
381 return materialized_user_begin();
382 }
383 user_iterator user_end() { return user_iterator(); }
384 const_user_iterator user_end() const { return const_user_iterator(); }
385 User *user_back() {
386 assertModuleIsMaterialized();
387 return *materialized_user_begin();
388 }
389 const User *user_back() const {
390 assertModuleIsMaterialized();
391 return *materialized_user_begin();
392 }
393 iterator_range<user_iterator> materialized_users() {
394 return make_range(materialized_user_begin(), user_end());
395 }
396 iterator_range<const_user_iterator> materialized_users() const {
397 return make_range(materialized_user_begin(), user_end());
398 }
399 iterator_range<user_iterator> users() {
400 assertModuleIsMaterialized();
401 return materialized_users();
402 }
403 iterator_range<const_user_iterator> users() const {
404 assertModuleIsMaterialized();
405 return materialized_users();
406 }
407
408 /// Return true if there is exactly one user of this value.
409 ///
410 /// This is specialized because it is a common request and does not require
411 /// traversing the whole use list.
412 bool hasOneUse() const {
413 const_use_iterator I = use_begin(), E = use_end();
414 if (I == E) return false;
415 return ++I == E;
416 }
417
418 /// Return true if this Value has exactly N users.
419 bool hasNUses(unsigned N) const;
420
421 /// Return true if this value has N users or more.
422 ///
423 /// This is logically equivalent to getNumUses() >= N.
424 bool hasNUsesOrMore(unsigned N) const;
425
426 /// Check if this value is used in the specified basic block.
427 bool isUsedInBasicBlock(const BasicBlock *BB) const;
428
429 /// This method computes the number of uses of this Value.
430 ///
431 /// This is a linear time operation. Use hasOneUse, hasNUses, or
432 /// hasNUsesOrMore to check for specific values.
433 unsigned getNumUses() const;
434
435 /// This method should only be used by the Use class.
436 void addUse(Use &U) { U.addToList(&UseList); }
437
438 /// Concrete subclass of this.
439 ///
440 /// An enumeration for keeping track of the concrete subclass of Value that
441 /// is actually instantiated. Values of this enumeration are kept in the
442 /// Value classes SubclassID field. They are used for concrete type
443 /// identification.
444 enum ValueTy {
445#define HANDLE_VALUE(Name) Name##Val,
446#include "llvm/IR/Value.def"
447
448 // Markers:
449#define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
450#include "llvm/IR/Value.def"
451 };
452
453 /// Return an ID for the concrete type of this object.
454 ///
455 /// This is used to implement the classof checks. This should not be used
456 /// for any other purpose, as the values may change as LLVM evolves. Also,
457 /// note that for instructions, the Instruction's opcode is added to
458 /// InstructionVal. So this means three things:
459 /// # there is no value with code InstructionVal (no opcode==0).
460 /// # there are more possible values for the value type than in ValueTy enum.
461 /// # the InstructionVal enumerator must be the highest valued enumerator in
462 /// the ValueTy enum.
463 unsigned getValueID() const {
464 return SubclassID;
465 }
466
467 /// Return the raw optional flags value contained in this value.
468 ///
469 /// This should only be used when testing two Values for equivalence.
470 unsigned getRawSubclassOptionalData() const {
471 return SubclassOptionalData;
472 }
473
474 /// Clear the optional flags contained in this value.
475 void clearSubclassOptionalData() {
476 SubclassOptionalData = 0;
477 }
478
479 /// Check the optional flags for equality.
480 bool hasSameSubclassOptionalData(const Value *V) const {
481 return SubclassOptionalData == V->SubclassOptionalData;
482 }
483
484 /// Return true if there is a value handle associated with this value.
485 bool hasValueHandle() const { return HasValueHandle; }
486
487 /// Return true if there is metadata referencing this value.
488 bool isUsedByMetadata() const { return IsUsedByMD; }
489
490 /// Return true if this value is a swifterror value.
491 ///
492 /// swifterror values can be either a function argument or an alloca with a
493 /// swifterror attribute.
494 bool isSwiftError() const;
495
496 /// Strip off pointer casts, all-zero GEPs, and aliases.
497 ///
498 /// Returns the original uncasted value. If this is called on a non-pointer
499 /// value, it returns 'this'.
500 const Value *stripPointerCasts() const;
501 Value *stripPointerCasts() {
502 return const_cast<Value *>(
503 static_cast<const Value *>(this)->stripPointerCasts());
504 }
505
506 /// Strip off pointer casts, all-zero GEPs, aliases and invariant group
507 /// info.
508 ///
509 /// Returns the original uncasted value. If this is called on a non-pointer
510 /// value, it returns 'this'. This function should be used only in
511 /// Alias analysis.
512 const Value *stripPointerCastsAndInvariantGroups() const;
513 Value *stripPointerCastsAndInvariantGroups() {
514 return const_cast<Value *>(
515 static_cast<const Value *>(this)->stripPointerCastsAndInvariantGroups());
516 }
517
518 /// Strip off pointer casts and all-zero GEPs.
519 ///
520 /// Returns the original uncasted value. If this is called on a non-pointer
521 /// value, it returns 'this'.
522 const Value *stripPointerCastsNoFollowAliases() const;
523 Value *stripPointerCastsNoFollowAliases() {
524 return const_cast<Value *>(
525 static_cast<const Value *>(this)->stripPointerCastsNoFollowAliases());
526 }
527
528 /// Strip off pointer casts and all-constant inbounds GEPs.
529 ///
530 /// Returns the original pointer value. If this is called on a non-pointer
531 /// value, it returns 'this'.
532 const Value *stripInBoundsConstantOffsets() const;
533 Value *stripInBoundsConstantOffsets() {
534 return const_cast<Value *>(
535 static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
536 }
537
538 /// Accumulate offsets from \a stripInBoundsConstantOffsets().
539 ///
540 /// Stores the resulting constant offset stripped into the APInt provided.
541 /// The provided APInt will be extended or truncated as needed to be the
542 /// correct bitwidth for an offset of this pointer type.
543 ///
544 /// If this is called on a non-pointer value, it returns 'this'.
545 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
546 APInt &Offset) const;
547 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
548 APInt &Offset) {
549 return const_cast<Value *>(static_cast<const Value *>(this)
550 ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset));
551 }
552
553 /// Strip off pointer casts and inbounds GEPs.
554 ///
555 /// Returns the original pointer value. If this is called on a non-pointer
556 /// value, it returns 'this'.
557 const Value *stripInBoundsOffsets() const;
558 Value *stripInBoundsOffsets() {
559 return const_cast<Value *>(
560 static_cast<const Value *>(this)->stripInBoundsOffsets());
561 }
562
563 /// Returns the number of bytes known to be dereferenceable for the
564 /// pointer value.
565 ///
566 /// If CanBeNull is set by this function the pointer can either be null or be
567 /// dereferenceable up to the returned number of bytes.
568 uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
569 bool &CanBeNull) const;
570
571 /// Returns an alignment of the pointer value.
572 ///
573 /// Returns an alignment which is either specified explicitly, e.g. via
574 /// align attribute of a function argument, or guaranteed by DataLayout.
575 unsigned getPointerAlignment(const DataLayout &DL) const;
576
577 /// Translate PHI node to its predecessor from the given basic block.
578 ///
579 /// If this value is a PHI node with CurBB as its parent, return the value in
580 /// the PHI node corresponding to PredBB. If not, return ourself. This is
581 /// useful if you want to know the value something has in a predecessor
582 /// block.
583 const Value *DoPHITranslation(const BasicBlock *CurBB,
584 const BasicBlock *PredBB) const;
585 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
586 return const_cast<Value *>(
587 static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
588 }
589
590 /// The maximum alignment for instructions.
591 ///
592 /// This is the greatest alignment value supported by load, store, and alloca
593 /// instructions, and global values.
594 static const unsigned MaxAlignmentExponent = 29;
595 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
596
597 /// Mutate the type of this Value to be of the specified type.
598 ///
599 /// Note that this is an extremely dangerous operation which can create
600 /// completely invalid IR very easily. It is strongly recommended that you
601 /// recreate IR objects with the right types instead of mutating them in
602 /// place.
603 void mutateType(Type *Ty) {
604 VTy = Ty;
605 }
606
607 /// Sort the use-list.
608 ///
609 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
610 /// expected to compare two \a Use references.
611 template <class Compare> void sortUseList(Compare Cmp);
612
613 /// Reverse the use-list.
614 void reverseUseList();
615
616private:
617 /// Merge two lists together.
618 ///
619 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
620 /// "equal" items from L before items from R.
621 ///
622 /// \return the first element in the list.
623 ///
624 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
625 template <class Compare>
626 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
627 Use *Merged;
628 Use **Next = &Merged;
629
630 while (true) {
631 if (!L) {
632 *Next = R;
633 break;
634 }
635 if (!R) {
636 *Next = L;
637 break;
638 }
639 if (Cmp(*R, *L)) {
640 *Next = R;
641 Next = &R->Next;
642 R = R->Next;
643 } else {
644 *Next = L;
645 Next = &L->Next;
646 L = L->Next;
647 }
648 }
649
650 return Merged;
651 }
652
653protected:
654 unsigned short getSubclassDataFromValue() const { return SubclassData; }
655 void setValueSubclassData(unsigned short D) { SubclassData = D; }
656};
657
658struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
659
660/// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
661/// Those don't work because Value and Instruction's destructors are protected,
662/// aren't virtual, and won't destroy the complete object.
663using unique_value = std::unique_ptr<Value, ValueDeleter>;
664
665inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
666 V.print(OS);
667 return OS;
668}
669
670void Use::set(Value *V) {
671 if (Val) removeFromList();
672 Val = V;
673 if (V) V->addUse(*this);
674}
675
676Value *Use::operator=(Value *RHS) {
677 set(RHS);
678 return RHS;
679}
680
681const Use &Use::operator=(const Use &RHS) {
682 set(RHS.Val);
683 return *this;
684}
685
686template <class Compare> void Value::sortUseList(Compare Cmp) {
687 if (!UseList || !UseList->Next)
688 // No need to sort 0 or 1 uses.
689 return;
690
691 // Note: this function completely ignores Prev pointers until the end when
692 // they're fixed en masse.
693
694 // Create a binomial vector of sorted lists, visiting uses one at a time and
695 // merging lists as necessary.
696 const unsigned MaxSlots = 32;
697 Use *Slots[MaxSlots];
698
699 // Collect the first use, turning it into a single-item list.
700 Use *Next = UseList->Next;
701 UseList->Next = nullptr;
702 unsigned NumSlots = 1;
703 Slots[0] = UseList;
704
705 // Collect all but the last use.
706 while (Next->Next) {
707 Use *Current = Next;
708 Next = Current->Next;
709
710 // Turn Current into a single-item list.
711 Current->Next = nullptr;
712
713 // Save Current in the first available slot, merging on collisions.
714 unsigned I;
715 for (I = 0; I < NumSlots; ++I) {
716 if (!Slots[I])
717 break;
718
719 // Merge two lists, doubling the size of Current and emptying slot I.
720 //
721 // Since the uses in Slots[I] originally preceded those in Current, send
722 // Slots[I] in as the left parameter to maintain a stable sort.
723 Current = mergeUseLists(Slots[I], Current, Cmp);
724 Slots[I] = nullptr;
725 }
726 // Check if this is a new slot.
727 if (I == NumSlots) {
728 ++NumSlots;
729 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32")((NumSlots <= MaxSlots && "Use list bigger than 2^32"
) ? static_cast<void> (0) : __assert_fail ("NumSlots <= MaxSlots && \"Use list bigger than 2^32\""
, "/build/llvm-toolchain-snapshot-9~svn361465/include/llvm/IR/Value.h"
, 729, __PRETTY_FUNCTION__))
;
730 }
731
732 // Found an open slot.
733 Slots[I] = Current;
734 }
735
736 // Merge all the lists together.
737 assert(Next && "Expected one more Use")((Next && "Expected one more Use") ? static_cast<void
> (0) : __assert_fail ("Next && \"Expected one more Use\""
, "/build/llvm-toolchain-snapshot-9~svn361465/include/llvm/IR/Value.h"
, 737, __PRETTY_FUNCTION__))
;
738 assert(!Next->Next && "Expected only one Use")((!Next->Next && "Expected only one Use") ? static_cast
<void> (0) : __assert_fail ("!Next->Next && \"Expected only one Use\""
, "/build/llvm-toolchain-snapshot-9~svn361465/include/llvm/IR/Value.h"
, 738, __PRETTY_FUNCTION__))
;
739 UseList = Next;
740 for (unsigned I = 0; I < NumSlots; ++I)
741 if (Slots[I])
742 // Since the uses in Slots[I] originally preceded those in UseList, send
743 // Slots[I] in as the left parameter to maintain a stable sort.
744 UseList = mergeUseLists(Slots[I], UseList, Cmp);
745
746 // Fix the Prev pointers.
747 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
748 I->setPrev(Prev);
749 Prev = &I->Next;
750 }
751}
752
753// isa - Provide some specializations of isa so that we don't have to include
754// the subtype header files to test to see if the value is a subclass...
755//
756template <> struct isa_impl<Constant, Value> {
757 static inline bool doit(const Value &Val) {
758 static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
759 return Val.getValueID() <= Value::ConstantLastVal;
760 }
761};
762
763template <> struct isa_impl<ConstantData, Value> {
764 static inline bool doit(const Value &Val) {
765 return Val.getValueID() >= Value::ConstantDataFirstVal &&
766 Val.getValueID() <= Value::ConstantDataLastVal;
767 }
768};
769
770template <> struct isa_impl<ConstantAggregate, Value> {
771 static inline bool doit(const Value &Val) {
772 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
773 Val.getValueID() <= Value::ConstantAggregateLastVal;
774 }
775};
776
777template <> struct isa_impl<Argument, Value> {
778 static inline bool doit (const Value &Val) {
779 return Val.getValueID() == Value::ArgumentVal;
780 }
781};
782
783template <> struct isa_impl<InlineAsm, Value> {
784 static inline bool doit(const Value &Val) {
785 return Val.getValueID() == Value::InlineAsmVal;
786 }
787};
788
789template <> struct isa_impl<Instruction, Value> {
790 static inline bool doit(const Value &Val) {
791 return Val.getValueID() >= Value::InstructionVal;
792 }
793};
794
795template <> struct isa_impl<BasicBlock, Value> {
796 static inline bool doit(const Value &Val) {
797 return Val.getValueID() == Value::BasicBlockVal;
798 }
799};
800
801template <> struct isa_impl<Function, Value> {
802 static inline bool doit(const Value &Val) {
803 return Val.getValueID() == Value::FunctionVal;
804 }
805};
806
807template <> struct isa_impl<GlobalVariable, Value> {
808 static inline bool doit(const Value &Val) {
809 return Val.getValueID() == Value::GlobalVariableVal;
810 }
811};
812
813template <> struct isa_impl<GlobalAlias, Value> {
814 static inline bool doit(const Value &Val) {
815 return Val.getValueID() == Value::GlobalAliasVal;
816 }
817};
818
819template <> struct isa_impl<GlobalIFunc, Value> {
820 static inline bool doit(const Value &Val) {
821 return Val.getValueID() == Value::GlobalIFuncVal;
822 }
823};
824
825template <> struct isa_impl<GlobalIndirectSymbol, Value> {
826 static inline bool doit(const Value &Val) {
827 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
828 }
829};
830
831template <> struct isa_impl<GlobalValue, Value> {
832 static inline bool doit(const Value &Val) {
833 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
834 }
835};
836
837template <> struct isa_impl<GlobalObject, Value> {
838 static inline bool doit(const Value &Val) {
839 return isa<GlobalVariable>(Val) || isa<Function>(Val);
840 }
841};
842
843// Create wrappers for C Binding types (see CBindingWrapping.h).
844DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)inline Value *unwrap(LLVMValueRef P) { return reinterpret_cast
<Value*>(P); } inline LLVMValueRef wrap(const Value *P)
{ return reinterpret_cast<LLVMValueRef>(const_cast<
Value*>(P)); } template<typename T> inline T *unwrap
(LLVMValueRef P) { return cast<T>(unwrap(P)); }
845
846// Specialized opaque value conversions.
847inline Value **unwrap(LLVMValueRef *Vals) {
848 return reinterpret_cast<Value**>(Vals);
849}
850
851template<typename T>
852inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
853#ifndef NDEBUG
854 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
855 unwrap<T>(*I); // For side effect of calling assert on invalid usage.
856#endif
857 (void)Length;
858 return reinterpret_cast<T**>(Vals);
859}
860
861inline LLVMValueRef *wrap(const Value **Vals) {
862 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
863}
864
865} // end namespace llvm
866
867#endif // LLVM_IR_VALUE_H