Bug Summary

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