blob: 387154ecfe537fd820dfa83271b58d5fcd452f99 [file] [log] [blame]
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001//===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Vlad Tsyrklevich3b59a8a2018-04-26 17:34:51 +000010// This library implements `print` family of functions in classes like
11// Module, Function, Value, etc. In-memory representation of those classes is
12// converted to IR strings.
Chris Lattner2f7c9632001-06-06 20:29:01 +000013//
Chris Lattner189088e2002-04-12 18:21:53 +000014// Note that these routines must be extremely tolerant of various errors in the
Chris Lattnerf70da102003-05-08 02:44:12 +000015// LLVM code, because it can be used for debugging transformations.
Chris Lattner189088e2002-04-12 18:21:53 +000016//
Chris Lattner2f7c9632001-06-06 20:29:01 +000017//===----------------------------------------------------------------------===//
18
Eugene Zelenkode6cce22017-06-19 22:05:08 +000019#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/DenseMap.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000023#include "llvm/ADT/None.h"
24#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/ADT/STLExtras.h"
Benjamin Kramerba05a782015-03-17 19:53:41 +000026#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/SmallString.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000028#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/ADT/StringExtras.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000030#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/iterator_range.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/BinaryFormat/Dwarf.h"
Nico Weber432a3882018-04-30 14:59:11 +000033#include "llvm/Config/llvm-config.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000034#include "llvm/IR/Argument.h"
Chandler Carruth9aca9182014-01-07 12:34:26 +000035#include "llvm/IR/AssemblyAnnotationWriter.h"
Reid Klecknereb9dd5b2017-04-10 23:31:05 +000036#include "llvm/IR/Attributes.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000037#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000038#include "llvm/IR/CFG.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000039#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/CallingConv.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000041#include "llvm/IR/Comdat.h"
42#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Constants.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000044#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000046#include "llvm/IR/Function.h"
47#include "llvm/IR/GlobalAlias.h"
48#include "llvm/IR/GlobalIFunc.h"
49#include "llvm/IR/GlobalIndirectSymbol.h"
50#include "llvm/IR/GlobalObject.h"
51#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/GlobalVariable.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000053#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/InlineAsm.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000055#include "llvm/IR/InstrTypes.h"
56#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/LLVMContext.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000059#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +000061#include "llvm/IR/ModuleSlotTracker.h"
Teresa Johnson08d5b4e2018-05-26 02:34:13 +000062#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/Operator.h"
Igor Laevsky2aa8caf2015-05-05 13:20:42 +000064#include "llvm/IR/Statepoint.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000065#include "llvm/IR/Type.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000066#include "llvm/IR/TypeFinder.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000067#include "llvm/IR/Use.h"
Benjamin Kramerba05a782015-03-17 19:53:41 +000068#include "llvm/IR/UseListOrder.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000069#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
71#include "llvm/Support/AtomicOrdering.h"
72#include "llvm/Support/Casting.h"
73#include "llvm/Support/Compiler.h"
David Greenec7f9b122010-01-05 01:29:26 +000074#include "llvm/Support/Debug.h"
Torok Edwin6dd27302009-07-08 18:01:40 +000075#include "llvm/Support/ErrorHandling.h"
Justin Bogner93289572015-12-04 02:14:34 +000076#include "llvm/Support/Format.h"
Dan Gohmane2745262009-08-12 17:23:50 +000077#include "llvm/Support/FormattedStream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000078#include "llvm/Support/raw_ostream.h"
Chris Lattnerfee714f2001-09-07 16:36:04 +000079#include <algorithm>
Eugene Zelenkode6cce22017-06-19 22:05:08 +000080#include <cassert>
Reid Spencerbdf03b42007-05-22 19:27:35 +000081#include <cctype>
Eugene Zelenkode6cce22017-06-19 22:05:08 +000082#include <cstddef>
83#include <cstdint>
84#include <iterator>
85#include <memory>
86#include <string>
87#include <tuple>
88#include <utility>
89#include <vector>
90
Chris Lattner189d19f2003-11-21 20:23:48 +000091using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000092
Reid Spencer294715b2005-05-15 16:13:11 +000093// Make virtual table appear in this compilation unit.
Eugene Zelenkode6cce22017-06-19 22:05:08 +000094AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
Reid Spencer294715b2005-05-15 16:13:11 +000095
Chris Lattner3eee99c2008-08-19 04:36:02 +000096//===----------------------------------------------------------------------===//
97// Helper Functions
98//===----------------------------------------------------------------------===//
99
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000100namespace {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000101
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000102struct OrderMap {
103 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
104
105 unsigned size() const { return IDs.size(); }
106 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000107
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000108 std::pair<unsigned, bool> lookup(const Value *V) const {
109 return IDs.lookup(V);
110 }
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000111
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000112 void index(const Value *V) {
113 // Explicitly sequence get-size and insert-value operations to avoid UB.
114 unsigned ID = IDs.size() + 1;
115 IDs[V].first = ID;
116 }
117};
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000118
119} // end anonymous namespace
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000120
121static void orderValue(const Value *V, OrderMap &OM) {
122 if (OM.lookup(V).first)
123 return;
124
125 if (const Constant *C = dyn_cast<Constant>(V))
126 if (C->getNumOperands() && !isa<GlobalValue>(C))
127 for (const Value *Op : C->operands())
128 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
129 orderValue(Op, OM);
130
131 // Note: we cannot cache this lookup above, since inserting into the map
132 // changes the map's size, and thus affects the other IDs.
133 OM.index(V);
134}
135
136static OrderMap orderModule(const Module *M) {
137 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
138 // and ValueEnumerator::incorporateFunction().
139 OrderMap OM;
140
141 for (const GlobalVariable &G : M->globals()) {
142 if (G.hasInitializer())
143 if (!isa<GlobalValue>(G.getInitializer()))
144 orderValue(G.getInitializer(), OM);
145 orderValue(&G, OM);
146 }
147 for (const GlobalAlias &A : M->aliases()) {
148 if (!isa<GlobalValue>(A.getAliasee()))
149 orderValue(A.getAliasee(), OM);
150 orderValue(&A, OM);
151 }
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000152 for (const GlobalIFunc &I : M->ifuncs()) {
153 if (!isa<GlobalValue>(I.getResolver()))
154 orderValue(I.getResolver(), OM);
155 orderValue(&I, OM);
156 }
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000157 for (const Function &F : *M) {
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000158 for (const Use &U : F.operands())
159 if (!isa<GlobalValue>(U.get()))
160 orderValue(U.get(), OM);
David Majnemer7fddecc2015-06-17 20:52:32 +0000161
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000162 orderValue(&F, OM);
163
164 if (F.isDeclaration())
165 continue;
166
167 for (const Argument &A : F.args())
168 orderValue(&A, OM);
169 for (const BasicBlock &BB : F) {
170 orderValue(&BB, OM);
171 for (const Instruction &I : BB) {
172 for (const Value *Op : I.operands())
173 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
174 isa<InlineAsm>(*Op))
175 orderValue(Op, OM);
176 orderValue(&I, OM);
177 }
178 }
179 }
180 return OM;
181}
182
183static void predictValueUseListOrderImpl(const Value *V, const Function *F,
184 unsigned ID, const OrderMap &OM,
185 UseListOrderStack &Stack) {
186 // Predict use-list order for this one.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000187 using Entry = std::pair<const Use *, unsigned>;
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000188 SmallVector<Entry, 64> List;
189 for (const Use &U : V->uses())
190 // Check if this user will be serialized.
191 if (OM.lookup(U.getUser()).first)
192 List.push_back(std::make_pair(&U, List.size()));
193
194 if (List.size() < 2)
195 // We may have lost some users.
196 return;
197
198 bool GetsReversed =
199 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
200 if (auto *BA = dyn_cast<BlockAddress>(V))
201 ID = OM.lookup(BA->getBasicBlock()).first;
Mandeep Singh Grangf3555652018-04-05 21:52:24 +0000202 llvm::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000203 const Use *LU = L.first;
204 const Use *RU = R.first;
205 if (LU == RU)
206 return false;
207
208 auto LID = OM.lookup(LU->getUser()).first;
209 auto RID = OM.lookup(RU->getUser()).first;
210
211 // If ID is 4, then expect: 7 6 5 1 2 3.
212 if (LID < RID) {
213 if (GetsReversed)
214 if (RID <= ID)
215 return true;
216 return false;
217 }
218 if (RID < LID) {
219 if (GetsReversed)
220 if (LID <= ID)
221 return false;
222 return true;
223 }
224
225 // LID and RID are equal, so we have different operands of the same user.
226 // Assume operands are added in order for all instructions.
227 if (GetsReversed)
228 if (LID <= ID)
229 return LU->getOperandNo() < RU->getOperandNo();
230 return LU->getOperandNo() > RU->getOperandNo();
231 });
232
233 if (std::is_sorted(
234 List.begin(), List.end(),
235 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
236 // Order is already correct.
237 return;
238
239 // Store the shuffle.
240 Stack.emplace_back(V, F, List.size());
241 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
242 for (size_t I = 0, E = List.size(); I != E; ++I)
243 Stack.back().Shuffle[I] = List[I].second;
244}
245
246static void predictValueUseListOrder(const Value *V, const Function *F,
247 OrderMap &OM, UseListOrderStack &Stack) {
248 auto &IDPair = OM[V];
249 assert(IDPair.first && "Unmapped value");
250 if (IDPair.second)
251 // Already predicted.
252 return;
253
254 // Do the actual prediction.
255 IDPair.second = true;
256 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
257 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
258
259 // Recursive descent into constants.
260 if (const Constant *C = dyn_cast<Constant>(V))
261 if (C->getNumOperands()) // Visit GlobalValues.
262 for (const Value *Op : C->operands())
263 if (isa<Constant>(Op)) // Visit GlobalValues.
264 predictValueUseListOrder(Op, F, OM, Stack);
265}
266
267static UseListOrderStack predictUseListOrder(const Module *M) {
268 OrderMap OM = orderModule(M);
269
270 // Use-list orders need to be serialized after all the users have been added
271 // to a value, or else the shuffles will be incomplete. Store them per
272 // function in a stack.
273 //
274 // Aside from function order, the order of values doesn't matter much here.
275 UseListOrderStack Stack;
276
277 // We want to visit the functions backward now so we can list function-local
278 // constants in the last Function they're used in. Module-level constants
279 // have already been visited above.
Pete Cooper7679afd2015-07-24 21:13:43 +0000280 for (const Function &F : make_range(M->rbegin(), M->rend())) {
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000281 if (F.isDeclaration())
282 continue;
283 for (const BasicBlock &BB : F)
284 predictValueUseListOrder(&BB, &F, OM, Stack);
285 for (const Argument &A : F.args())
286 predictValueUseListOrder(&A, &F, OM, Stack);
287 for (const BasicBlock &BB : F)
288 for (const Instruction &I : BB)
289 for (const Value *Op : I.operands())
290 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
291 predictValueUseListOrder(Op, &F, OM, Stack);
292 for (const BasicBlock &BB : F)
293 for (const Instruction &I : BB)
294 predictValueUseListOrder(&I, &F, OM, Stack);
295 }
296
297 // Visit globals last.
298 for (const GlobalVariable &G : M->globals())
299 predictValueUseListOrder(&G, nullptr, OM, Stack);
300 for (const Function &F : *M)
301 predictValueUseListOrder(&F, nullptr, OM, Stack);
302 for (const GlobalAlias &A : M->aliases())
303 predictValueUseListOrder(&A, nullptr, OM, Stack);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000304 for (const GlobalIFunc &I : M->ifuncs())
305 predictValueUseListOrder(&I, nullptr, OM, Stack);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000306 for (const GlobalVariable &G : M->globals())
307 if (G.hasInitializer())
308 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
309 for (const GlobalAlias &A : M->aliases())
310 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000311 for (const GlobalIFunc &I : M->ifuncs())
312 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000313 for (const Function &F : *M)
Vedant Kumar3a63fb32015-12-19 08:52:49 +0000314 for (const Use &U : F.operands())
315 predictValueUseListOrder(U.get(), nullptr, OM, Stack);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000316
317 return Stack;
318}
319
Chris Lattner3eee99c2008-08-19 04:36:02 +0000320static const Module *getModuleFromVal(const Value *V) {
321 if (const Argument *MA = dyn_cast<Argument>(V))
Craig Topperc6207612014-04-09 06:08:46 +0000322 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000323
Chris Lattner3eee99c2008-08-19 04:36:02 +0000324 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
Craig Topperc6207612014-04-09 06:08:46 +0000325 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000326
Chris Lattner3eee99c2008-08-19 04:36:02 +0000327 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Craig Topperc6207612014-04-09 06:08:46 +0000328 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
329 return M ? M->getParent() : nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000330 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000331
Chris Lattner3eee99c2008-08-19 04:36:02 +0000332 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
333 return GV->getParent();
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000334
335 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
336 for (const User *U : MAV->users())
337 if (isa<Instruction>(U))
338 if (const Module *M = getModuleFromVal(U))
339 return M;
340 return nullptr;
341 }
342
Craig Topperc6207612014-04-09 06:08:46 +0000343 return nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000344}
345
Bill Wendling90bc19c2013-02-20 07:21:42 +0000346static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
Micah Villmow857186d2012-09-13 15:11:12 +0000347 switch (cc) {
Bill Wendling90bc19c2013-02-20 07:21:42 +0000348 default: Out << "cc" << cc; break;
349 case CallingConv::Fast: Out << "fastcc"; break;
350 case CallingConv::Cold: Out << "coldcc"; break;
Andrew Trick5ae6ed82013-11-11 22:40:22 +0000351 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
352 case CallingConv::AnyReg: Out << "anyregcc"; break;
Juergen Ributzkae6250132014-01-17 19:47:03 +0000353 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
354 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
Manman Ren19c7bbe2015-12-04 17:40:13 +0000355 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
Reid Kleckner35fc3632014-12-01 21:04:44 +0000356 case CallingConv::GHC: Out << "ghccc"; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000357 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
358 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
359 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
Oren Ben Simhon92ccbf22016-10-13 07:53:43 +0000360 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
Reid Kleckner9ccce992014-10-28 01:29:26 +0000361 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000362 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
363 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
364 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
365 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
Sander de Smalen4dbc5122018-09-12 08:54:06 +0000366 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000367 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
Dylan McKay4fd0d4a2016-03-03 10:08:02 +0000368 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
369 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
Bill Wendling90bc19c2013-02-20 07:21:42 +0000370 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
371 case CallingConv::PTX_Device: Out << "ptx_device"; break;
Charles Davise8f297c2013-07-12 06:02:35 +0000372 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
Martin Storsjo2f24e932017-07-17 20:05:19 +0000373 case CallingConv::Win64: Out << "win64cc"; break;
Michael Kupersteine31b4862013-12-15 10:01:20 +0000374 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
375 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
Manman Renf8bdd882016-04-05 22:41:47 +0000376 case CallingConv::Swift: Out << "swiftcc"; break;
Amjad Aboud60b5e1b2015-12-21 14:07:14 +0000377 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
Maksim Panchenkocce239c2015-09-29 22:09:16 +0000378 case CallingConv::HHVM: Out << "hhvmcc"; break;
379 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +0000380 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +0000381 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
Marek Olsaka302a7362017-05-02 15:41:10 +0000382 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
Tim Renoufef1ae8f2017-09-29 09:51:22 +0000383 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
Nicolai Haehnledf3a20c2016-04-06 19:40:20 +0000384 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
385 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
386 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
Nikolay Haustov1f7732a2016-05-06 09:07:29 +0000387 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
Micah Villmow857186d2012-09-13 15:11:12 +0000388 }
389}
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000390
Chris Lattner3eee99c2008-08-19 04:36:02 +0000391enum PrefixType {
392 GlobalPrefix,
David Majnemerdad0a642014-06-27 18:19:56 +0000393 ComdatPrefix,
Chris Lattner3eee99c2008-08-19 04:36:02 +0000394 LabelPrefix,
Daniel Dunbar389529a2008-10-14 23:28:09 +0000395 LocalPrefix,
396 NoPrefix
Chris Lattner3eee99c2008-08-19 04:36:02 +0000397};
398
Alex Lorenz2b7f2652015-07-21 16:50:35 +0000399void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
Jay Foadf7adb322011-04-24 14:30:00 +0000400 assert(!Name.empty() && "Cannot get empty name!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000401
Chris Lattner3eee99c2008-08-19 04:36:02 +0000402 // Scan the name to see if it needs quotes first.
Guy Benyei83c74e92013-02-12 21:21:59 +0000403 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
Chris Lattner3eee99c2008-08-19 04:36:02 +0000404 if (!NeedsQuotes) {
Daniel Dunbare03eecb2009-07-25 23:55:21 +0000405 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
Aaron Ballmaned9b0a92012-07-16 16:18:18 +0000406 // By making this unsigned, the value passed in to isalnum will always be
407 // in the range 0-255. This is important when building with MSVC because
408 // its implementation will assert. This situation can arise when dealing
409 // with UTF-8 multibyte characters.
410 unsigned char C = Name[i];
Guy Benyei83c74e92013-02-12 21:21:59 +0000411 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
412 C != '_') {
Chris Lattner3eee99c2008-08-19 04:36:02 +0000413 NeedsQuotes = true;
414 break;
415 }
416 }
417 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000418
Chris Lattner3eee99c2008-08-19 04:36:02 +0000419 // If we didn't need any quotes, just write out the name in one blast.
420 if (!NeedsQuotes) {
Daniel Dunbare03eecb2009-07-25 23:55:21 +0000421 OS << Name;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000422 return;
423 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000424
Chris Lattner3eee99c2008-08-19 04:36:02 +0000425 // Okay, we need quotes. Output the quotes and escape any scary characters as
426 // needed.
427 OS << '"';
Jonas Devlieghere745918ff2018-05-31 17:01:42 +0000428 printEscapedString(Name, OS);
Chris Lattner3eee99c2008-08-19 04:36:02 +0000429 OS << '"';
430}
431
Alex Lorenz2b7f2652015-07-21 16:50:35 +0000432/// Turn the specified name into an 'LLVM name', which is either prefixed with %
433/// (if the string only contains simple characters) or is surrounded with ""'s
434/// (if it has special chars in it). Print it out.
435static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
436 switch (Prefix) {
437 case NoPrefix:
438 break;
439 case GlobalPrefix:
440 OS << '@';
441 break;
442 case ComdatPrefix:
443 OS << '$';
444 break;
445 case LabelPrefix:
446 break;
447 case LocalPrefix:
448 OS << '%';
449 break;
450 }
451 printLLVMNameWithoutPrefix(OS, Name);
452}
453
454/// Turn the specified name into an 'LLVM name', which is either prefixed with %
455/// (if the string only contains simple characters) or is surrounded with ""'s
456/// (if it has special chars in it). Print it out.
Dan Gohman12dad632009-08-12 20:56:03 +0000457static void PrintLLVMName(raw_ostream &OS, const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000458 PrintLLVMName(OS, V->getName(),
Chris Lattner3eee99c2008-08-19 04:36:02 +0000459 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
460}
461
Benjamin Kramerba05a782015-03-17 19:53:41 +0000462namespace {
Benjamin Kramerba05a782015-03-17 19:53:41 +0000463
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000464class TypePrinting {
465public:
Roman Tereshind96de6f2018-03-22 21:29:07 +0000466 TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
Benjamin Kramerba05a782015-03-17 19:53:41 +0000467
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000468 TypePrinting(const TypePrinting &) = delete;
469 TypePrinting &operator=(const TypePrinting &) = delete;
Benjamin Kramerba05a782015-03-17 19:53:41 +0000470
Roman Tereshind96de6f2018-03-22 21:29:07 +0000471 /// The named types that are used by the current module.
472 TypeFinder &getNamedTypes();
473
474 /// The numbered types, number to type mapping.
475 std::vector<StructType *> &getNumberedTypes();
476
477 bool empty();
Benjamin Kramerba05a782015-03-17 19:53:41 +0000478
479 void print(Type *Ty, raw_ostream &OS);
480
481 void printStructBody(StructType *Ty, raw_ostream &OS);
Roman Tereshind96de6f2018-03-22 21:29:07 +0000482
483private:
484 void incorporateTypes();
485
486 /// A module to process lazily when needed. Set to nullptr as soon as used.
487 const Module *DeferredM;
488
489 TypeFinder NamedTypes;
490
491 // The numbered types, along with their value.
492 DenseMap<StructType *, unsigned> Type2Number;
493
494 std::vector<StructType *> NumberedTypes;
Benjamin Kramerba05a782015-03-17 19:53:41 +0000495};
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000496
497} // end anonymous namespace
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000498
Roman Tereshind96de6f2018-03-22 21:29:07 +0000499TypeFinder &TypePrinting::getNamedTypes() {
500 incorporateTypes();
501 return NamedTypes;
502}
503
504std::vector<StructType *> &TypePrinting::getNumberedTypes() {
505 incorporateTypes();
506
507 // We know all the numbers that each type is used and we know that it is a
508 // dense assignment. Convert the map to an index table, if it's not done
509 // already (judging from the sizes):
510 if (NumberedTypes.size() == Type2Number.size())
511 return NumberedTypes;
512
513 NumberedTypes.resize(Type2Number.size());
514 for (const auto &P : Type2Number) {
515 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
516 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
517 NumberedTypes[P.second] = P.first;
518 }
519 return NumberedTypes;
520}
521
522bool TypePrinting::empty() {
523 incorporateTypes();
524 return NamedTypes.empty() && Type2Number.empty();
525}
526
527void TypePrinting::incorporateTypes() {
528 if (!DeferredM)
529 return;
530
531 NamedTypes.run(*DeferredM, false);
532 DeferredM = nullptr;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000533
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000534 // The list of struct types we got back includes all the struct types, split
535 // the unnamed ones out to a numbering and remove the anonymous structs.
536 unsigned NextNumber = 0;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000537
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000538 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
539 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
540 StructType *STy = *I;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000541
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000542 // Ignore anonymous types.
Chris Lattner01beceb2011-08-12 18:07:07 +0000543 if (STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000544 continue;
Andrew Trickec4b6e72011-09-30 19:48:58 +0000545
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000546 if (STy->getName().empty())
Roman Tereshind96de6f2018-03-22 21:29:07 +0000547 Type2Number[STy] = NextNumber++;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000548 else
549 *NextToUse++ = STy;
550 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000551
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000552 NamedTypes.erase(NextToUse, NamedTypes.end());
553}
554
Roman Tereshind96de6f2018-03-22 21:29:07 +0000555/// Write the specified type to the specified raw_ostream, making use of type
556/// names or up references to shorten the type name where possible.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000557void TypePrinting::print(Type *Ty, raw_ostream &OS) {
Chris Lattner0f578952009-02-28 20:25:14 +0000558 switch (Ty->getTypeID()) {
Rafael Espindolaba7df702013-12-07 02:27:52 +0000559 case Type::VoidTyID: OS << "void"; return;
560 case Type::HalfTyID: OS << "half"; return;
561 case Type::FloatTyID: OS << "float"; return;
562 case Type::DoubleTyID: OS << "double"; return;
563 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
564 case Type::FP128TyID: OS << "fp128"; return;
565 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
566 case Type::LabelTyID: OS << "label"; return;
567 case Type::MetadataTyID: OS << "metadata"; return;
568 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
David Majnemerb611e3f2015-08-14 05:09:07 +0000569 case Type::TokenTyID: OS << "token"; return;
Chris Lattner68318b12009-02-28 21:18:43 +0000570 case Type::IntegerTyID:
Chris Lattner06a23212009-02-28 21:27:31 +0000571 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000572 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573
Chris Lattner07d88292009-02-28 20:35:42 +0000574 case Type::FunctionTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000575 FunctionType *FTy = cast<FunctionType>(Ty);
576 print(FTy->getReturnType(), OS);
Chris Lattner06a23212009-02-28 21:27:31 +0000577 OS << " (";
Chris Lattner07d88292009-02-28 20:35:42 +0000578 for (FunctionType::param_iterator I = FTy->param_begin(),
579 E = FTy->param_end(); I != E; ++I) {
580 if (I != FTy->param_begin())
Chris Lattner06a23212009-02-28 21:27:31 +0000581 OS << ", ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000582 print(*I, OS);
Chris Lattner0f578952009-02-28 20:25:14 +0000583 }
Chris Lattner07d88292009-02-28 20:35:42 +0000584 if (FTy->isVarArg()) {
Chris Lattner06a23212009-02-28 21:27:31 +0000585 if (FTy->getNumParams()) OS << ", ";
586 OS << "...";
Chris Lattner0f578952009-02-28 20:25:14 +0000587 }
Chris Lattner06a23212009-02-28 21:27:31 +0000588 OS << ')';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000589 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000590 }
591 case Type::StructTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000592 StructType *STy = cast<StructType>(Ty);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000593
Chris Lattner01beceb2011-08-12 18:07:07 +0000594 if (STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000595 return printStructBody(STy, OS);
596
597 if (!STy->getName().empty())
598 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000599
Roman Tereshind96de6f2018-03-22 21:29:07 +0000600 incorporateTypes();
601 const auto I = Type2Number.find(STy);
602 if (I != Type2Number.end())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000603 OS << '%' << I->second;
604 else // Not enumerated, print the hex address.
Benjamin Kramer4e8b4632011-11-02 17:24:36 +0000605 OS << "%\"type " << STy << '\"';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000606 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000607 }
608 case Type::PointerTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000609 PointerType *PTy = cast<PointerType>(Ty);
610 print(PTy->getElementType(), OS);
Chris Lattner07d88292009-02-28 20:35:42 +0000611 if (unsigned AddressSpace = PTy->getAddressSpace())
Chris Lattner06a23212009-02-28 21:27:31 +0000612 OS << " addrspace(" << AddressSpace << ')';
613 OS << '*';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000614 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000615 }
616 case Type::ArrayTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000617 ArrayType *ATy = cast<ArrayType>(Ty);
Chris Lattner06a23212009-02-28 21:27:31 +0000618 OS << '[' << ATy->getNumElements() << " x ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000619 print(ATy->getElementType(), OS);
Chris Lattner06a23212009-02-28 21:27:31 +0000620 OS << ']';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000621 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000622 }
623 case Type::VectorTyID: {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000624 VectorType *PTy = cast<VectorType>(Ty);
Chris Lattner06a23212009-02-28 21:27:31 +0000625 OS << "<" << PTy->getNumElements() << " x ";
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000626 print(PTy->getElementType(), OS);
Chris Lattner06a23212009-02-28 21:27:31 +0000627 OS << '>';
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000628 return;
Chris Lattner07d88292009-02-28 20:35:42 +0000629 }
Chris Lattner0f578952009-02-28 20:25:14 +0000630 }
Rafael Espindolaba7df702013-12-07 02:27:52 +0000631 llvm_unreachable("Invalid TypeID");
Chris Lattner0f578952009-02-28 20:25:14 +0000632}
633
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000634void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
635 if (STy->isOpaque()) {
636 OS << "opaque";
637 return;
Chris Lattner0f578952009-02-28 20:25:14 +0000638 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000639
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000640 if (STy->isPacked())
641 OS << '<';
Andrew Trickec4b6e72011-09-30 19:48:58 +0000642
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000643 if (STy->getNumElements() == 0) {
644 OS << "{}";
645 } else {
646 StructType::element_iterator I = STy->element_begin();
647 OS << "{ ";
648 print(*I++, OS);
649 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
650 OS << ", ";
651 print(*I, OS);
Chris Lattner3243ea12009-03-01 00:03:38 +0000652 }
Andrew Trickec4b6e72011-09-30 19:48:58 +0000653
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000654 OS << " }";
Chris Lattner92c5c122009-02-28 23:20:19 +0000655 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000656 if (STy->isPacked())
657 OS << '>';
Chris Lattner92c5c122009-02-28 23:20:19 +0000658}
659
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000660namespace llvm {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000661
Chris Lattner3eee99c2008-08-19 04:36:02 +0000662//===----------------------------------------------------------------------===//
663// SlotTracker Class: Enumerate slot numbers for unnamed values
664//===----------------------------------------------------------------------===//
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000665/// This class provides computation of slot numbers for LLVM Assembly writing.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000666///
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000667class SlotTracker {
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000668public:
Devang Patel983c6b12009-07-08 21:44:25 +0000669 /// ValueMap - A mapping of Values to slot numbers.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000670 using ValueMap = DenseMap<const Value *, unsigned>;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
672private:
Devang Patel983c6b12009-07-08 21:44:25 +0000673 /// TheModule - The module for which we are holding slot numbers.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000674 const Module* TheModule;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000675
Devang Patel983c6b12009-07-08 21:44:25 +0000676 /// TheFunction - The function for which we are holding slot numbers.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000677 const Function* TheFunction = nullptr;
678 bool FunctionProcessed = false;
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000679 bool ShouldInitializeAllMetadata;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000680
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000681 /// The summary index for which we are holding slot numbers.
682 const ModuleSummaryIndex *TheIndex = nullptr;
683
Jay Foaddbb221d2011-07-11 07:28:49 +0000684 /// mMap - The slot map for the module level data.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000685 ValueMap mMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000686 unsigned mNext = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687
Jay Foaddbb221d2011-07-11 07:28:49 +0000688 /// fMap - The slot map for the function level data.
Chris Lattner393b7cd2008-08-17 04:17:45 +0000689 ValueMap fMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000690 unsigned fNext = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
Devang Patel983c6b12009-07-08 21:44:25 +0000692 /// mdnMap - Map for MDNodes.
Chris Lattnercf4a76e2009-12-31 02:20:11 +0000693 DenseMap<const MDNode*, unsigned> mdnMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000694 unsigned mdnNext = 0;
Bill Wendling829b4782013-02-11 08:43:33 +0000695
696 /// asMap - The slot map for attribute sets.
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000697 DenseMap<AttributeSet, unsigned> asMap;
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000698 unsigned asNext = 0;
699
Teresa Johnson8fc76662018-07-02 22:09:23 +0000700 /// ModulePathMap - The slot map for Module paths used in the summary index.
701 StringMap<unsigned> ModulePathMap;
702 unsigned ModulePathNext = 0;
703
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000704 /// GUIDMap - The slot map for GUIDs used in the summary index.
705 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
706 unsigned GUIDNext = 0;
707
Teresa Johnson7fb39df2018-09-25 20:14:40 +0000708 /// TypeIdMap - The slot map for type ids used in the summary index.
709 StringMap<unsigned> TypeIdMap;
710 unsigned TypeIdNext = 0;
711
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000712public:
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000713 /// Construct from a module.
714 ///
715 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
716 /// functions, giving correct numbering for metadata referenced only from
717 /// within a function (even if no functions have been initialized).
718 explicit SlotTracker(const Module *M,
719 bool ShouldInitializeAllMetadata = false);
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000720
Chris Lattner393b7cd2008-08-17 04:17:45 +0000721 /// Construct from a function, starting out in incorp state.
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000722 ///
723 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
724 /// functions, giving correct numbering for metadata referenced only from
725 /// within a function (even if no functions have been initialized).
726 explicit SlotTracker(const Function *F,
727 bool ShouldInitializeAllMetadata = false);
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000728
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000729 /// Construct from a module summary index.
730 explicit SlotTracker(const ModuleSummaryIndex *Index);
731
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000732 SlotTracker(const SlotTracker &) = delete;
733 SlotTracker &operator=(const SlotTracker &) = delete;
734
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000735 /// Return the slot number of the specified value in it's type
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000736 /// plane. If something is not in the SlotTracker, return -1.
Chris Lattner5e043322007-01-11 03:54:27 +0000737 int getLocalSlot(const Value *V);
738 int getGlobalSlot(const GlobalValue *V);
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000739 int getMetadataSlot(const MDNode *N);
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000740 int getAttributeGroupSlot(AttributeSet AS);
Teresa Johnson8fc76662018-07-02 22:09:23 +0000741 int getModulePathSlot(StringRef Path);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000742 int getGUIDSlot(GlobalValue::GUID GUID);
Teresa Johnson7fb39df2018-09-25 20:14:40 +0000743 int getTypeIdSlot(StringRef Id);
Reid Spencer8beac692004-06-09 15:26:53 +0000744
Misha Brukmanb1c93172005-04-21 23:48:37 +0000745 /// If you'd like to deal with a function instead of just a module, use
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000746 /// this method to get its data into the SlotTracker.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000747 void incorporateFunction(const Function *F) {
748 TheFunction = F;
Reid Spencerb0ac8c42004-08-16 07:46:33 +0000749 FunctionProcessed = false;
750 }
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000751
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +0000752 const Function *getFunction() const { return TheFunction; }
753
Misha Brukmanb1c93172005-04-21 23:48:37 +0000754 /// After calling incorporateFunction, use this method to remove the
Chris Lattnere36fd8a2008-08-19 04:26:57 +0000755 /// most recently incorporated function from the SlotTracker. This
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000756 /// will reset the state of the machine back to just the module contents.
757 void purgeFunction();
758
Devang Patel983c6b12009-07-08 21:44:25 +0000759 /// MDNode map iterators.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000760 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
761
Chris Lattnercf4a76e2009-12-31 02:20:11 +0000762 mdn_iterator mdn_begin() { return mdnMap.begin(); }
763 mdn_iterator mdn_end() { return mdnMap.end(); }
764 unsigned mdn_size() const { return mdnMap.size(); }
765 bool mdn_empty() const { return mdnMap.empty(); }
Devang Patel983c6b12009-07-08 21:44:25 +0000766
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000767 /// AttributeSet map iterators.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000768 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
769
Bill Wendling829b4782013-02-11 08:43:33 +0000770 as_iterator as_begin() { return asMap.begin(); }
771 as_iterator as_end() { return asMap.end(); }
772 unsigned as_size() const { return asMap.size(); }
773 bool as_empty() const { return asMap.empty(); }
774
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000775 /// GUID map iterators.
776 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
777
778 /// These functions do the actual initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +0000779 inline void initializeIfNeeded();
780 void initializeIndexIfNeeded();
Reid Spencer56010e42004-05-26 21:56:09 +0000781
Devang Patel983c6b12009-07-08 21:44:25 +0000782 // Implementation Details
783private:
Chris Lattnerea862a32007-01-09 07:55:49 +0000784 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
785 void CreateModuleSlot(const GlobalValue *V);
Devang Patel983c6b12009-07-08 21:44:25 +0000786
787 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000788 void CreateMetadataSlot(const MDNode *N);
Devang Patel983c6b12009-07-08 21:44:25 +0000789
Chris Lattnerea862a32007-01-09 07:55:49 +0000790 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
791 void CreateFunctionSlot(const Value *V);
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000792
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000793 /// Insert the specified AttributeSet into the slot table.
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000794 void CreateAttributeSetSlot(AttributeSet AS);
Bill Wendling829b4782013-02-11 08:43:33 +0000795
Teresa Johnson8fc76662018-07-02 22:09:23 +0000796 inline void CreateModulePathSlot(StringRef Path);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000797 void CreateGUIDSlot(GlobalValue::GUID GUID);
Teresa Johnson7fb39df2018-09-25 20:14:40 +0000798 void CreateTypeIdSlot(StringRef Id);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000799
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000800 /// Add all of the module level global variables (and their initializers)
801 /// and function declarations, but not the contents of those functions.
802 void processModule();
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000803 void processIndex();
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000804
Devang Patel983c6b12009-07-08 21:44:25 +0000805 /// Add all of the functions arguments, basic blocks, and instructions.
Reid Spencer56010e42004-05-26 21:56:09 +0000806 void processFunction();
807
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000808 /// Add the metadata directly attached to a GlobalObject.
809 void processGlobalObjectMetadata(const GlobalObject &GO);
810
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000811 /// Add all of the metadata from a function.
812 void processFunctionMetadata(const Function &F);
813
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +0000814 /// Add all of the metadata from an instruction.
815 void processInstructionMetadata(const Instruction &I);
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000816};
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000817
818} // end namespace llvm
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000819
820ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
821 const Function *F)
822 : M(M), F(F), Machine(&Machine) {}
823
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +0000824ModuleSlotTracker::ModuleSlotTracker(const Module *M,
825 bool ShouldInitializeAllMetadata)
Duncan P. N. Exon Smithaf0fdc22016-04-20 19:05:59 +0000826 : ShouldCreateStorage(M),
827 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000828
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000829ModuleSlotTracker::~ModuleSlotTracker() = default;
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000830
Duncan P. N. Exon Smithaf0fdc22016-04-20 19:05:59 +0000831SlotTracker *ModuleSlotTracker::getMachine() {
832 if (!ShouldCreateStorage)
833 return Machine;
834
835 ShouldCreateStorage = false;
836 MachineStorage =
837 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
838 Machine = MachineStorage.get();
839 return Machine;
840}
841
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000842void ModuleSlotTracker::incorporateFunction(const Function &F) {
Duncan P. N. Exon Smithaf0fdc22016-04-20 19:05:59 +0000843 // Using getMachine() may lazily create the slot tracker.
844 if (!getMachine())
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +0000845 return;
846
847 // Nothing to do if this is the right function already.
848 if (this->F == &F)
849 return;
850 if (this->F)
851 Machine->purgeFunction();
852 Machine->incorporateFunction(&F);
853 this->F = &F;
854}
Reid Spencer16f2f7f2004-05-26 07:18:52 +0000855
Alex Lorenz991a6242015-07-27 22:31:04 +0000856int ModuleSlotTracker::getLocalSlot(const Value *V) {
857 assert(F && "No function incorporated");
858 return Machine->getLocalSlot(V);
859}
860
Chris Lattner3eee99c2008-08-19 04:36:02 +0000861static SlotTracker *createSlotTracker(const Value *V) {
862 if (const Argument *FA = dyn_cast<Argument>(V))
863 return new SlotTracker(FA->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000864
Chris Lattner3eee99c2008-08-19 04:36:02 +0000865 if (const Instruction *I = dyn_cast<Instruction>(V))
Andrew Trick2f0cbf62011-09-30 19:50:40 +0000866 if (I->getParent())
867 return new SlotTracker(I->getParent()->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000868
Chris Lattner3eee99c2008-08-19 04:36:02 +0000869 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
870 return new SlotTracker(BB->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000871
Chris Lattner3eee99c2008-08-19 04:36:02 +0000872 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
873 return new SlotTracker(GV->getParent());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000874
Chris Lattner3eee99c2008-08-19 04:36:02 +0000875 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000876 return new SlotTracker(GA->getParent());
877
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000878 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
879 return new SlotTracker(GIF->getParent());
880
Chris Lattner3eee99c2008-08-19 04:36:02 +0000881 if (const Function *Func = dyn_cast<Function>(V))
882 return new SlotTracker(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000883
Craig Topperc6207612014-04-09 06:08:46 +0000884 return nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +0000885}
886
887#if 0
David Greenec7f9b122010-01-05 01:29:26 +0000888#define ST_DEBUG(X) dbgs() << X
Chris Lattner3eee99c2008-08-19 04:36:02 +0000889#else
Chris Lattner604e3512008-08-19 04:47:09 +0000890#define ST_DEBUG(X)
Chris Lattner3eee99c2008-08-19 04:36:02 +0000891#endif
892
893// Module level constructor. Causes the contents of the Module (sans functions)
894// to be added to the slot table.
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000895SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000896 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
Chris Lattner3eee99c2008-08-19 04:36:02 +0000897
898// Function level constructor. Causes the contents of the Module and the one
899// function provided to be added to the slot table.
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000900SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000901 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000902 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
Chris Lattner3eee99c2008-08-19 04:36:02 +0000903
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000904SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
905 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
906
Teresa Johnsonfc801f52018-07-03 15:52:57 +0000907inline void SlotTracker::initializeIfNeeded() {
Chris Lattner3eee99c2008-08-19 04:36:02 +0000908 if (TheModule) {
909 processModule();
Craig Topperc6207612014-04-09 06:08:46 +0000910 TheModule = nullptr; ///< Prevent re-processing next time we're called.
Chris Lattner3eee99c2008-08-19 04:36:02 +0000911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
Chris Lattner3eee99c2008-08-19 04:36:02 +0000913 if (TheFunction && !FunctionProcessed)
914 processFunction();
915}
916
Teresa Johnsonfc801f52018-07-03 15:52:57 +0000917void SlotTracker::initializeIndexIfNeeded() {
Teresa Johnson08d5b4e2018-05-26 02:34:13 +0000918 if (!TheIndex)
919 return;
920 processIndex();
921 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
922}
923
Chris Lattner3eee99c2008-08-19 04:36:02 +0000924// Iterate through all the global variables, functions, and global
925// variable initializers and create slots for them.
926void SlotTracker::processModule() {
Chris Lattner604e3512008-08-19 04:47:09 +0000927 ST_DEBUG("begin processModule!\n");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000928
Chris Lattner3eee99c2008-08-19 04:36:02 +0000929 // Add all of the unnamed global variables to the value table.
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000930 for (const GlobalVariable &Var : TheModule->globals()) {
931 if (!Var.hasName())
932 CreateModuleSlot(&Var);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000933 processGlobalObjectMetadata(Var);
Javed Absarf3d79042017-05-11 12:28:08 +0000934 auto Attrs = Var.getAttributes();
935 if (Attrs.hasAttributes())
936 CreateAttributeSetSlot(Attrs);
Devang Patel983c6b12009-07-08 21:44:25 +0000937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
Rafael Espindola54fc2982015-06-17 17:53:31 +0000939 for (const GlobalAlias &A : TheModule->aliases()) {
940 if (!A.hasName())
941 CreateModuleSlot(&A);
942 }
943
Dmitry Polukhina1feff72016-04-07 12:32:19 +0000944 for (const GlobalIFunc &I : TheModule->ifuncs()) {
945 if (!I.hasName())
946 CreateModuleSlot(&I);
947 }
948
Devang Patel23e68302009-07-29 22:04:47 +0000949 // Add metadata used by named metadata.
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000950 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
951 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
952 CreateMetadataSlot(NMD.getOperand(i));
Devang Patel23e68302009-07-29 22:04:47 +0000953 }
954
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000955 for (const Function &F : *TheModule) {
956 if (!F.hasName())
Bill Wendling829b4782013-02-11 08:43:33 +0000957 // Add all the unnamed functions to the table.
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000958 CreateModuleSlot(&F);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000959
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000960 if (ShouldInitializeAllMetadata)
Rafael Espindola5d8a1552015-06-17 17:33:37 +0000961 processFunctionMetadata(F);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +0000962
Bill Wendling829b4782013-02-11 08:43:33 +0000963 // Add all the function attributes to the table.
Bill Wendling90bc19c2013-02-20 07:21:42 +0000964 // FIXME: Add attributes of other objects?
Reid Klecknerc2cb5602017-04-12 00:38:00 +0000965 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
966 if (FnAttrs.hasAttributes())
Bill Wendling829b4782013-02-11 08:43:33 +0000967 CreateAttributeSetSlot(FnAttrs);
968 }
969
Chris Lattner604e3512008-08-19 04:47:09 +0000970 ST_DEBUG("end processModule!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +0000971}
972
Chris Lattner3eee99c2008-08-19 04:36:02 +0000973// Process the arguments, basic blocks, and instructions of a function.
974void SlotTracker::processFunction() {
Chris Lattner604e3512008-08-19 04:47:09 +0000975 ST_DEBUG("begin processFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +0000976 fNext = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000977
Duncan P. N. Exon Smithadc54562015-09-11 01:34:59 +0000978 // Process function metadata if it wasn't hit at the module-level.
979 if (!ShouldInitializeAllMetadata)
980 processFunctionMetadata(*TheFunction);
981
Chris Lattner3eee99c2008-08-19 04:36:02 +0000982 // Add all the function arguments with no names.
983 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
984 AE = TheFunction->arg_end(); AI != AE; ++AI)
985 if (!AI->hasName())
Duncan P. N. Exon Smith52888a62015-10-08 23:49:46 +0000986 CreateFunctionSlot(&*AI);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000987
Chris Lattner604e3512008-08-19 04:47:09 +0000988 ST_DEBUG("Inserting Instructions:\n");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000989
Chris Lattner3eee99c2008-08-19 04:36:02 +0000990 // Add all of the basic blocks and instructions with no names.
Duncan P. N. Exon Smith27f33ee2015-03-14 19:44:01 +0000991 for (auto &BB : *TheFunction) {
992 if (!BB.hasName())
993 CreateFunctionSlot(&BB);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000994
Duncan P. N. Exon Smith27f33ee2015-03-14 19:44:01 +0000995 for (auto &I : BB) {
996 if (!I.getType()->isVoidTy() && !I.hasName())
997 CreateFunctionSlot(&I);
Andrew Trickec4b6e72011-09-30 19:48:58 +0000998
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +0000999 // We allow direct calls to any llvm.foo function here, because the
1000 // target may not be linked into the optimizer.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001001 if (auto CS = ImmutableCallSite(&I)) {
Bill Wendlinga0323742013-02-22 09:09:42 +00001002 // Add all the call attributes to the table.
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001003 AttributeSet Attrs = CS.getAttributes().getFnAttributes();
1004 if (Attrs.hasAttributes())
Bill Wendlinga0323742013-02-22 09:09:42 +00001005 CreateAttributeSetSlot(Attrs);
Chris Lattner58aff8f2010-05-10 20:53:17 +00001006 }
Devang Patel983c6b12009-07-08 21:44:25 +00001007 }
Chris Lattner3eee99c2008-08-19 04:36:02 +00001008 }
Devang Pateldec23fd2009-09-16 20:21:17 +00001009
Chris Lattner3eee99c2008-08-19 04:36:02 +00001010 FunctionProcessed = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001011
Chris Lattner604e3512008-08-19 04:47:09 +00001012 ST_DEBUG("end processFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001013}
1014
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001015// Iterate through all the GUID in the index and create slots for them.
1016void SlotTracker::processIndex() {
1017 ST_DEBUG("begin processIndex!\n");
1018 assert(TheIndex);
1019
1020 // The first block of slots are just the module ids, which start at 0 and are
Teresa Johnson8fc76662018-07-02 22:09:23 +00001021 // assigned consecutively. Since the StringMap iteration order isn't
1022 // guaranteed, use a std::map to order by module ID before assigning slots.
1023 std::map<uint64_t, StringRef> ModuleIdToPathMap;
1024 for (auto &ModPath : TheIndex->modulePaths())
1025 ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1026 for (auto &ModPair : ModuleIdToPathMap)
1027 CreateModulePathSlot(ModPair.second);
1028
1029 // Start numbering the GUIDs after the module ids.
1030 GUIDNext = ModulePathNext;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001031
1032 for (auto &GlobalList : *TheIndex)
1033 CreateGUIDSlot(GlobalList.first);
1034
Teresa Johnson7fb39df2018-09-25 20:14:40 +00001035 // Start numbering the TypeIds after the GUIDs.
1036 TypeIdNext = GUIDNext;
1037
1038 for (auto TidIter = TheIndex->typeIds().begin();
1039 TidIter != TheIndex->typeIds().end(); TidIter++)
1040 CreateTypeIdSlot(TidIter->second.first);
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001041
1042 ST_DEBUG("end processIndex!\n");
1043}
1044
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001045void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001046 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001047 GO.getAllMetadata(MDs);
Duncan P. N. Exon Smithadc54562015-09-11 01:34:59 +00001048 for (auto &MD : MDs)
1049 CreateMetadataSlot(MD.second);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001050}
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001051
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001052void SlotTracker::processFunctionMetadata(const Function &F) {
1053 processGlobalObjectMetadata(F);
Duncan P. N. Exon Smithadc54562015-09-11 01:34:59 +00001054 for (auto &BB : F) {
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00001055 for (auto &I : BB)
1056 processInstructionMetadata(I);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001057 }
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00001058}
1059
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +00001060void SlotTracker::processInstructionMetadata(const Instruction &I) {
1061 // Process metadata used directly by intrinsics.
1062 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1063 if (Function *F = CI->getCalledFunction())
Justin Lebar9cbc3012016-07-28 23:58:15 +00001064 if (F->isIntrinsic())
Duncan P. N. Exon Smith20b76ac2015-03-14 19:48:31 +00001065 for (auto &Op : I.operands())
1066 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1067 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1068 CreateMetadataSlot(N);
1069
1070 // Process metadata attached to this instruction.
1071 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1072 I.getAllMetadata(MDs);
1073 for (auto &MD : MDs)
1074 CreateMetadataSlot(MD.second);
1075}
1076
Chris Lattner3eee99c2008-08-19 04:36:02 +00001077/// Clean up after incorporating a function. This is the only way to get out of
1078/// the function incorporation state that affects get*Slot/Create*Slot. Function
1079/// incorporation state is indicated by TheFunction != 0.
1080void SlotTracker::purgeFunction() {
Chris Lattner604e3512008-08-19 04:47:09 +00001081 ST_DEBUG("begin purgeFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001082 fMap.clear(); // Simply discard the function level map
Craig Topperc6207612014-04-09 06:08:46 +00001083 TheFunction = nullptr;
Chris Lattner3eee99c2008-08-19 04:36:02 +00001084 FunctionProcessed = false;
Chris Lattner604e3512008-08-19 04:47:09 +00001085 ST_DEBUG("end purgeFunction!\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001086}
1087
1088/// getGlobalSlot - Get the slot number of a global value.
1089int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1090 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001091 initializeIfNeeded();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001092
Jay Foaddbb221d2011-07-11 07:28:49 +00001093 // Find the value in the module map
Chris Lattner3eee99c2008-08-19 04:36:02 +00001094 ValueMap::iterator MI = mMap.find(V);
Dan Gohman1dd27572008-10-01 19:58:59 +00001095 return MI == mMap.end() ? -1 : (int)MI->second;
Chris Lattner3eee99c2008-08-19 04:36:02 +00001096}
1097
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001098/// getMetadataSlot - Get the slot number of a MDNode.
1099int SlotTracker::getMetadataSlot(const MDNode *N) {
Devang Patel983c6b12009-07-08 21:44:25 +00001100 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001101 initializeIfNeeded();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001102
Jay Foaddbb221d2011-07-11 07:28:49 +00001103 // Find the MDNode in the module map
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001104 mdn_iterator MI = mdnMap.find(N);
Devang Patel983c6b12009-07-08 21:44:25 +00001105 return MI == mdnMap.end() ? -1 : (int)MI->second;
1106}
1107
Chris Lattner3eee99c2008-08-19 04:36:02 +00001108/// getLocalSlot - Get the slot number for a value that is local to a function.
1109int SlotTracker::getLocalSlot(const Value *V) {
1110 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001111
Chris Lattner3eee99c2008-08-19 04:36:02 +00001112 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001113 initializeIfNeeded();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001114
Chris Lattner3eee99c2008-08-19 04:36:02 +00001115 ValueMap::iterator FI = fMap.find(V);
Dan Gohman1dd27572008-10-01 19:58:59 +00001116 return FI == fMap.end() ? -1 : (int)FI->second;
Chris Lattner3eee99c2008-08-19 04:36:02 +00001117}
1118
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001119int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
Bill Wendling829b4782013-02-11 08:43:33 +00001120 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001121 initializeIfNeeded();
Bill Wendling829b4782013-02-11 08:43:33 +00001122
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001123 // Find the AttributeSet in the module map.
Bill Wendling829b4782013-02-11 08:43:33 +00001124 as_iterator AI = asMap.find(AS);
1125 return AI == asMap.end() ? -1 : (int)AI->second;
1126}
Chris Lattner3eee99c2008-08-19 04:36:02 +00001127
Teresa Johnson8fc76662018-07-02 22:09:23 +00001128int SlotTracker::getModulePathSlot(StringRef Path) {
1129 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001130 initializeIndexIfNeeded();
Teresa Johnson8fc76662018-07-02 22:09:23 +00001131
1132 // Find the Module path in the map
1133 auto I = ModulePathMap.find(Path);
1134 return I == ModulePathMap.end() ? -1 : (int)I->second;
1135}
1136
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001137int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1138 // Check for uninitialized state and do lazy initialization.
Teresa Johnsonfc801f52018-07-03 15:52:57 +00001139 initializeIndexIfNeeded();
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001140
1141 // Find the GUID in the map
1142 guid_iterator I = GUIDMap.find(GUID);
1143 return I == GUIDMap.end() ? -1 : (int)I->second;
1144}
1145
Teresa Johnson7fb39df2018-09-25 20:14:40 +00001146int SlotTracker::getTypeIdSlot(StringRef Id) {
1147 // Check for uninitialized state and do lazy initialization.
1148 initializeIndexIfNeeded();
1149
1150 // Find the TypeId string in the map
1151 auto I = TypeIdMap.find(Id);
1152 return I == TypeIdMap.end() ? -1 : (int)I->second;
1153}
1154
Chris Lattner3eee99c2008-08-19 04:36:02 +00001155/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1156void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1157 assert(V && "Can't insert a null Value into SlotTracker!");
Chris Lattner031560c2009-12-29 07:25:48 +00001158 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001159 assert(!V->hasName() && "Doesn't need a slot!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001160
Chris Lattner3eee99c2008-08-19 04:36:02 +00001161 unsigned DestSlot = mNext++;
1162 mMap[V] = DestSlot;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001163
Chris Lattner604e3512008-08-19 04:47:09 +00001164 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
Chris Lattner3eee99c2008-08-19 04:36:02 +00001165 DestSlot << " [");
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001166 // G = Global, F = Function, A = Alias, I = IFunc, o = other
Chris Lattner604e3512008-08-19 04:47:09 +00001167 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
Chris Lattner3eee99c2008-08-19 04:36:02 +00001168 (isa<Function>(V) ? 'F' :
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001169 (isa<GlobalAlias>(V) ? 'A' :
1170 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
Chris Lattner3eee99c2008-08-19 04:36:02 +00001171}
1172
Chris Lattner3eee99c2008-08-19 04:36:02 +00001173/// CreateSlot - Create a new slot for the specified value if it has no name.
1174void SlotTracker::CreateFunctionSlot(const Value *V) {
Chris Lattner031560c2009-12-29 07:25:48 +00001175 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001176
Chris Lattner3eee99c2008-08-19 04:36:02 +00001177 unsigned DestSlot = fNext++;
1178 fMap[V] = DestSlot;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001179
Chris Lattner3eee99c2008-08-19 04:36:02 +00001180 // G = Global, F = Function, o = other
Chris Lattner604e3512008-08-19 04:47:09 +00001181 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
Chris Lattner3eee99c2008-08-19 04:36:02 +00001182 DestSlot << " [o]\n");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001183}
Chris Lattner3eee99c2008-08-19 04:36:02 +00001184
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001185/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1186void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1187 assert(N && "Can't insert a null Value into SlotTracker!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001188
Reid Kleckner6d353342017-08-23 20:31:27 +00001189 // Don't make slots for DIExpressions. We just print them inline everywhere.
1190 if (isa<DIExpression>(N))
1191 return;
1192
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001193 unsigned DestSlot = mdnNext;
1194 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1195 return;
1196 ++mdnNext;
Devang Patel983c6b12009-07-08 21:44:25 +00001197
Chris Lattner0d50bdd2009-12-31 02:27:30 +00001198 // Recursively add any MDNodes referenced by operands.
1199 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1200 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1201 CreateMetadataSlot(Op);
Devang Patel983c6b12009-07-08 21:44:25 +00001202}
Chris Lattner3eee99c2008-08-19 04:36:02 +00001203
Reid Klecknerc2cb5602017-04-12 00:38:00 +00001204void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1205 assert(AS.hasAttributes() && "Doesn't need a slot!");
Bill Wendling829b4782013-02-11 08:43:33 +00001206
1207 as_iterator I = asMap.find(AS);
1208 if (I != asMap.end())
1209 return;
1210
1211 unsigned DestSlot = asNext++;
1212 asMap[AS] = DestSlot;
1213}
1214
Teresa Johnson8fc76662018-07-02 22:09:23 +00001215/// Create a new slot for the specified Module
1216void SlotTracker::CreateModulePathSlot(StringRef Path) {
1217 ModulePathMap[Path] = ModulePathNext++;
1218}
1219
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00001220/// Create a new slot for the specified GUID
1221void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1222 GUIDMap[GUID] = GUIDNext++;
1223}
1224
Teresa Johnson7fb39df2018-09-25 20:14:40 +00001225/// Create a new slot for the specified Id
1226void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1227 TypeIdMap[Id] = TypeIdNext++;
1228}
1229
Chris Lattner3eee99c2008-08-19 04:36:02 +00001230//===----------------------------------------------------------------------===//
1231// AsmWriter Implementation
1232//===----------------------------------------------------------------------===//
Chris Lattner7f8845a2002-07-23 18:07:49 +00001233
Dan Gohman12dad632009-08-12 20:56:03 +00001234static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
Dan Gohman8061d9e2009-08-13 15:27:57 +00001235 TypePrinting *TypePrinter,
Dan Gohmana2489d12010-07-20 23:55:01 +00001236 SlotTracker *Machine,
1237 const Module *Context);
Reid Spencer58d30f22004-07-04 11:50:43 +00001238
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001239static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1240 TypePrinting *TypePrinter,
1241 SlotTracker *Machine, const Module *Context,
1242 bool FromValue = false);
1243
Eli Friedmanc9a551e2011-07-28 21:48:00 +00001244static void writeAtomicRMWOperation(raw_ostream &Out,
1245 AtomicRMWInst::BinOp Op) {
1246 switch (Op) {
1247 default: Out << " <unknown operation " << Op << ">"; break;
1248 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1249 case AtomicRMWInst::Add: Out << " add"; break;
1250 case AtomicRMWInst::Sub: Out << " sub"; break;
1251 case AtomicRMWInst::And: Out << " and"; break;
1252 case AtomicRMWInst::Nand: Out << " nand"; break;
1253 case AtomicRMWInst::Or: Out << " or"; break;
1254 case AtomicRMWInst::Xor: Out << " xor"; break;
1255 case AtomicRMWInst::Max: Out << " max"; break;
1256 case AtomicRMWInst::Min: Out << " min"; break;
1257 case AtomicRMWInst::UMax: Out << " umax"; break;
1258 case AtomicRMWInst::UMin: Out << " umin"; break;
1259 }
1260}
Devang Patel983c6b12009-07-08 21:44:25 +00001261
Dan Gohman12dad632009-08-12 20:56:03 +00001262static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
Michael Ilseman92053172012-11-27 00:42:44 +00001263 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
Sanjay Patel629c4112017-11-06 16:27:15 +00001264 // 'Fast' is an abbreviation for all fast-math-flags.
1265 if (FPO->isFast())
Michael Ilseman92053172012-11-27 00:42:44 +00001266 Out << " fast";
1267 else {
Sanjay Patel629c4112017-11-06 16:27:15 +00001268 if (FPO->hasAllowReassoc())
1269 Out << " reassoc";
Michael Ilseman92053172012-11-27 00:42:44 +00001270 if (FPO->hasNoNaNs())
1271 Out << " nnan";
1272 if (FPO->hasNoInfs())
1273 Out << " ninf";
1274 if (FPO->hasNoSignedZeros())
1275 Out << " nsz";
1276 if (FPO->hasAllowReciprocal())
1277 Out << " arcp";
Adam Nemetcd847a82017-03-28 20:11:52 +00001278 if (FPO->hasAllowContract())
1279 Out << " contract";
Sanjay Patel629c4112017-11-06 16:27:15 +00001280 if (FPO->hasApproxFunc())
1281 Out << " afn";
Michael Ilseman92053172012-11-27 00:42:44 +00001282 }
1283 }
1284
Dan Gohman0ebd6962009-07-20 21:19:07 +00001285 if (const OverflowingBinaryOperator *OBO =
1286 dyn_cast<OverflowingBinaryOperator>(U)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001287 if (OBO->hasNoUnsignedWrap())
Dan Gohman9c7f8082009-07-27 16:11:46 +00001288 Out << " nuw";
Dan Gohman16f54152009-08-20 17:11:38 +00001289 if (OBO->hasNoSignedWrap())
Dan Gohman9c7f8082009-07-27 16:11:46 +00001290 Out << " nsw";
Chris Lattner35315d02011-02-06 21:44:57 +00001291 } else if (const PossiblyExactOperator *Div =
1292 dyn_cast<PossiblyExactOperator>(U)) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001293 if (Div->isExact())
Dan Gohman9c7f8082009-07-27 16:11:46 +00001294 Out << " exact";
Dan Gohman1639c392009-07-27 21:53:46 +00001295 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1296 if (GEP->isInBounds())
1297 Out << " inbounds";
Dan Gohman0ebd6962009-07-20 21:19:07 +00001298 }
1299}
1300
Dan Gohmanefb8dbb2010-07-14 20:57:55 +00001301static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1302 TypePrinting &TypePrinter,
Dan Gohmana2489d12010-07-20 23:55:01 +00001303 SlotTracker *Machine,
1304 const Module *Context) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001305 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001306 if (CI->getType()->isIntegerTy(1)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00001307 Out << (CI->getZExtValue() ? "true" : "false");
Chris Lattner17f71652008-08-17 07:19:36 +00001308 return;
1309 }
1310 Out << CI->getValue();
1311 return;
1312 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001313
Chris Lattner17f71652008-08-17 07:19:36 +00001314 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001315 const APFloat &APF = CFP->getValueAPF();
1316 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1317 &APF.getSemantics() == &APFloat::IEEEdouble()) {
Dale Johannesen028084e2007-09-12 03:30:33 +00001318 // We would like to output the FP constant value in exponential notation,
1319 // but we cannot do this if doing so will lose precision. Check here to
1320 // make sure that we only output it in exponential format if we can parse
1321 // the value back and get the same value.
1322 //
Dale Johannesen1f864982009-01-21 20:32:55 +00001323 bool ignored;
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001324 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1325 bool isInf = APF.isInfinity();
1326 bool isNaN = APF.isNaN();
Justin Bognerb609b6b2015-12-04 01:14:24 +00001327 if (!isInf && !isNaN) {
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001328 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
Dan Gohman518cda42011-12-17 00:04:22 +00001329 SmallString<128> StrVal;
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001330 APF.toString(StrVal, 6, 0, false);
Dan Gohman518cda42011-12-17 00:04:22 +00001331 // Check to make sure that the stringized number is not some string like
1332 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1333 // that the string matches the "[-+]?[0-9]" regex.
1334 //
Serguei Katkovc9a752c2017-04-21 06:14:38 +00001335 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1336 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1337 (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1338 "[-+]?[0-9] regex does not match!");
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001339 // Reparse stringized version!
1340 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1341 Out << StrVal;
1342 return;
Dale Johannesen028084e2007-09-12 03:30:33 +00001343 }
Chris Lattner1e194682002-04-18 18:53:13 +00001344 }
Dale Johannesen028084e2007-09-12 03:30:33 +00001345 // Otherwise we could not reparse it to exactly the same value, so we must
Dale Johannesen1f864982009-01-21 20:32:55 +00001346 // output the string in hexadecimal format! Note that loading and storing
1347 // floating point types changes the bits of NaNs on some hosts, notably
1348 // x86, so we must not use these types.
Benjamin Kramer86c77412014-03-15 18:47:07 +00001349 static_assert(sizeof(double) == sizeof(uint64_t),
1350 "assuming that double is 64 bits!");
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001351 APFloat apf = APF;
Justin Bognerb609b6b2015-12-04 01:14:24 +00001352 // Floats are represented in ASCII IR as double, convert.
Dale Johannesen1f864982009-01-21 20:32:55 +00001353 if (!isDouble)
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001354 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
Dale Johannesen1f864982009-01-21 20:32:55 +00001355 &ignored);
Justin Bogner93289572015-12-04 02:14:34 +00001356 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001357 return;
1358 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001359
Tobias Grosser6b31d172012-05-24 15:59:06 +00001360 // Either half, or some form of long double.
1361 // These appear as a magic letter identifying the type, then a
1362 // fixed number of hex digits.
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001363 Out << "0x";
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001364 APInt API = APF.bitcastToAPInt();
1365 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001366 Out << 'K';
Justin Bogner93289572015-12-04 02:14:34 +00001367 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1368 /*Upper=*/true);
1369 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1370 /*Upper=*/true);
Dale Johannesen93eefa02009-03-23 21:16:53 +00001371 return;
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001372 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001373 Out << 'L';
Justin Bogner93289572015-12-04 02:14:34 +00001374 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1375 /*Upper=*/true);
1376 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1377 /*Upper=*/true);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001378 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001379 Out << 'M';
Justin Bogner93289572015-12-04 02:14:34 +00001380 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1381 /*Upper=*/true);
1382 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1383 /*Upper=*/true);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00001384 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
Tobias Grosser6b31d172012-05-24 15:59:06 +00001385 Out << 'H';
Justin Bogner93289572015-12-04 02:14:34 +00001386 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1387 /*Upper=*/true);
Tobias Grosser6b31d172012-05-24 15:59:06 +00001388 } else
Torok Edwinfbcc6632009-07-14 16:55:14 +00001389 llvm_unreachable("Unsupported floating point type");
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001390 return;
1391 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001392
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001393 if (isa<ConstantAggregateZero>(CV)) {
Chris Lattner76b2ff42004-02-15 05:55:15 +00001394 Out << "zeroinitializer";
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001395 return;
1396 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00001397
Chris Lattner214cc702009-10-28 03:38:12 +00001398 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1399 Out << "blockaddress(";
Dan Gohmana2489d12010-07-20 23:55:01 +00001400 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1401 Context);
Chris Lattner214cc702009-10-28 03:38:12 +00001402 Out << ", ";
Dan Gohmana2489d12010-07-20 23:55:01 +00001403 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1404 Context);
Chris Lattner214cc702009-10-28 03:38:12 +00001405 Out << ")";
1406 return;
1407 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001408
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001409 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001410 Type *ETy = CA->getType()->getElementType();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001411 Out << '[';
1412 TypePrinter.print(ETy, Out);
1413 Out << ' ';
1414 WriteAsOperandInternal(Out, CA->getOperand(0),
1415 &TypePrinter, Machine,
1416 Context);
1417 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1418 Out << ", ";
Chris Lattner9c181f62012-01-31 03:15:40 +00001419 TypePrinter.print(ETy, Out);
1420 Out << ' ';
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001421 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
Chris Lattner9c181f62012-01-31 03:15:40 +00001422 Context);
Chris Lattnerd84bb632002-04-16 21:36:08 +00001423 }
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001424 Out << ']';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001425 return;
1426 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001427
Chris Lattnerfa775002012-01-26 02:32:04 +00001428 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1429 // As a special case, print the array as a string if it is an array of
1430 // i8 with ConstantInt values.
1431 if (CA->isString()) {
1432 Out << "c\"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00001433 printEscapedString(CA->getAsString(), Out);
Chris Lattnerfa775002012-01-26 02:32:04 +00001434 Out << '"';
1435 return;
1436 }
1437
1438 Type *ETy = CA->getType()->getElementType();
1439 Out << '[';
Chris Lattner9c181f62012-01-31 03:15:40 +00001440 TypePrinter.print(ETy, Out);
1441 Out << ' ';
1442 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1443 &TypePrinter, Machine,
1444 Context);
1445 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1446 Out << ", ";
Chris Lattnerfa775002012-01-26 02:32:04 +00001447 TypePrinter.print(ETy, Out);
1448 Out << ' ';
Chris Lattner9c181f62012-01-31 03:15:40 +00001449 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1450 Machine, Context);
Chris Lattnerfa775002012-01-26 02:32:04 +00001451 }
Chris Lattner9c181f62012-01-31 03:15:40 +00001452 Out << ']';
Chris Lattnerfa775002012-01-26 02:32:04 +00001453 return;
1454 }
1455
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001456 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
Andrew Lenharth0d124b82007-01-08 18:21:30 +00001457 if (CS->getType()->isPacked())
1458 Out << '<';
Misha Brukman21bbdb92004-06-04 21:11:51 +00001459 Out << '{';
Jim Laskey3bb78742006-02-25 12:27:03 +00001460 unsigned N = CS->getNumOperands();
1461 if (N) {
Chris Lattner604e3512008-08-19 04:47:09 +00001462 Out << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00001463 TypePrinter.print(CS->getOperand(0)->getType(), Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001464 Out << ' ';
Chris Lattnerd84bb632002-04-16 21:36:08 +00001465
Dan Gohmana2489d12010-07-20 23:55:01 +00001466 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1467 Context);
Chris Lattnerd84bb632002-04-16 21:36:08 +00001468
Jim Laskey3bb78742006-02-25 12:27:03 +00001469 for (unsigned i = 1; i < N; i++) {
Chris Lattnerd84bb632002-04-16 21:36:08 +00001470 Out << ", ";
Chris Lattnere101c442009-02-28 21:26:53 +00001471 TypePrinter.print(CS->getOperand(i)->getType(), Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001472 Out << ' ';
Chris Lattnerd84bb632002-04-16 21:36:08 +00001473
Dan Gohmana2489d12010-07-20 23:55:01 +00001474 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1475 Context);
Chris Lattnerd84bb632002-04-16 21:36:08 +00001476 }
Dan Gohman81313fd2008-09-14 17:21:12 +00001477 Out << ' ';
Chris Lattnerd84bb632002-04-16 21:36:08 +00001478 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001479
Dan Gohman81313fd2008-09-14 17:21:12 +00001480 Out << '}';
Andrew Lenharth0d124b82007-01-08 18:21:30 +00001481 if (CS->getType()->isPacked())
1482 Out << '>';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001483 return;
1484 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001485
Chris Lattnerfa775002012-01-26 02:32:04 +00001486 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1487 Type *ETy = CV->getType()->getVectorElementType();
Dan Gohman1262a252009-02-11 00:25:25 +00001488 Out << '<';
Chris Lattnere101c442009-02-28 21:26:53 +00001489 TypePrinter.print(ETy, Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001490 Out << ' ';
Chris Lattnerfa775002012-01-26 02:32:04 +00001491 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1492 Machine, Context);
1493 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
Chris Lattner585297e82008-08-19 05:26:17 +00001494 Out << ", ";
Chris Lattnere101c442009-02-28 21:26:53 +00001495 TypePrinter.print(ETy, Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001496 Out << ' ';
Chris Lattnerfa775002012-01-26 02:32:04 +00001497 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1498 Machine, Context);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001499 }
Dan Gohman1262a252009-02-11 00:25:25 +00001500 Out << '>';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001501 return;
1502 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001503
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001504 if (isa<ConstantPointerNull>(CV)) {
Chris Lattnerd84bb632002-04-16 21:36:08 +00001505 Out << "null";
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001506 return;
1507 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001508
David Majnemerf0f224d2015-11-11 21:57:16 +00001509 if (isa<ConstantTokenNone>(CV)) {
1510 Out << "none";
1511 return;
1512 }
1513
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001514 if (isa<UndefValue>(CV)) {
Chris Lattner5e0b9f22004-10-16 18:08:06 +00001515 Out << "undef";
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001516 return;
1517 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001518
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001519 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Reid Spencer812a1be2006-12-04 05:19:18 +00001520 Out << CE->getOpcodeName();
Dan Gohman9c7f8082009-07-27 16:11:46 +00001521 WriteOptimizationInfo(Out, CE);
Reid Spencer812a1be2006-12-04 05:19:18 +00001522 if (CE->isCompare())
Tim Northoverde3aea0412016-08-17 20:25:25 +00001523 Out << ' ' << CmpInst::getPredicateName(
1524 static_cast<CmpInst::Predicate>(CE->getPredicate()));
Reid Spencer812a1be2006-12-04 05:19:18 +00001525 Out << " (";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001526
Peter Collingbourned93620b2016-11-10 22:34:55 +00001527 Optional<unsigned> InRangeOp;
David Blaikief72d05b2015-03-13 18:20:45 +00001528 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
David Blaikied06654f2015-07-29 20:26:23 +00001529 TypePrinter.print(GEP->getSourceElementType(), Out);
David Blaikief72d05b2015-03-13 18:20:45 +00001530 Out << ", ";
Peter Collingbourned93620b2016-11-10 22:34:55 +00001531 InRangeOp = GEP->getInRangeIndex();
1532 if (InRangeOp)
1533 ++*InRangeOp;
David Blaikief72d05b2015-03-13 18:20:45 +00001534 }
1535
Vikram S. Adveb952b542002-07-14 23:14:45 +00001536 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
Zachary Turner804d5022016-11-11 23:58:11 +00001537 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
Peter Collingbourned93620b2016-11-10 22:34:55 +00001538 Out << "inrange ";
Chris Lattnere101c442009-02-28 21:26:53 +00001539 TypePrinter.print((*OI)->getType(), Out);
Dan Gohman81313fd2008-09-14 17:21:12 +00001540 Out << ' ';
Dan Gohmana2489d12010-07-20 23:55:01 +00001541 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
Vikram S. Adveb952b542002-07-14 23:14:45 +00001542 if (OI+1 != CE->op_end())
Chris Lattner3cd8c562002-07-30 18:54:25 +00001543 Out << ", ";
Vikram S. Adveb952b542002-07-14 23:14:45 +00001544 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001545
Dan Gohmana76f0f72008-05-31 19:12:39 +00001546 if (CE->hasIndices()) {
Jay Foad0091fe82011-04-13 15:22:40 +00001547 ArrayRef<unsigned> Indices = CE->getIndices();
Dan Gohmana76f0f72008-05-31 19:12:39 +00001548 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1549 Out << ", " << Indices[i];
1550 }
1551
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001552 if (CE->isCast()) {
Chris Lattner83b396b2002-08-15 19:37:43 +00001553 Out << " to ";
Chris Lattnere101c442009-02-28 21:26:53 +00001554 TypePrinter.print(CE->getType(), Out);
Chris Lattner83b396b2002-08-15 19:37:43 +00001555 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001556
Misha Brukman21bbdb92004-06-04 21:11:51 +00001557 Out << ')';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001558 return;
Chris Lattnerd84bb632002-04-16 21:36:08 +00001559 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001560
Chris Lattner3a36d2c2008-08-19 05:06:27 +00001561 Out << "<placeholder or erroneous Constant>";
Chris Lattnerd84bb632002-04-16 21:36:08 +00001562}
1563
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00001564static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1565 TypePrinting *TypePrinter, SlotTracker *Machine,
1566 const Module *Context) {
Chris Lattnercdec5812009-12-31 02:31:59 +00001567 Out << "!{";
1568 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001569 const Metadata *MD = Node->getOperand(mi);
1570 if (!MD)
Chris Lattnercdec5812009-12-31 02:31:59 +00001571 Out << "null";
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001572 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1573 Value *V = MDV->getValue();
Chris Lattnercdec5812009-12-31 02:31:59 +00001574 TypePrinter->print(V->getType(), Out);
1575 Out << ' ';
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001576 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1577 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001578 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
Chris Lattnercdec5812009-12-31 02:31:59 +00001579 }
1580 if (mi + 1 != me)
1581 Out << ", ";
1582 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00001583
Chris Lattnercdec5812009-12-31 02:31:59 +00001584 Out << "}";
1585}
1586
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001587namespace {
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001588
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001589struct FieldSeparator {
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001590 bool Skip = true;
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00001591 const char *Sep;
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001592
1593 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001594};
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001595
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001596raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1597 if (FS.Skip) {
1598 FS.Skip = false;
1599 return OS;
1600 }
Duncan P. N. Exon Smith70ab3d22015-02-21 01:02:18 +00001601 return OS << FS.Sep;
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001602}
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001603
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001604struct MDFieldPrinter {
1605 raw_ostream &Out;
1606 FieldSeparator FS;
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001607 TypePrinting *TypePrinter = nullptr;
1608 SlotTracker *Machine = nullptr;
1609 const Module *Context = nullptr;
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001610
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001611 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001612 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1613 SlotTracker *Machine, const Module *Context)
1614 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1615 }
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001616
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001617 void printTag(const DINode *N);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001618 void printMacinfoType(const DIMacroNode *N);
Scott Linder71603842018-02-12 19:45:54 +00001619 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001620 void printString(StringRef Name, StringRef Value,
1621 bool ShouldSkipEmpty = true);
1622 void printMetadata(StringRef Name, const Metadata *MD,
1623 bool ShouldSkipNull = true);
1624 template <class IntTy>
1625 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
David Blaikiea01f2952016-08-24 18:29:49 +00001626 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001627 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001628 template <class IntTy, class Stringifier>
1629 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1630 bool ShouldSkipZero = true);
Adrian Prantlb939a252016-03-31 23:56:58 +00001631 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
David Blaikie66cf14d2018-08-16 21:29:55 +00001632 void printNameTableKind(StringRef Name,
1633 DICompileUnit::DebugNameTableKind NTK);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001634};
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001635
1636} // end anonymous namespace
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001637
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001638void MDFieldPrinter::printTag(const DINode *N) {
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001639 Out << FS << "tag: ";
Mehdi Amini149f6ea2016-10-05 05:59:29 +00001640 auto Tag = dwarf::TagString(N->getTag());
1641 if (!Tag.empty())
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001642 Out << Tag;
1643 else
1644 Out << N->getTag();
1645}
1646
Amjad Abouda9bcf162015-12-10 12:56:35 +00001647void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1648 Out << FS << "type: ";
Mehdi Amini149f6ea2016-10-05 05:59:29 +00001649 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1650 if (!Type.empty())
Amjad Abouda9bcf162015-12-10 12:56:35 +00001651 Out << Type;
1652 else
1653 Out << N->getMacinfoType();
1654}
1655
Scott Linder71603842018-02-12 19:45:54 +00001656void MDFieldPrinter::printChecksum(
1657 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1658 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1659 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001660}
1661
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001662void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1663 bool ShouldSkipEmpty) {
1664 if (ShouldSkipEmpty && Value.empty())
1665 return;
1666
1667 Out << FS << Name << ": \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00001668 printEscapedString(Value, Out);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001669 Out << "\"";
1670}
1671
Duncan P. N. Exon Smith61a09332015-02-06 22:27:22 +00001672static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1673 TypePrinting *TypePrinter,
1674 SlotTracker *Machine,
1675 const Module *Context) {
1676 if (!MD) {
1677 Out << "null";
1678 return;
1679 }
1680 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1681}
1682
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001683void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1684 bool ShouldSkipNull) {
1685 if (ShouldSkipNull && !MD)
Duncan P. N. Exon Smith79cf9702015-02-28 22:16:56 +00001686 return;
1687
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001688 Out << FS << Name << ": ";
1689 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1690}
1691
1692template <class IntTy>
1693void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1694 if (ShouldSkipZero && !Int)
1695 return;
1696
1697 Out << FS << Name << ": " << Int;
1698}
1699
David Blaikiea01f2952016-08-24 18:29:49 +00001700void MDFieldPrinter::printBool(StringRef Name, bool Value,
1701 Optional<bool> Default) {
1702 if (Default && Value == *Default)
1703 return;
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001704 Out << FS << Name << ": " << (Value ? "true" : "false");
1705}
1706
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001707void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001708 if (!Flags)
1709 return;
1710
1711 Out << FS << Name << ": ";
1712
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001713 SmallVector<DINode::DIFlags, 8> SplitFlags;
1714 auto Extra = DINode::splitFlags(Flags, SplitFlags);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001715
1716 FieldSeparator FlagsFS(" | ");
Leny Kholodov5fcc4182016-09-06 10:46:28 +00001717 for (auto F : SplitFlags) {
Mehdi Aminif42ec792016-10-01 05:57:50 +00001718 auto StringF = DINode::getFlagString(F);
1719 assert(!StringF.empty() && "Expected valid flag");
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001720 Out << FlagsFS << StringF;
1721 }
1722 if (Extra || SplitFlags.empty())
1723 Out << FlagsFS << Extra;
1724}
1725
Adrian Prantlb939a252016-03-31 23:56:58 +00001726void MDFieldPrinter::printEmissionKind(StringRef Name,
1727 DICompileUnit::DebugEmissionKind EK) {
Fangrui Song3c1b5db2018-07-06 19:26:00 +00001728 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
Adrian Prantlb939a252016-03-31 23:56:58 +00001729}
1730
David Blaikie66cf14d2018-08-16 21:29:55 +00001731void MDFieldPrinter::printNameTableKind(StringRef Name,
1732 DICompileUnit::DebugNameTableKind NTK) {
1733 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1734 return;
1735 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1736}
1737
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001738template <class IntTy, class Stringifier>
1739void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1740 Stringifier toString, bool ShouldSkipZero) {
1741 if (!Value)
1742 return;
1743
1744 Out << FS << Name << ": ";
Mehdi Amini149f6ea2016-10-05 05:59:29 +00001745 auto S = toString(Value);
1746 if (!S.empty())
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001747 Out << S;
1748 else
1749 Out << Value;
Duncan P. N. Exon Smith79cf9702015-02-28 22:16:56 +00001750}
1751
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001752static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1753 TypePrinting *TypePrinter, SlotTracker *Machine,
1754 const Module *Context) {
1755 Out << "!GenericDINode(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001756 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1757 Printer.printTag(N);
1758 Printer.printString("header", N->getHeader());
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001759 if (N->getNumDwarfOperands()) {
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001760 Out << Printer.FS << "operands: {";
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001761 FieldSeparator IFS;
1762 for (auto &I : N->dwarf_operands()) {
1763 Out << IFS;
Duncan P. N. Exon Smith61a09332015-02-06 22:27:22 +00001764 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001765 }
1766 Out << "}";
1767 }
1768 Out << ")";
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +00001769}
1770
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001771static void writeDILocation(raw_ostream &Out, const DILocation *DL,
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001772 TypePrinting *TypePrinter, SlotTracker *Machine,
1773 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001774 Out << "!DILocation(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001775 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith503cf3b2015-01-14 22:14:26 +00001776 // Always output the line, since 0 is a relevant and important value for it.
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001777 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1778 Printer.printInt("column", DL->getColumn());
1779 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1780 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
Calixte Denizeteb7f6022018-09-20 08:53:06 +00001781 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1782 /* Default */ false);
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +00001783 Out << ")";
1784}
1785
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001786static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
Sander de Smalenfdf40912018-01-24 09:56:07 +00001787 TypePrinting *TypePrinter, SlotTracker *Machine,
1788 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001789 Out << "!DISubrange(";
Sander de Smalenfdf40912018-01-24 09:56:07 +00001790 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1791 if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1792 Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1793 else
1794 Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(),
1795 /*ShouldSkipNull */ false);
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001796 Printer.printInt("lowerBound", N->getLowerBound());
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001797 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001798}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001799
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001800static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001801 TypePrinting *, SlotTracker *, const Module *) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001802 Out << "!DIEnumerator(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001803 MDFieldPrinter Printer(Out);
1804 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
Momchil Velikov08dc66e2018-02-12 16:10:09 +00001805 if (N->isUnsigned()) {
1806 auto Value = static_cast<uint64_t>(N->getValue());
1807 Printer.printInt("value", Value, /* ShouldSkipZero */ false);
1808 Printer.printBool("isUnsigned", true);
1809 } else {
1810 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1811 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001812 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001813}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001814
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001815static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001816 TypePrinting *, SlotTracker *, const Module *) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001817 Out << "!DIBasicType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001818 MDFieldPrinter Printer(Out);
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00001819 if (N->getTag() != dwarf::DW_TAG_base_type)
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001820 Printer.printTag(N);
1821 Printer.printString("name", N->getName());
1822 Printer.printInt("size", N->getSizeInBits());
1823 Printer.printInt("align", N->getAlignInBits());
1824 Printer.printDwarfEnum("encoding", N->getEncoding(),
1825 dwarf::AttributeEncodingString);
Adrian Prantl55f42622018-08-14 19:35:34 +00001826 Printer.printDIFlags("flags", N->getFlags());
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001827 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001828}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001829
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001830static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001831 TypePrinting *TypePrinter, SlotTracker *Machine,
1832 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001833 Out << "!DIDerivedType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001834 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1835 Printer.printTag(N);
1836 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001837 Printer.printMetadata("scope", N->getRawScope());
1838 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001839 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001840 Printer.printMetadata("baseType", N->getRawBaseType(),
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001841 /* ShouldSkipNull */ false);
1842 Printer.printInt("size", N->getSizeInBits());
1843 Printer.printInt("align", N->getAlignInBits());
1844 Printer.printInt("offset", N->getOffsetInBits());
1845 Printer.printDIFlags("flags", N->getFlags());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001846 Printer.printMetadata("extraData", N->getRawExtraData());
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001847 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1848 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1849 /* ShouldSkipZero */ false);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001850 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001851}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001852
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001853static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001854 TypePrinting *TypePrinter,
1855 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001856 Out << "!DICompositeType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001857 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1858 Printer.printTag(N);
1859 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001860 Printer.printMetadata("scope", N->getRawScope());
1861 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001862 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001863 Printer.printMetadata("baseType", N->getRawBaseType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001864 Printer.printInt("size", N->getSizeInBits());
1865 Printer.printInt("align", N->getAlignInBits());
1866 Printer.printInt("offset", N->getOffsetInBits());
1867 Printer.printDIFlags("flags", N->getFlags());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001868 Printer.printMetadata("elements", N->getRawElements());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001869 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1870 dwarf::LanguageString);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001871 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1872 Printer.printMetadata("templateParams", N->getRawTemplateParams());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001873 Printer.printString("identifier", N->getIdentifier());
Adrian Prantl8c599212018-02-06 23:45:59 +00001874 Printer.printMetadata("discriminator", N->getRawDiscriminator());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001875 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001876}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001877
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001878static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001879 TypePrinting *TypePrinter,
1880 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001881 Out << "!DISubroutineType(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001882 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1883 Printer.printDIFlags("flags", N->getFlags());
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001884 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001885 Printer.printMetadata("types", N->getRawTypeArray(),
1886 /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001887 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001888}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001889
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001890static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001891 SlotTracker *, const Module *) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001892 Out << "!DIFile(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001893 MDFieldPrinter Printer(Out);
1894 Printer.printString("filename", N->getFilename(),
1895 /* ShouldSkipEmpty */ false);
1896 Printer.printString("directory", N->getDirectory(),
1897 /* ShouldSkipEmpty */ false);
Scott Linder71603842018-02-12 19:45:54 +00001898 // Print all values for checksum together, or not at all.
1899 if (N->getChecksum())
1900 Printer.printChecksum(*N->getChecksum());
Scott Linder16c7bda2018-02-23 23:01:06 +00001901 Printer.printString("source", N->getSource().getValueOr(StringRef()),
1902 /* ShouldSkipEmpty */ true);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001903 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001904}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001905
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001906static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001907 TypePrinting *TypePrinter, SlotTracker *Machine,
1908 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001909 Out << "!DICompileUnit(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001910 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1911 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1912 dwarf::LanguageString, /* ShouldSkipZero */ false);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001913 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001914 Printer.printString("producer", N->getProducer());
1915 Printer.printBool("isOptimized", N->isOptimized());
1916 Printer.printString("flags", N->getFlags());
1917 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1918 /* ShouldSkipZero */ false);
1919 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
Adrian Prantlb939a252016-03-31 23:56:58 +00001920 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001921 Printer.printMetadata("enums", N->getRawEnumTypes());
1922 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001923 Printer.printMetadata("globals", N->getRawGlobalVariables());
1924 Printer.printMetadata("imports", N->getRawImportedEntities());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001925 Printer.printMetadata("macros", N->getRawMacros());
Adrian Prantl1f599f92015-05-21 20:37:30 +00001926 Printer.printInt("dwoId", N->getDWOId());
David Blaikiea01f2952016-08-24 18:29:49 +00001927 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
Dehao Chen0944a8c2017-02-01 22:45:09 +00001928 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1929 false);
David Blaikie66cf14d2018-08-16 21:29:55 +00001930 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001931 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001932}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001933
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001934static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001935 TypePrinting *TypePrinter, SlotTracker *Machine,
1936 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001937 Out << "!DISubprogram(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001938 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1939 Printer.printString("name", N->getName());
1940 Printer.printString("linkageName", N->getLinkageName());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001941 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1942 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001943 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001944 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001945 Printer.printBool("isLocal", N->isLocalToUnit());
1946 Printer.printBool("isDefinition", N->isDefinition());
1947 Printer.printInt("scopeLine", N->getScopeLine());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001948 Printer.printMetadata("containingType", N->getRawContainingType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001949 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1950 dwarf::VirtualityString);
Peter Collingbournea1f86252016-03-17 23:58:03 +00001951 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1952 N->getVirtualIndex() != 0)
1953 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001954 Printer.printInt("thisAdjustment", N->getThisAdjustment());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001955 Printer.printDIFlags("flags", N->getFlags());
1956 Printer.printBool("isOptimized", N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001957 Printer.printMetadata("unit", N->getRawUnit());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001958 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1959 Printer.printMetadata("declaration", N->getRawDeclaration());
Shiva Chen2c864552018-05-09 02:40:45 +00001960 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001961 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001962 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001963}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001964
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001965static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1966 TypePrinting *TypePrinter, SlotTracker *Machine,
1967 const Module *Context) {
1968 Out << "!DILexicalBlock(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001969 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001970 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1971 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001972 Printer.printInt("line", N->getLine());
1973 Printer.printInt("column", N->getColumn());
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001974 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001975}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001976
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001977static void writeDILexicalBlockFile(raw_ostream &Out,
1978 const DILexicalBlockFile *N,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001979 TypePrinting *TypePrinter,
1980 SlotTracker *Machine,
1981 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001982 Out << "!DILexicalBlockFile(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001983 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001984 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1985 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001986 Printer.printInt("discriminator", N->getDiscriminator(),
1987 /* ShouldSkipZero */ false);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001988 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001989}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001990
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001991static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001992 TypePrinting *TypePrinter, SlotTracker *Machine,
1993 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001994 Out << "!DINamespace(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00001995 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1996 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001997 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Adrian Prantldbfda632016-11-03 19:42:02 +00001998 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001999 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002000}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002001
Amjad Abouda9bcf162015-12-10 12:56:35 +00002002static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2003 TypePrinting *TypePrinter, SlotTracker *Machine,
2004 const Module *Context) {
2005 Out << "!DIMacro(";
2006 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2007 Printer.printMacinfoType(N);
2008 Printer.printInt("line", N->getLine());
2009 Printer.printString("name", N->getName());
2010 Printer.printString("value", N->getValue());
2011 Out << ")";
2012}
2013
2014static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2015 TypePrinting *TypePrinter, SlotTracker *Machine,
2016 const Module *Context) {
2017 Out << "!DIMacroFile(";
2018 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2019 Printer.printInt("line", N->getLine());
2020 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2021 Printer.printMetadata("nodes", N->getRawElements());
2022 Out << ")";
2023}
2024
Adrian Prantlab1243f2015-06-29 23:03:47 +00002025static void writeDIModule(raw_ostream &Out, const DIModule *N,
2026 TypePrinting *TypePrinter, SlotTracker *Machine,
2027 const Module *Context) {
2028 Out << "!DIModule(";
2029 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2030 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2031 Printer.printString("name", N->getName());
2032 Printer.printString("configMacros", N->getConfigurationMacros());
2033 Printer.printString("includePath", N->getIncludePath());
2034 Printer.printString("isysroot", N->getISysRoot());
2035 Out << ")";
2036}
2037
2038
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002039static void writeDITemplateTypeParameter(raw_ostream &Out,
2040 const DITemplateTypeParameter *N,
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002041 TypePrinting *TypePrinter,
2042 SlotTracker *Machine,
2043 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002044 Out << "!DITemplateTypeParameter(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002045 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2046 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith3ec5fa62015-04-06 19:03:45 +00002047 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002048 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002049}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002050
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002051static void writeDITemplateValueParameter(raw_ostream &Out,
2052 const DITemplateValueParameter *N,
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002053 TypePrinting *TypePrinter,
2054 SlotTracker *Machine,
2055 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002056 Out << "!DITemplateValueParameter(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002057 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith16d182a2015-02-28 23:21:38 +00002058 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002059 Printer.printTag(N);
2060 Printer.printString("name", N->getName());
Duncan P. N. Exon Smith3ec5fa62015-04-06 19:03:45 +00002061 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002062 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002063 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002064}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002065
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002066static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002067 TypePrinting *TypePrinter,
2068 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002069 Out << "!DIGlobalVariable(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002070 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2071 Printer.printString("name", N->getName());
2072 Printer.printString("linkageName", N->getLinkageName());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002073 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2074 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002075 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002076 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002077 Printer.printBool("isLocal", N->isLocalToUnit());
2078 Printer.printBool("isDefinition", N->isDefinition());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002079 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
Victor Leschuk2ede1262016-10-20 00:13:12 +00002080 Printer.printInt("align", N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002081 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002082}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002083
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002084static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002085 TypePrinting *TypePrinter,
2086 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002087 Out << "!DILocalVariable(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002088 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002089 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002090 Printer.printInt("arg", N->getArg());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002091 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2092 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002093 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00002094 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002095 Printer.printDIFlags("flags", N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00002096 Printer.printInt("align", N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002097 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002098}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002099
Shiva Chen2c864552018-05-09 02:40:45 +00002100static void writeDILabel(raw_ostream &Out, const DILabel *N,
2101 TypePrinting *TypePrinter,
2102 SlotTracker *Machine, const Module *Context) {
2103 Out << "!DILabel(";
2104 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2105 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2106 Printer.printString("name", N->getName());
2107 Printer.printMetadata("file", N->getRawFile());
2108 Printer.printInt("line", N->getLine());
2109 Out << ")";
2110}
2111
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002112static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002113 TypePrinting *TypePrinter, SlotTracker *Machine,
2114 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002115 Out << "!DIExpression(";
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002116 FieldSeparator FS;
2117 if (N->isValid()) {
2118 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
Mehdi Amini149f6ea2016-10-05 05:59:29 +00002119 auto OpStr = dwarf::OperationEncodingString(I->getOp());
2120 assert(!OpStr.empty() && "Expected valid opcode");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002121
2122 Out << FS << OpStr;
2123 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2124 Out << FS << I->getArg(A);
2125 }
2126 } else {
2127 for (const auto &I : N->getElements())
2128 Out << FS << I;
2129 }
2130 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002131}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002132
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002133static void writeDIGlobalVariableExpression(raw_ostream &Out,
2134 const DIGlobalVariableExpression *N,
2135 TypePrinting *TypePrinter,
2136 SlotTracker *Machine,
2137 const Module *Context) {
2138 Out << "!DIGlobalVariableExpression(";
2139 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2140 Printer.printMetadata("var", N->getVariable());
2141 Printer.printMetadata("expr", N->getExpression());
2142 Out << ")";
2143}
2144
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002145static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002146 TypePrinting *TypePrinter, SlotTracker *Machine,
2147 const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002148 Out << "!DIObjCProperty(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002149 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2150 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00002151 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002152 Printer.printInt("line", N->getLine());
2153 Printer.printString("setter", N->getSetterName());
2154 Printer.printString("getter", N->getGetterName());
2155 Printer.printInt("attributes", N->getAttributes());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00002156 Printer.printMetadata("type", N->getRawType());
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002157 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002158}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002159
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002160static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002161 TypePrinting *TypePrinter,
2162 SlotTracker *Machine, const Module *Context) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002163 Out << "!DIImportedEntity(";
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002164 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2165 Printer.printTag(N);
2166 Printer.printString("name", N->getName());
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00002167 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2168 Printer.printMetadata("entity", N->getRawEntity());
Adrian Prantld63bfd22017-07-19 00:09:54 +00002169 Printer.printMetadata("file", N->getRawFile());
Duncan P. N. Exon Smith6d267f02015-03-27 00:17:42 +00002170 Printer.printInt("line", N->getLine());
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002171 Out << ")";
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00002172}
2173
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002174static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2175 TypePrinting *TypePrinter,
2176 SlotTracker *Machine,
2177 const Module *Context) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002178 if (Node->isDistinct())
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002179 Out << "distinct ";
Duncan P. N. Exon Smith3d510662015-03-16 21:21:10 +00002180 else if (Node->isTemporary())
2181 Out << "<temporary!> "; // Handle broken code.
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002182
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002183 switch (Node->getMetadataID()) {
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002184 default:
2185 llvm_unreachable("Expected uniquable MDNode");
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002186#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002187 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00002188 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
Duncan P. N. Exon Smitha6de6a42015-01-12 23:45:31 +00002189 break;
2190#include "llvm/IR/Metadata.def"
2191 }
2192}
2193
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002194// Full implementation of printing a Value as an operand with support for
2195// TypePrinting, etc.
Dan Gohman12dad632009-08-12 20:56:03 +00002196static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
Dan Gohman8061d9e2009-08-13 15:27:57 +00002197 TypePrinting *TypePrinter,
Dan Gohmana2489d12010-07-20 23:55:01 +00002198 SlotTracker *Machine,
2199 const Module *Context) {
Chris Lattner033935d2008-08-17 04:40:13 +00002200 if (V->hasName()) {
2201 PrintLLVMName(Out, V);
2202 return;
2203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002204
Chris Lattner033935d2008-08-17 04:40:13 +00002205 const Constant *CV = dyn_cast<Constant>(V);
2206 if (CV && !isa<GlobalValue>(CV)) {
Dan Gohman8061d9e2009-08-13 15:27:57 +00002207 assert(TypePrinter && "Constants require TypePrinting!");
Dan Gohmana2489d12010-07-20 23:55:01 +00002208 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002209 return;
2210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002211
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002212 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Chris Lattner033935d2008-08-17 04:40:13 +00002213 Out << "asm ";
2214 if (IA->hasSideEffects())
2215 Out << "sideeffect ";
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002216 if (IA->isAlignStack())
2217 Out << "alignstack ";
Chad Rosierd8c76102012-09-05 19:00:49 +00002218 // We don't emit the AD_ATT dialect as it's the assumed default.
2219 if (IA->getDialect() == InlineAsm::AD_Intel)
2220 Out << "inteldialect ";
Chris Lattner033935d2008-08-17 04:40:13 +00002221 Out << '"';
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002222 printEscapedString(IA->getAsmString(), Out);
Chris Lattner033935d2008-08-17 04:40:13 +00002223 Out << "\", \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002224 printEscapedString(IA->getConstraintString(), Out);
Chris Lattner033935d2008-08-17 04:40:13 +00002225 Out << '"';
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002226 return;
2227 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002228
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002229 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2230 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2231 Context, /* FromValue */ true);
Devang Patel7428d8a2009-07-22 17:43:22 +00002232 return;
2233 }
2234
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002235 char Prefix = '%';
2236 int Slot;
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002237 // If we have a SlotTracker, use it.
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002238 if (Machine) {
2239 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2240 Slot = Machine->getGlobalSlot(GV);
2241 Prefix = '@';
2242 } else {
2243 Slot = Machine->getLocalSlot(V);
Andrew Trickec4b6e72011-09-30 19:48:58 +00002244
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002245 // If the local value didn't succeed, then we may be referring to a value
2246 // from a different function. Translate it, as this can happen when using
2247 // address of blocks.
2248 if (Slot == -1)
2249 if ((Machine = createSlotTracker(V))) {
2250 Slot = Machine->getLocalSlot(V);
2251 delete Machine;
2252 }
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002253 }
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002254 } else if ((Machine = createSlotTracker(V))) {
2255 // Otherwise, create one to get the # and then destroy it.
2256 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2257 Slot = Machine->getGlobalSlot(GV);
2258 Prefix = '@';
Chris Lattnera2d810d2006-01-25 22:26:05 +00002259 } else {
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002260 Slot = Machine->getLocalSlot(V);
Chris Lattnerd84bb632002-04-16 21:36:08 +00002261 }
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002262 delete Machine;
Craig Topperc6207612014-04-09 06:08:46 +00002263 Machine = nullptr;
Chris Lattner5b82a0a2011-08-03 06:15:41 +00002264 } else {
2265 Slot = -1;
Chris Lattnerd84bb632002-04-16 21:36:08 +00002266 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002267
Chris Lattner3a36d2c2008-08-19 05:06:27 +00002268 if (Slot != -1)
2269 Out << Prefix << Slot;
2270 else
2271 Out << "<badref>";
Chris Lattnerd84bb632002-04-16 21:36:08 +00002272}
2273
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002274static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2275 TypePrinting *TypePrinter,
2276 SlotTracker *Machine, const Module *Context,
2277 bool FromValue) {
Reid Kleckner6d353342017-08-23 20:31:27 +00002278 // Write DIExpressions inline when used as a value. Improves readability of
2279 // debug info intrinsics.
2280 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2281 writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2282 return;
2283 }
2284
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002285 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smithf8b3ad62015-06-27 00:15:32 +00002286 std::unique_ptr<SlotTracker> MachineStorage;
2287 if (!Machine) {
2288 MachineStorage = make_unique<SlotTracker>(Context);
2289 Machine = MachineStorage.get();
2290 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002291 int Slot = Machine->getMetadataSlot(N);
2292 if (Slot == -1)
Duncan P. N. Exon Smithfee167f2014-12-16 07:09:37 +00002293 // Give the pointer value instead of "badref", since this comes up all
2294 // the time when debugging.
2295 Out << "<" << N << ">";
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002296 else
2297 Out << '!' << Slot;
2298 return;
2299 }
2300
2301 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2302 Out << "!\"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002303 printEscapedString(MDS->getString(), Out);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002304 Out << '"';
2305 return;
2306 }
2307
2308 auto *V = cast<ValueAsMetadata>(MD);
2309 assert(TypePrinter && "TypePrinter required for metadata values");
2310 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2311 "Unexpected function-local metadata outside of value argument");
2312
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002313 TypePrinter->print(V->getValue()->getType(), Out);
2314 Out << ' ';
2315 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002316}
2317
Benjamin Kramerba05a782015-03-17 19:53:41 +00002318namespace {
Eugene Zelenkode6cce22017-06-19 22:05:08 +00002319
Benjamin Kramerba05a782015-03-17 19:53:41 +00002320class AssemblyWriter {
2321 formatted_raw_ostream &Out;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002322 const Module *TheModule = nullptr;
2323 const ModuleSummaryIndex *TheIndex = nullptr;
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00002324 std::unique_ptr<SlotTracker> SlotTrackerStorage;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002325 SlotTracker &Machine;
2326 TypePrinting TypePrinter;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002327 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002328 SetVector<const Comdat *> Comdats;
Justin Bognerd7d1a722015-09-27 22:38:50 +00002329 bool IsForDebug;
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002330 bool ShouldPreserveUseListOrder;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002331 UseListOrderStack UseListOrders;
Duncan P. N. Exon Smithe30f10e2015-04-24 21:03:05 +00002332 SmallVector<StringRef, 8> MDNames;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002333 /// Synchronization scope names registered with LLVMContext.
2334 SmallVector<StringRef, 8> SSNs;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002335 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
Benjamin Kramerba05a782015-03-17 19:53:41 +00002336
2337public:
2338 /// Construct an AssemblyWriter with an external SlotTracker
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002339 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
Justin Bognerd7d1a722015-09-27 22:38:50 +00002340 AssemblyAnnotationWriter *AAW, bool IsForDebug,
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002341 bool ShouldPreserveUseListOrder = false);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002342
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002343 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2344 const ModuleSummaryIndex *Index, bool IsForDebug);
2345
Benjamin Kramerba05a782015-03-17 19:53:41 +00002346 void printMDNodeBody(const MDNode *MD);
2347 void printNamedMDNode(const NamedMDNode *NMD);
2348
2349 void printModule(const Module *M);
2350
2351 void writeOperand(const Value *Op, bool PrintType);
Reid Kleckner6652a522017-04-28 18:37:16 +00002352 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002353 void writeOperandBundles(ImmutableCallSite CS);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002354 void writeSyncScope(const LLVMContext &Context,
2355 SyncScope::ID SSID);
2356 void writeAtomic(const LLVMContext &Context,
2357 AtomicOrdering Ordering,
2358 SyncScope::ID SSID);
2359 void writeAtomicCmpXchg(const LLVMContext &Context,
2360 AtomicOrdering SuccessOrdering,
Benjamin Kramerba05a782015-03-17 19:53:41 +00002361 AtomicOrdering FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002362 SyncScope::ID SSID);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002363
2364 void writeAllMDNodes();
2365 void writeMDNode(unsigned Slot, const MDNode *Node);
2366 void writeAllAttributeGroups();
2367
2368 void printTypeIdentities();
2369 void printGlobal(const GlobalVariable *GV);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002370 void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002371 void printComdat(const Comdat *C);
2372 void printFunction(const Function *F);
Reid Kleckner6652a522017-04-28 18:37:16 +00002373 void printArgument(const Argument *FA, AttributeSet Attrs);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002374 void printBasicBlock(const BasicBlock *BB);
2375 void printInstructionLine(const Instruction &I);
2376 void printInstruction(const Instruction &I);
2377
2378 void printUseListOrder(const UseListOrder &Order);
2379 void printUseLists(const Function *F);
2380
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002381 void printModuleSummaryIndex();
2382 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2383 void printSummary(const GlobalValueSummary &Summary);
2384 void printAliasSummary(const AliasSummary *AS);
2385 void printGlobalVarSummary(const GlobalVarSummary *GS);
2386 void printFunctionSummary(const FunctionSummary *FS);
2387 void printTypeIdSummary(const TypeIdSummary &TIS);
2388 void printTypeTestResolution(const TypeTestResolution &TTRes);
2389 void printArgs(const std::vector<uint64_t> &Args);
2390 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2391 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2392 void printVFuncId(const FunctionSummary::VFuncId VFId);
2393 void
2394 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2395 const char *Tag);
2396 void
2397 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2398 const char *Tag);
2399
Benjamin Kramerba05a782015-03-17 19:53:41 +00002400private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002401 /// Print out metadata attachments.
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00002402 void printMetadataAttachments(
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00002403 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2404 StringRef Separator);
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00002405
Benjamin Kramerba05a782015-03-17 19:53:41 +00002406 // printInfoComment - Print a little comment after the instruction indicating
2407 // which slot it occupies.
2408 void printInfoComment(const Value &V);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00002409
2410 // printGCRelocateComment - print comment after call to the gc.relocate
2411 // intrinsic indicating base and derived pointer names.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002412 void printGCRelocateComment(const GCRelocateInst &Relocate);
Benjamin Kramerba05a782015-03-17 19:53:41 +00002413};
Eugene Zelenkode6cce22017-06-19 22:05:08 +00002414
2415} // end anonymous namespace
Benjamin Kramerba05a782015-03-17 19:53:41 +00002416
Justin Bogner0ffea9d2015-09-02 22:46:15 +00002417AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2418 const Module *M, AssemblyAnnotationWriter *AAW,
Justin Bognerd7d1a722015-09-27 22:38:50 +00002419 bool IsForDebug, bool ShouldPreserveUseListOrder)
Roman Tereshind96de6f2018-03-22 21:29:07 +00002420 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
Justin Bognerd7d1a722015-09-27 22:38:50 +00002421 IsForDebug(IsForDebug),
Justin Bogner0ffea9d2015-09-02 22:46:15 +00002422 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
David Majnemerdad0a642014-06-27 18:19:56 +00002423 if (!TheModule)
2424 return;
Peter Collingbourne6d88fde2016-06-22 20:29:42 +00002425 for (const GlobalObject &GO : TheModule->global_objects())
2426 if (const Comdat *C = GO.getComdat())
David Majnemerdad0a642014-06-27 18:19:56 +00002427 Comdats.insert(C);
Daniel Maleaded9f932013-05-08 20:38:31 +00002428}
Chris Lattner2e9fee42001-07-12 23:35:26 +00002429
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002430AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2431 const ModuleSummaryIndex *Index, bool IsForDebug)
2432 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2433 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2434
Chris Lattner78e2e8b2006-12-06 06:24:27 +00002435void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
Craig Topperc6207612014-04-09 06:08:46 +00002436 if (!Operand) {
Chris Lattner08f7d0c2005-02-24 16:58:29 +00002437 Out << "<null operand!>";
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002438 return;
Chris Lattner08f7d0c2005-02-24 16:58:29 +00002439 }
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002440 if (PrintType) {
2441 TypePrinter.print(Operand->getType(), Out);
2442 Out << ' ';
2443 }
Dan Gohmana2489d12010-07-20 23:55:01 +00002444 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
Chris Lattner2f7c9632001-06-06 20:29:01 +00002445}
2446
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002447void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2448 SyncScope::ID SSID) {
2449 switch (SSID) {
2450 case SyncScope::System: {
2451 break;
2452 }
2453 default: {
2454 if (SSNs.empty())
2455 Context.getSyncScopeNames(SSNs);
2456
2457 Out << " syncscope(\"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002458 printEscapedString(SSNs[SSID], Out);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002459 Out << "\")";
2460 break;
2461 }
2462 }
2463}
2464
2465void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2466 AtomicOrdering Ordering,
2467 SyncScope::ID SSID) {
JF Bastien800f87a2016-04-06 21:19:33 +00002468 if (Ordering == AtomicOrdering::NotAtomic)
Eli Friedmanfee02c62011-07-25 23:16:38 +00002469 return;
2470
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002471 writeSyncScope(Context, SSID);
JF Bastien800f87a2016-04-06 21:19:33 +00002472 Out << " " << toIRString(Ordering);
Eli Friedmanfee02c62011-07-25 23:16:38 +00002473}
2474
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002475void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2476 AtomicOrdering SuccessOrdering,
Tim Northovere94a5182014-03-11 10:48:52 +00002477 AtomicOrdering FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002478 SyncScope::ID SSID) {
JF Bastien800f87a2016-04-06 21:19:33 +00002479 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2480 FailureOrdering != AtomicOrdering::NotAtomic);
Tim Northovere94a5182014-03-11 10:48:52 +00002481
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002482 writeSyncScope(Context, SSID);
JF Bastien800f87a2016-04-06 21:19:33 +00002483 Out << " " << toIRString(SuccessOrdering);
2484 Out << " " << toIRString(FailureOrdering);
Tim Northovere94a5182014-03-11 10:48:52 +00002485}
2486
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487void AssemblyWriter::writeParamOperand(const Value *Operand,
Reid Kleckner6652a522017-04-28 18:37:16 +00002488 AttributeSet Attrs) {
Craig Topperc6207612014-04-09 06:08:46 +00002489 if (!Operand) {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002490 Out << "<null operand!>";
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002491 return;
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002492 }
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002493
2494 // Print the type
2495 TypePrinter.print(Operand->getType(), Out);
2496 // Print parameter attributes list
Reid Kleckner6652a522017-04-28 18:37:16 +00002497 if (Attrs.hasAttributes())
2498 Out << ' ' << Attrs.getAsString();
Chris Lattnerb419a1e2009-12-31 02:33:14 +00002499 Out << ' ';
2500 // Print the operand
Dan Gohmana2489d12010-07-20 23:55:01 +00002501 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002502}
Chris Lattner2f7c9632001-06-06 20:29:01 +00002503
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002504void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2505 if (!CS.hasOperandBundles())
2506 return;
2507
2508 Out << " [ ";
2509
2510 bool FirstBundle = true;
2511 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002512 OperandBundleUse BU = CS.getOperandBundleAt(i);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002513
2514 if (!FirstBundle)
2515 Out << ", ";
2516 FirstBundle = false;
2517
2518 Out << '"';
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002519 printEscapedString(BU.getTagName(), Out);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002520 Out << '"';
2521
2522 Out << '(';
2523
2524 bool FirstInput = true;
2525 for (const auto &Input : BU.Inputs) {
2526 if (!FirstInput)
2527 Out << ", ";
2528 FirstInput = false;
2529
2530 TypePrinter.print(Input->getType(), Out);
2531 Out << " ";
2532 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2533 }
2534
2535 Out << ')';
2536 }
2537
2538 Out << " ]";
2539}
2540
Chris Lattner7bfee412001-10-29 16:05:51 +00002541void AssemblyWriter::printModule(const Module *M) {
Teresa Johnsonfc801f52018-07-03 15:52:57 +00002542 Machine.initializeIfNeeded();
Bill Wendling829b4782013-02-11 08:43:33 +00002543
Duncan P. N. Exon Smith89010d82015-04-15 01:36:30 +00002544 if (ShouldPreserveUseListOrder)
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00002545 UseListOrders = predictUseListOrder(M);
2546
Chris Lattner4d8689e2005-03-02 23:12:40 +00002547 if (!M->getModuleIdentifier().empty() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00002548 // Don't print the ID if it will start a new line (which would
Chris Lattner4d8689e2005-03-02 23:12:40 +00002549 // require a comment char before it).
2550 M->getModuleIdentifier().find('\n') == std::string::npos)
2551 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2552
Teresa Johnson83c517c2016-03-30 18:15:08 +00002553 if (!M->getSourceFileName().empty()) {
Teresa Johnsond8d94652016-03-30 22:17:28 +00002554 Out << "source_filename = \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002555 printEscapedString(M->getSourceFileName(), Out);
Teresa Johnsond8d94652016-03-30 22:17:28 +00002556 Out << "\"\n";
Teresa Johnson83c517c2016-03-30 18:15:08 +00002557 }
2558
Rafael Espindolaf863ee22014-02-25 20:01:08 +00002559 const std::string &DL = M->getDataLayoutStr();
2560 if (!DL.empty())
2561 Out << "target datalayout = \"" << DL << "\"\n";
Reid Spencer48f98c82004-07-25 21:44:54 +00002562 if (!M->getTargetTriple().empty())
Reid Spencerffec7df2004-07-25 21:29:43 +00002563 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00002564
Chris Lattnereef2fe72006-01-24 04:13:11 +00002565 if (!M->getModuleInlineAsm().empty()) {
Dan Gohman69273e62009-08-12 23:54:22 +00002566 Out << '\n';
Benjamin Kramerbbd05a22015-06-07 13:59:33 +00002567
2568 // Split the string into lines, to make it easier to read the .ll file.
Benjamin Kramerf1cfc422015-06-08 18:58:57 +00002569 StringRef Asm = M->getModuleInlineAsm();
Benjamin Kramerbbd05a22015-06-07 13:59:33 +00002570 do {
2571 StringRef Front;
2572 std::tie(Front, Asm) = Asm.split('\n');
2573
Chris Lattnerefaf35d2006-01-24 00:45:30 +00002574 // We found a newline, print the portion of the asm string from the
2575 // last newline up to this newline.
2576 Out << "module asm \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00002577 printEscapedString(Front, Out);
Chris Lattnerefaf35d2006-01-24 00:45:30 +00002578 Out << "\"\n";
Benjamin Kramerbbd05a22015-06-07 13:59:33 +00002579 } while (!Asm.empty());
Chris Lattner6ed87bd2006-01-23 23:03:36 +00002580 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002581
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002582 printTypeIdentities();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002583
David Majnemerdad0a642014-06-27 18:19:56 +00002584 // Output all comdats.
2585 if (!Comdats.empty())
2586 Out << '\n';
2587 for (const Comdat *C : Comdats) {
2588 printComdat(C);
2589 if (C != Comdats.back())
2590 Out << '\n';
2591 }
2592
Dan Gohman69273e62009-08-12 23:54:22 +00002593 // Output all globals.
2594 if (!M->global_empty()) Out << '\n';
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002595 for (const GlobalVariable &GV : M->globals()) {
2596 printGlobal(&GV); Out << '\n';
Duncan Sands66fc0e62012-09-12 09:55:51 +00002597 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002598
Chris Lattnerd2747052007-04-26 02:24:10 +00002599 // Output all aliases.
2600 if (!M->alias_empty()) Out << "\n";
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002601 for (const GlobalAlias &GA : M->aliases())
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002602 printIndirectSymbol(&GA);
Chris Lattnerfee714f2001-09-07 16:36:04 +00002603
Dmitry Polukhina1feff72016-04-07 12:32:19 +00002604 // Output all ifuncs.
2605 if (!M->ifunc_empty()) Out << "\n";
2606 for (const GlobalIFunc &GI : M->ifuncs())
2607 printIndirectSymbol(&GI);
2608
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00002609 // Output global use-lists.
2610 printUseLists(nullptr);
2611
Chris Lattner2cdd49d2004-09-14 05:06:58 +00002612 // Output all of the functions.
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002613 for (const Function &F : *M)
2614 printFunction(&F);
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00002615 assert(UseListOrders.empty() && "All use-lists should have been consumed");
Devang Patel983c6b12009-07-08 21:44:25 +00002616
Bill Wendling829b4782013-02-11 08:43:33 +00002617 // Output all attribute groups.
Bill Wendling04945972013-04-29 23:48:06 +00002618 if (!Machine.as_empty()) {
Bill Wendling829b4782013-02-11 08:43:33 +00002619 Out << '\n';
2620 writeAllAttributeGroups();
2621 }
2622
Devang Patel23e68302009-07-29 22:04:47 +00002623 // Output named metadata.
Dan Gohman69273e62009-08-12 23:54:22 +00002624 if (!M->named_metadata_empty()) Out << '\n';
Andrew Trickec4b6e72011-09-30 19:48:58 +00002625
Yaron Kerenf3cf9d12015-06-13 17:50:47 +00002626 for (const NamedMDNode &Node : M->named_metadata())
2627 printNamedMDNode(&Node);
Devang Patel23e68302009-07-29 22:04:47 +00002628
2629 // Output metadata.
Chris Lattnercf4a76e2009-12-31 02:20:11 +00002630 if (!Machine.mdn_empty()) {
Chris Lattnerbddea6a2009-12-31 02:13:35 +00002631 Out << '\n';
2632 writeAllMDNodes();
2633 }
Chris Lattnerfee714f2001-09-07 16:36:04 +00002634}
2635
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002636void AssemblyWriter::printModuleSummaryIndex() {
2637 assert(TheIndex);
Teresa Johnsonfc801f52018-07-03 15:52:57 +00002638 Machine.initializeIndexIfNeeded();
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002639
2640 Out << "\n";
2641
Teresa Johnson8fc76662018-07-02 22:09:23 +00002642 // Print module path entries. To print in order, add paths to a vector
2643 // indexed by module slot.
Teresa Johnson724e7a12018-05-26 02:53:52 +00002644 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002645 std::string RegularLTOModuleName = "[Regular LTO]";
2646 moduleVec.resize(TheIndex->modulePaths().size());
Teresa Johnson8fc76662018-07-02 22:09:23 +00002647 for (auto &ModPath : TheIndex->modulePaths())
2648 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2649 // A module id of -1 is a special entry for a regular LTO module created
2650 // during the thin link.
2651 ModPath.second.first == -1u ? RegularLTOModuleName
2652 : (std::string)ModPath.first(),
2653 ModPath.second.second);
2654
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002655 unsigned i = 0;
2656 for (auto &ModPair : moduleVec) {
2657 Out << "^" << i++ << " = module: (";
Andrew Ngac305e12018-07-12 14:40:21 +00002658 Out << "path: \"";
2659 printEscapedString(ModPair.first, Out);
2660 Out << "\", hash: (";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002661 FieldSeparator FS;
2662 for (auto Hash : ModPair.second)
2663 Out << FS << Hash;
2664 Out << "))\n";
2665 }
2666
2667 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2668 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2669 for (auto &GlobalList : *TheIndex) {
2670 auto GUID = GlobalList.first;
2671 for (auto &Summary : GlobalList.second.SummaryList)
2672 SummaryToGUIDMap[Summary.get()] = GUID;
2673 }
2674
2675 // Print the global value summary entries.
2676 for (auto &GlobalList : *TheIndex) {
2677 auto GUID = GlobalList.first;
2678 auto VI = TheIndex->getValueInfo(GlobalList);
2679 printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2680 }
2681
2682 // Print the TypeIdMap entries.
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002683 for (auto TidIter = TheIndex->typeIds().begin();
2684 TidIter != TheIndex->typeIds().end(); TidIter++) {
2685 Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2686 << " = typeid: (name: \"" << TidIter->second.first << "\"";
2687 printTypeIdSummary(TidIter->second.second);
2688 Out << ") ; guid = " << TidIter->first << "\n";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002689 }
2690}
2691
2692static const char *
2693getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2694 switch (K) {
2695 case WholeProgramDevirtResolution::Indir:
2696 return "indir";
2697 case WholeProgramDevirtResolution::SingleImpl:
2698 return "singleImpl";
2699 case WholeProgramDevirtResolution::BranchFunnel:
2700 return "branchFunnel";
2701 }
2702 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2703}
2704
2705static const char *getWholeProgDevirtResByArgKindName(
2706 WholeProgramDevirtResolution::ByArg::Kind K) {
2707 switch (K) {
2708 case WholeProgramDevirtResolution::ByArg::Indir:
2709 return "indir";
2710 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2711 return "uniformRetVal";
2712 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2713 return "uniqueRetVal";
2714 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2715 return "virtualConstProp";
2716 }
2717 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2718}
2719
2720static const char *getTTResKindName(TypeTestResolution::Kind K) {
2721 switch (K) {
2722 case TypeTestResolution::Unsat:
2723 return "unsat";
2724 case TypeTestResolution::ByteArray:
2725 return "byteArray";
2726 case TypeTestResolution::Inline:
2727 return "inline";
2728 case TypeTestResolution::Single:
2729 return "single";
2730 case TypeTestResolution::AllOnes:
2731 return "allOnes";
2732 }
2733 llvm_unreachable("invalid TypeTestResolution kind");
2734}
2735
2736void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2737 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2738 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2739
2740 // The following fields are only used if the target does not support the use
2741 // of absolute symbols to store constants. Print only if non-zero.
2742 if (TTRes.AlignLog2)
2743 Out << ", alignLog2: " << TTRes.AlignLog2;
2744 if (TTRes.SizeM1)
2745 Out << ", sizeM1: " << TTRes.SizeM1;
2746 if (TTRes.BitMask)
2747 // BitMask is uint8_t which causes it to print the corresponding char.
2748 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2749 if (TTRes.InlineBits)
2750 Out << ", inlineBits: " << TTRes.InlineBits;
2751
2752 Out << ")";
2753}
2754
2755void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2756 Out << ", summary: (";
2757 printTypeTestResolution(TIS.TTRes);
2758 if (!TIS.WPDRes.empty()) {
2759 Out << ", wpdResolutions: (";
2760 FieldSeparator FS;
2761 for (auto &WPDRes : TIS.WPDRes) {
2762 Out << FS;
2763 Out << "(offset: " << WPDRes.first << ", ";
2764 printWPDRes(WPDRes.second);
2765 Out << ")";
2766 }
2767 Out << ")";
2768 }
2769 Out << ")";
2770}
2771
2772void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2773 Out << "args: (";
2774 FieldSeparator FS;
2775 for (auto arg : Args) {
2776 Out << FS;
2777 Out << arg;
2778 }
2779 Out << ")";
2780}
2781
2782void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2783 Out << "wpdRes: (kind: ";
2784 Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2785
2786 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2787 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2788
2789 if (!WPDRes.ResByArg.empty()) {
2790 Out << ", resByArg: (";
2791 FieldSeparator FS;
2792 for (auto &ResByArg : WPDRes.ResByArg) {
2793 Out << FS;
2794 printArgs(ResByArg.first);
2795 Out << ", byArg: (kind: ";
2796 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2797 if (ResByArg.second.TheKind ==
2798 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2799 ResByArg.second.TheKind ==
2800 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2801 Out << ", info: " << ResByArg.second.Info;
2802
2803 // The following fields are only used if the target does not support the
2804 // use of absolute symbols to store constants. Print only if non-zero.
2805 if (ResByArg.second.Byte || ResByArg.second.Bit)
2806 Out << ", byte: " << ResByArg.second.Byte
2807 << ", bit: " << ResByArg.second.Bit;
2808
2809 Out << ")";
2810 }
2811 Out << ")";
2812 }
2813 Out << ")";
2814}
2815
2816static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2817 switch (SK) {
2818 case GlobalValueSummary::AliasKind:
2819 return "alias";
2820 case GlobalValueSummary::FunctionKind:
2821 return "function";
2822 case GlobalValueSummary::GlobalVarKind:
2823 return "variable";
2824 }
2825 llvm_unreachable("invalid summary kind");
2826}
2827
2828void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
Teresa Johnsonf8182f12018-07-03 01:11:43 +00002829 Out << ", aliasee: ";
2830 // The indexes emitted for distributed backends may not include the
2831 // aliasee summary (only if it is being imported directly). Handle
2832 // that case by just emitting "null" as the aliasee.
2833 if (AS->hasAliasee())
2834 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2835 else
2836 Out << "null";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002837}
2838
2839void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2840 // Nothing for now
2841}
2842
Teresa Johnsonc80c8732018-05-25 15:15:39 +00002843static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2844 switch (LT) {
2845 case GlobalValue::ExternalLinkage:
2846 return "external";
2847 case GlobalValue::PrivateLinkage:
2848 return "private";
2849 case GlobalValue::InternalLinkage:
2850 return "internal";
2851 case GlobalValue::LinkOnceAnyLinkage:
2852 return "linkonce";
2853 case GlobalValue::LinkOnceODRLinkage:
2854 return "linkonce_odr";
2855 case GlobalValue::WeakAnyLinkage:
2856 return "weak";
2857 case GlobalValue::WeakODRLinkage:
2858 return "weak_odr";
2859 case GlobalValue::CommonLinkage:
2860 return "common";
2861 case GlobalValue::AppendingLinkage:
2862 return "appending";
2863 case GlobalValue::ExternalWeakLinkage:
2864 return "extern_weak";
2865 case GlobalValue::AvailableExternallyLinkage:
2866 return "available_externally";
2867 }
2868 llvm_unreachable("invalid linkage");
2869}
2870
2871// When printing the linkage types in IR where the ExternalLinkage is
2872// not printed, and other linkage types are expected to be printed with
2873// a space after the name.
2874static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2875 if (LT == GlobalValue::ExternalLinkage)
2876 return "";
2877 return getLinkageName(LT) + " ";
2878}
2879
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002880void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2881 Out << ", insts: " << FS->instCount();
2882
2883 FunctionSummary::FFlags FFlags = FS->fflags();
2884 if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2885 FFlags.ReturnDoesNotAlias) {
2886 Out << ", funcFlags: (";
2887 Out << "readNone: " << FFlags.ReadNone;
2888 Out << ", readOnly: " << FFlags.ReadOnly;
2889 Out << ", noRecurse: " << FFlags.NoRecurse;
2890 Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2891 Out << ")";
2892 }
2893 if (!FS->calls().empty()) {
2894 Out << ", calls: (";
2895 FieldSeparator IFS;
2896 for (auto &Call : FS->calls()) {
2897 Out << IFS;
2898 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2899 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2900 Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2901 else if (Call.second.RelBlockFreq)
2902 Out << ", relbf: " << Call.second.RelBlockFreq;
2903 Out << ")";
2904 }
2905 Out << ")";
2906 }
2907
2908 if (const auto *TIdInfo = FS->getTypeIdInfo())
2909 printTypeIdInfo(*TIdInfo);
2910}
2911
2912void AssemblyWriter::printTypeIdInfo(
2913 const FunctionSummary::TypeIdInfo &TIDInfo) {
2914 Out << ", typeIdInfo: (";
2915 FieldSeparator TIDFS;
2916 if (!TIDInfo.TypeTests.empty()) {
2917 Out << TIDFS;
2918 Out << "typeTests: (";
2919 FieldSeparator FS;
2920 for (auto &GUID : TIDInfo.TypeTests) {
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002921 auto TidIter = TheIndex->typeIds().equal_range(GUID);
2922 if (TidIter.first == TidIter.second) {
2923 Out << FS;
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002924 Out << GUID;
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002925 continue;
2926 }
2927 // Print all type id that correspond to this GUID.
2928 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2929 Out << FS;
2930 auto Slot = Machine.getTypeIdSlot(It->second.first);
2931 assert(Slot != -1);
2932 Out << "^" << Slot;
2933 }
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002934 }
2935 Out << ")";
2936 }
2937 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
2938 Out << TIDFS;
2939 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
2940 }
2941 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
2942 Out << TIDFS;
2943 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
2944 }
2945 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
2946 Out << TIDFS;
2947 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
2948 "typeTestAssumeConstVCalls");
2949 }
2950 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
2951 Out << TIDFS;
2952 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
2953 "typeCheckedLoadConstVCalls");
2954 }
2955 Out << ")";
2956}
2957
2958void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002959 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
2960 if (TidIter.first == TidIter.second) {
2961 Out << "vFuncId: (";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002962 Out << "guid: " << VFId.GUID;
Teresa Johnson7fb39df2018-09-25 20:14:40 +00002963 Out << ", offset: " << VFId.Offset;
2964 Out << ")";
2965 return;
2966 }
2967 // Print all type id that correspond to this GUID.
2968 FieldSeparator FS;
2969 for (auto It = TidIter.first; It != TidIter.second; ++It) {
2970 Out << FS;
2971 Out << "vFuncId: (";
2972 auto Slot = Machine.getTypeIdSlot(It->second.first);
2973 assert(Slot != -1);
2974 Out << "^" << Slot;
2975 Out << ", offset: " << VFId.Offset;
2976 Out << ")";
2977 }
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002978}
2979
2980void AssemblyWriter::printNonConstVCalls(
2981 const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
2982 Out << Tag << ": (";
2983 FieldSeparator FS;
2984 for (auto &VFuncId : VCallList) {
2985 Out << FS;
2986 printVFuncId(VFuncId);
2987 }
2988 Out << ")";
2989}
2990
2991void AssemblyWriter::printConstVCalls(
2992 const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
2993 Out << Tag << ": (";
2994 FieldSeparator FS;
2995 for (auto &ConstVCall : VCallList) {
2996 Out << FS;
Teresa Johnsonc7816802018-08-14 01:49:33 +00002997 Out << "(";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00002998 printVFuncId(ConstVCall.VFunc);
2999 if (!ConstVCall.Args.empty()) {
3000 Out << ", ";
3001 printArgs(ConstVCall.Args);
3002 }
Teresa Johnsonc7816802018-08-14 01:49:33 +00003003 Out << ")";
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00003004 }
3005 Out << ")";
3006}
3007
3008void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3009 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3010 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3011 Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
Teresa Johnson8fc76662018-07-02 22:09:23 +00003012 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00003013 << ", flags: (";
3014 Out << "linkage: " << getLinkageName(LT);
3015 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3016 Out << ", live: " << GVFlags.Live;
3017 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3018 Out << ")";
3019
3020 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3021 printAliasSummary(cast<AliasSummary>(&Summary));
3022 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3023 printFunctionSummary(cast<FunctionSummary>(&Summary));
3024 else
3025 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3026
3027 auto RefList = Summary.refs();
3028 if (!RefList.empty()) {
3029 Out << ", refs: (";
3030 FieldSeparator FS;
3031 for (auto &Ref : RefList) {
3032 Out << FS;
3033 Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3034 }
3035 Out << ")";
3036 }
3037
3038 Out << ")";
3039}
3040
3041void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3042 Out << "^" << Slot << " = gv: (";
3043 if (!VI.name().empty())
3044 Out << "name: \"" << VI.name() << "\"";
3045 else
3046 Out << "guid: " << VI.getGUID();
3047 if (!VI.getSummaryList().empty()) {
3048 Out << ", summaries: (";
3049 FieldSeparator FS;
3050 for (auto &Summary : VI.getSummaryList()) {
3051 Out << FS;
3052 printSummary(*Summary);
3053 }
3054 Out << ")";
3055 }
3056 Out << ")";
3057 if (!VI.name().empty())
3058 Out << " ; guid = " << VI.getGUID();
3059 Out << "\n";
3060}
3061
Filipe Cabecinhas62431b12015-06-02 21:25:08 +00003062static void printMetadataIdentifier(StringRef Name,
3063 formatted_raw_ostream &Out) {
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003064 if (Name.empty()) {
3065 Out << "<empty name> ";
3066 } else {
Filipe Cabecinhas1ac0d2d2015-06-02 21:25:00 +00003067 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3068 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003069 Out << Name[0];
3070 else
3071 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3072 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3073 unsigned char C = Name[i];
Guy Benyei83c74e92013-02-12 21:21:59 +00003074 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3075 C == '.' || C == '_')
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003076 Out << C;
3077 else
3078 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3079 }
3080 }
Filipe Cabecinhas62431b12015-06-02 21:25:08 +00003081}
3082
3083void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3084 Out << '!';
3085 printMetadataIdentifier(NMD->getName(), Out);
Nick Lewycky5bcbd732011-06-15 06:37:58 +00003086 Out << " = !{";
Chris Lattner2c48c642009-12-31 01:54:05 +00003087 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
Filipe Cabecinhas1ac0d2d2015-06-02 21:25:00 +00003088 if (i)
3089 Out << ", ";
Reid Kleckner6d353342017-08-23 20:31:27 +00003090
3091 // Write DIExpressions inline.
3092 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3093 MDNode *Op = NMD->getOperand(i);
3094 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3095 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3096 continue;
3097 }
3098
3099 int Slot = Machine.getMetadataSlot(Op);
Dan Gohman0a54da22010-09-09 20:53:58 +00003100 if (Slot == -1)
3101 Out << "<badref>";
3102 else
3103 Out << '!' << Slot;
Chris Lattner2c48c642009-12-31 01:54:05 +00003104 }
3105 Out << "}\n";
3106}
3107
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003108static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
Dan Gohmane2745262009-08-12 17:23:50 +00003109 formatted_raw_ostream &Out) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003110 switch (Vis) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003111 case GlobalValue::DefaultVisibility: break;
3112 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3113 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3114 }
3115}
3116
Rafael Espindolae4b02312018-01-11 22:15:05 +00003117static void PrintDSOLocation(const GlobalValue &GV,
3118 formatted_raw_ostream &Out) {
Rafael Espindola9fbc0402018-01-18 02:08:23 +00003119 // GVs with local linkage or non default visibility are implicitly dso_local,
3120 // so we don't print it.
3121 bool Implicit = GV.hasLocalLinkage() ||
3122 (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3123 if (GV.isDSOLocal() && !Implicit)
Sean Fertilec70d28b2017-10-26 15:00:26 +00003124 Out << "dso_local ";
3125}
3126
Nico Rieck7157bb72014-01-14 15:22:47 +00003127static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3128 formatted_raw_ostream &Out) {
3129 switch (SCT) {
3130 case GlobalValue::DefaultStorageClass: break;
3131 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3132 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3133 }
3134}
3135
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003136static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3137 formatted_raw_ostream &Out) {
3138 switch (TLM) {
3139 case GlobalVariable::NotThreadLocal:
3140 break;
3141 case GlobalVariable::GeneralDynamicTLSModel:
3142 Out << "thread_local ";
3143 break;
3144 case GlobalVariable::LocalDynamicTLSModel:
3145 Out << "thread_local(localdynamic) ";
3146 break;
3147 case GlobalVariable::InitialExecTLSModel:
3148 Out << "thread_local(initialexec) ";
3149 break;
3150 case GlobalVariable::LocalExecTLSModel:
3151 Out << "thread_local(localexec) ";
3152 break;
3153 }
3154}
3155
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003156static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3157 switch (UA) {
3158 case GlobalVariable::UnnamedAddr::None:
3159 return "";
3160 case GlobalVariable::UnnamedAddr::Local:
3161 return "local_unnamed_addr";
3162 case GlobalVariable::UnnamedAddr::Global:
3163 return "unnamed_addr";
3164 }
Aaron Ballman2b9fa3f2016-06-15 15:27:53 +00003165 llvm_unreachable("Unknown UnnamedAddr");
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003166}
3167
Rafael Espindola83a362c2015-01-06 22:55:16 +00003168static void maybePrintComdat(formatted_raw_ostream &Out,
3169 const GlobalObject &GO) {
3170 const Comdat *C = GO.getComdat();
3171 if (!C)
3172 return;
3173
3174 if (isa<GlobalVariable>(GO))
3175 Out << ',';
3176 Out << " comdat";
3177
3178 if (GO.getName() == C->getName())
3179 return;
3180
3181 Out << '(';
3182 PrintLLVMName(Out, C->getName(), ComdatPrefix);
3183 Out << ')';
3184}
3185
Chris Lattner7bfee412001-10-29 16:05:51 +00003186void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
Dan Gohman5ded1422010-01-29 23:12:36 +00003187 if (GV->isMaterializable())
3188 Out << "; Materializable\n";
3189
Dan Gohmana2489d12010-07-20 23:55:01 +00003190 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
Dan Gohman466876b2009-08-12 23:32:33 +00003191 Out << " = ";
Chris Lattner37798642001-09-18 04:01:05 +00003192
Chris Lattner1508d3f2008-08-19 05:16:28 +00003193 if (!GV->hasInitializer() && GV->hasExternalLinkage())
3194 Out << "external ";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003195
Teresa Johnsonc80c8732018-05-25 15:15:39 +00003196 Out << getLinkageNameWithSpace(GV->getLinkage());
Rafael Espindolae4b02312018-01-11 22:15:05 +00003197 PrintDSOLocation(*GV, Out);
Chris Lattner1508d3f2008-08-19 05:16:28 +00003198 PrintVisibility(GV->getVisibility(), Out);
Nico Rieck7157bb72014-01-14 15:22:47 +00003199 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003200 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003201 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3202 if (!UA.empty())
3203 Out << UA << ' ';
Lauro Ramos Venancio749e4662007-04-12 18:32:50 +00003204
Chris Lattnerac161bf2009-01-02 07:01:27 +00003205 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3206 Out << "addrspace(" << AddressSpace << ") ";
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003207 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
Misha Brukmana6619a92004-06-21 21:53:56 +00003208 Out << (GV->isConstant() ? "constant " : "global ");
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003209 TypePrinter.print(GV->getValueType(), Out);
Chris Lattner37798642001-09-18 04:01:05 +00003210
Dan Gohman81313fd2008-09-14 17:21:12 +00003211 if (GV->hasInitializer()) {
3212 Out << ' ';
Devang Patel983c6b12009-07-08 21:44:25 +00003213 writeOperand(GV->getInitializer(), false);
Dan Gohman81313fd2008-09-14 17:21:12 +00003214 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003215
Chris Lattner9380b812010-07-07 23:16:37 +00003216 if (GV->hasSection()) {
3217 Out << ", section \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00003218 printEscapedString(GV->getSection(), Out);
Chris Lattner9380b812010-07-07 23:16:37 +00003219 Out << '"';
3220 }
Rafael Espindola83a362c2015-01-06 22:55:16 +00003221 maybePrintComdat(Out, *GV);
Chris Lattner4b96c542005-11-12 00:10:19 +00003222 if (GV->getAlignment())
Chris Lattnerf8a974d2005-11-06 06:48:53 +00003223 Out << ", align " << GV->getAlignment();
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003224
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003225 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3226 GV->getAllMetadata(MDs);
3227 printMetadataAttachments(MDs, ", ");
3228
Javed Absarf3d79042017-05-11 12:28:08 +00003229 auto Attrs = GV->getAttributes();
3230 if (Attrs.hasAttributes())
3231 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3232
Chris Lattner113f4f42002-06-25 16:13:24 +00003233 printInfoComment(*GV);
Chris Lattnerda975502001-09-10 07:58:01 +00003234}
3235
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003236void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3237 if (GIS->isMaterializable())
Dan Gohman5ded1422010-01-29 23:12:36 +00003238 Out << "; Materializable\n";
3239
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003240 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
Rafael Espindola54fc2982015-06-17 17:53:31 +00003241 Out << " = ";
3242
Teresa Johnsonc80c8732018-05-25 15:15:39 +00003243 Out << getLinkageNameWithSpace(GIS->getLinkage());
Rafael Espindolae4b02312018-01-11 22:15:05 +00003244 PrintDSOLocation(*GIS, Out);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003245 PrintVisibility(GIS->getVisibility(), Out);
3246 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3247 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003248 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3249 if (!UA.empty())
3250 Out << UA << ' ';
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003251
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003252 if (isa<GlobalAlias>(GIS))
3253 Out << "alias ";
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003254 else if (isa<GlobalIFunc>(GIS))
3255 Out << "ifunc ";
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003256 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003257 llvm_unreachable("Not an alias or ifunc!");
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003258
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003259 TypePrinter.print(GIS->getValueType(), Out);
David Blaikie2f408302015-09-11 03:22:04 +00003260
3261 Out << ", ";
3262
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003263 const Constant *IS = GIS->getIndirectSymbol();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003264
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003265 if (!IS) {
3266 TypePrinter.print(GIS->getType(), Out);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003267 Out << " <<NULL ALIASEE>>";
Jay Foad92c19132011-08-01 12:48:54 +00003268 } else {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003269 writeOperand(IS, !isa<ConstantExpr>(IS));
Jay Foad92c19132011-08-01 12:48:54 +00003270 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003271
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003272 printInfoComment(*GIS);
Chris Lattner1508d3f2008-08-19 05:16:28 +00003273 Out << '\n';
Anton Korobeynikova97b6942007-04-25 14:27:10 +00003274}
3275
David Majnemerdad0a642014-06-27 18:19:56 +00003276void AssemblyWriter::printComdat(const Comdat *C) {
3277 C->print(Out);
3278}
3279
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003280void AssemblyWriter::printTypeIdentities() {
Roman Tereshind96de6f2018-03-22 21:29:07 +00003281 if (TypePrinter.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003282 return;
Andrew Trickec4b6e72011-09-30 19:48:58 +00003283
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003284 Out << '\n';
Andrew Trickec4b6e72011-09-30 19:48:58 +00003285
Chris Lattner3243ea12009-03-01 00:03:38 +00003286 // Emit all numbered types.
Roman Tereshind96de6f2018-03-22 21:29:07 +00003287 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3288 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3289 Out << '%' << I << " = type ";
Andrew Trickec4b6e72011-09-30 19:48:58 +00003290
Chris Lattner3243ea12009-03-01 00:03:38 +00003291 // Make sure we print out at least one level of the type structure, so
3292 // that we do not get %2 = type %2
Roman Tereshind96de6f2018-03-22 21:29:07 +00003293 TypePrinter.printStructBody(NumberedTypes[I], Out);
Dan Gohman69273e62009-08-12 23:54:22 +00003294 Out << '\n';
Chris Lattner3243ea12009-03-01 00:03:38 +00003295 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00003296
Roman Tereshind96de6f2018-03-22 21:29:07 +00003297 auto &NamedTypes = TypePrinter.getNamedTypes();
3298 for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3299 PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
Chris Lattner1508d3f2008-08-19 05:16:28 +00003300 Out << " = type ";
Reid Spencere7e96712004-05-25 08:53:40 +00003301
3302 // Make sure we print out at least one level of the type structure, so
3303 // that we do not get %FILE = type %FILE
Roman Tereshind96de6f2018-03-22 21:29:07 +00003304 TypePrinter.printStructBody(NamedTypes[I], Out);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003305 Out << '\n';
Reid Spencere7e96712004-05-25 08:53:40 +00003306 }
Reid Spencer32af9e82007-01-06 07:24:44 +00003307}
3308
Misha Brukmanc566ca362004-03-02 00:22:19 +00003309/// printFunction - Print all aspects of a function.
Chris Lattner113f4f42002-06-25 16:13:24 +00003310void AssemblyWriter::printFunction(const Function *F) {
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003311 // Print out the return type and name.
3312 Out << '\n';
Chris Lattner379a8d22003-04-16 20:28:45 +00003313
Misha Brukmana6619a92004-06-21 21:53:56 +00003314 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
Chris Lattner8339f7d2003-10-30 23:41:03 +00003315
Dan Gohman5ded1422010-01-29 23:12:36 +00003316 if (F->isMaterializable())
3317 Out << "; Materializable\n";
3318
Reid Klecknerb5180542017-03-21 16:57:19 +00003319 const AttributeList &Attrs = F->getAttributes();
3320 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003321 AttributeSet AS = Attrs.getFnAttributes();
Rafael Espindolacbf5a7a2013-05-01 13:07:03 +00003322 std::string AttrStr;
3323
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003324 for (const Attribute &Attr : AS) {
Rafael Espindolacbf5a7a2013-05-01 13:07:03 +00003325 if (!Attr.isStringAttribute()) {
3326 if (!AttrStr.empty()) AttrStr += ' ';
3327 AttrStr += Attr.getAsString();
3328 }
3329 }
3330
Bill Wendling847a5c32013-04-16 20:55:47 +00003331 if (!AttrStr.empty())
3332 Out << "; Function Attrs: " << AttrStr << '\n';
3333 }
3334
Peter Collingbourne21521892016-06-21 23:42:48 +00003335 Machine.incorporateFunction(F);
3336
3337 if (F->isDeclaration()) {
3338 Out << "declare";
3339 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3340 F->getAllMetadata(MDs);
3341 printMetadataAttachments(MDs, " ");
3342 Out << ' ';
3343 } else
Reid Spencer7ce2d2a2006-12-29 20:29:48 +00003344 Out << "define ";
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003345
Teresa Johnsonc80c8732018-05-25 15:15:39 +00003346 Out << getLinkageNameWithSpace(F->getLinkage());
Rafael Espindolae4b02312018-01-11 22:15:05 +00003347 PrintDSOLocation(*F, Out);
Chris Lattner3a36d2c2008-08-19 05:06:27 +00003348 PrintVisibility(F->getVisibility(), Out);
Nico Rieck7157bb72014-01-14 15:22:47 +00003349 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
Chris Lattner379a8d22003-04-16 20:28:45 +00003350
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003351 // Print the calling convention.
Micah Villmow857186d2012-09-13 15:11:12 +00003352 if (F->getCallingConv() != CallingConv::C) {
3353 PrintCallingConv(F->getCallingConv(), Out);
3354 Out << " ";
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003355 }
3356
Chris Lattner229907c2011-07-18 04:54:35 +00003357 FunctionType *FT = F->getFunctionType();
Reid Klecknerb5180542017-03-21 16:57:19 +00003358 if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3359 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00003360 TypePrinter.print(F->getReturnType(), Out);
Chris Lattner585297e82008-08-19 05:26:17 +00003361 Out << ' ';
Dan Gohmana2489d12010-07-20 23:55:01 +00003362 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
Misha Brukmana6619a92004-06-21 21:53:56 +00003363 Out << '(';
Chris Lattnerfee714f2001-09-07 16:36:04 +00003364
Chris Lattner7bfee412001-10-29 16:05:51 +00003365 // Loop over the arguments, printing them...
Justin Bognerd7d1a722015-09-27 22:38:50 +00003366 if (F->isDeclaration() && !IsForDebug) {
Justin Bogner58e08232015-09-02 17:54:41 +00003367 // We're only interested in the type here - don't print argument names.
3368 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
Chris Lattner82738fe2007-04-18 00:57:22 +00003369 // Insert commas as we go... the first arg doesn't get a comma
Justin Bogner58e08232015-09-02 17:54:41 +00003370 if (I)
3371 Out << ", ";
3372 // Output type...
3373 TypePrinter.print(FT->getParamType(I), Out);
3374
Reid Kleckner6652a522017-04-28 18:37:16 +00003375 AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3376 if (ArgAttrs.hasAttributes())
3377 Out << ' ' << ArgAttrs.getAsString();
Chris Lattner82738fe2007-04-18 00:57:22 +00003378 }
3379 } else {
Justin Bogner58e08232015-09-02 17:54:41 +00003380 // The arguments are meaningful here, print them in detail.
Justin Bogner58e08232015-09-02 17:54:41 +00003381 for (const Argument &Arg : F->args()) {
Chris Lattner82738fe2007-04-18 00:57:22 +00003382 // Insert commas as we go... the first arg doesn't get a comma
Reid Kleckner6652a522017-04-28 18:37:16 +00003383 if (Arg.getArgNo() != 0)
Justin Bogner58e08232015-09-02 17:54:41 +00003384 Out << ", ";
Reid Kleckner6652a522017-04-28 18:37:16 +00003385 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
Chris Lattner82738fe2007-04-18 00:57:22 +00003386 }
Reid Spencer8c4914c2006-12-31 05:24:50 +00003387 }
Chris Lattnerfee714f2001-09-07 16:36:04 +00003388
3389 // Finish printing arguments...
Chris Lattner113f4f42002-06-25 16:13:24 +00003390 if (FT->isVarArg()) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003391 if (FT->getNumParams()) Out << ", ";
3392 Out << "..."; // Output varargs portion of signature!
Chris Lattnerfee714f2001-09-07 16:36:04 +00003393 }
Misha Brukmana6619a92004-06-21 21:53:56 +00003394 Out << ')';
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003395 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3396 if (!UA.empty())
3397 Out << ' ' << UA;
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003398 // We print the function address space if it is non-zero or if we are writing
3399 // a module with a non-zero program address space or if there is no valid
3400 // Module* so that the file can be parsed without the datalayout string.
3401 const Module *Mod = F->getParent();
3402 if (F->getAddressSpace() != 0 || !Mod ||
3403 Mod->getDataLayout().getProgramAddressSpace() != 0)
3404 Out << " addrspace(" << F->getAddressSpace() << ")";
Reid Klecknerb5180542017-03-21 16:57:19 +00003405 if (Attrs.hasAttributes(AttributeList::FunctionIndex))
Bill Wendling04945972013-04-29 23:48:06 +00003406 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
Chris Lattner9380b812010-07-07 23:16:37 +00003407 if (F->hasSection()) {
3408 Out << " section \"";
Jonas Devlieghere745918ff2018-05-31 17:01:42 +00003409 printEscapedString(F->getSection(), Out);
Chris Lattner9380b812010-07-07 23:16:37 +00003410 Out << '"';
3411 }
Rafael Espindola83a362c2015-01-06 22:55:16 +00003412 maybePrintComdat(Out, *F);
Chris Lattnerf8a974d2005-11-06 06:48:53 +00003413 if (F->getAlignment())
3414 Out << " align " << F->getAlignment();
Gordon Henriksend930f912008-08-17 18:44:35 +00003415 if (F->hasGC())
3416 Out << " gc \"" << F->getGC() << '"';
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003417 if (F->hasPrefixData()) {
3418 Out << " prefix ";
3419 writeOperand(F->getPrefixData(), true);
3420 }
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003421 if (F->hasPrologueData()) {
3422 Out << " prologue ";
3423 writeOperand(F->getPrologueData(), true);
3424 }
David Majnemer7fddecc2015-06-17 20:52:32 +00003425 if (F->hasPersonalityFn()) {
3426 Out << " personality ";
3427 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3428 }
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003429
Reid Spencer5301e7c2007-01-30 20:08:39 +00003430 if (F->isDeclaration()) {
Chris Lattnerfb483622010-09-02 22:52:10 +00003431 Out << '\n';
Chris Lattnerb2f02e52002-05-06 03:00:40 +00003432 } else {
Peter Collingbourne21521892016-06-21 23:42:48 +00003433 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3434 F->getAllMetadata(MDs);
3435 printMetadataAttachments(MDs, " ");
3436
Chris Lattnerfb483622010-09-02 22:52:10 +00003437 Out << " {";
3438 // Output all of the function's basic blocks.
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00003439 for (const BasicBlock &BB : *F)
3440 printBasicBlock(&BB);
Chris Lattnerfee714f2001-09-07 16:36:04 +00003441
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00003442 // Output the function's use-lists.
3443 printUseLists(F);
3444
Misha Brukmana6619a92004-06-21 21:53:56 +00003445 Out << "}\n";
Chris Lattnerfee714f2001-09-07 16:36:04 +00003446 }
3447
Reid Spencer16f2f7f2004-05-26 07:18:52 +00003448 Machine.purgeFunction();
Chris Lattner2f7c9632001-06-06 20:29:01 +00003449}
3450
Misha Brukmanc566ca362004-03-02 00:22:19 +00003451/// printArgument - This member is called for every argument that is passed into
3452/// the function. Simply print it out
Reid Kleckner6652a522017-04-28 18:37:16 +00003453void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00003454 // Output type...
Chris Lattnere101c442009-02-28 21:26:53 +00003455 TypePrinter.print(Arg->getType(), Out);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003456
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003457 // Output parameter attributes list
Reid Kleckner6652a522017-04-28 18:37:16 +00003458 if (Attrs.hasAttributes())
3459 Out << ' ' << Attrs.getAsString();
Reid Spencer8c4914c2006-12-31 05:24:50 +00003460
Chris Lattner2f7c9632001-06-06 20:29:01 +00003461 // Output name, if available...
Chris Lattner033935d2008-08-17 04:40:13 +00003462 if (Arg->hasName()) {
3463 Out << ' ';
3464 PrintLLVMName(Out, Arg);
3465 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003466}
3467
Misha Brukmanc566ca362004-03-02 00:22:19 +00003468/// printBasicBlock - This member is called for each basic block in a method.
Chris Lattner7bfee412001-10-29 16:05:51 +00003469void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003470 if (BB->hasName()) { // Print out the label if it exists...
Chris Lattner033935d2008-08-17 04:40:13 +00003471 Out << "\n";
Daniel Dunbare03eecb2009-07-25 23:55:21 +00003472 PrintLLVMName(Out, BB->getName(), LabelPrefix);
Chris Lattner033935d2008-08-17 04:40:13 +00003473 Out << ':';
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003474 } else if (!BB->use_empty()) { // Don't print block # of no uses...
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003475 Out << "\n; <label>:";
Chris Lattner5e043322007-01-11 03:54:27 +00003476 int Slot = Machine.getLocalSlot(BB);
Chris Lattner757ee0b2004-06-09 19:41:19 +00003477 if (Slot != -1)
Evgeniy Stepanove257f0f2016-01-27 21:53:08 +00003478 Out << Slot << ":";
Chris Lattner757ee0b2004-06-09 19:41:19 +00003479 else
Misha Brukmana6619a92004-06-21 21:53:56 +00003480 Out << "<badref>";
Chris Lattner58185f22002-10-02 19:38:55 +00003481 }
Chris Lattner2447ef52003-11-20 00:09:43 +00003482
Craig Topperc6207612014-04-09 06:08:46 +00003483 if (!BB->getParent()) {
Chris Lattneree97b8b2009-08-17 15:48:08 +00003484 Out.PadToColumn(50);
Dan Gohmane2745262009-08-12 17:23:50 +00003485 Out << "; Error: Block without parent!";
3486 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
Chris Lattnerfb483622010-09-02 22:52:10 +00003487 // Output predecessors for the block.
Chris Lattneree97b8b2009-08-17 15:48:08 +00003488 Out.PadToColumn(50);
Dan Gohmane2745262009-08-12 17:23:50 +00003489 Out << ";";
Gabor Greif6c6b2fd2010-03-25 23:25:28 +00003490 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003491
Chris Lattnerff834c02008-04-22 02:45:44 +00003492 if (PI == PE) {
3493 Out << " No predecessors!";
3494 } else {
Dan Gohman81313fd2008-09-14 17:21:12 +00003495 Out << " preds = ";
Chris Lattnerff834c02008-04-22 02:45:44 +00003496 writeOperand(*PI, false);
3497 for (++PI; PI != PE; ++PI) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003498 Out << ", ";
Chris Lattner78e2e8b2006-12-06 06:24:27 +00003499 writeOperand(*PI, false);
Chris Lattner00211f12003-11-16 22:59:57 +00003500 }
Chris Lattner58185f22002-10-02 19:38:55 +00003501 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003502 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003503
Chris Lattnerff834c02008-04-22 02:45:44 +00003504 Out << "\n";
Chris Lattner2f7c9632001-06-06 20:29:01 +00003505
Misha Brukmana6619a92004-06-21 21:53:56 +00003506 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
Chris Lattner8339f7d2003-10-30 23:41:03 +00003507
Chris Lattnerfee714f2001-09-07 16:36:04 +00003508 // Output all of the instructions in the basic block...
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00003509 for (const Instruction &I : *BB) {
3510 printInstructionLine(I);
Dan Gohmana4f709e2009-07-13 18:27:59 +00003511 }
Chris Lattner96cdd272004-03-08 18:51:45 +00003512
Misha Brukmana6619a92004-06-21 21:53:56 +00003513 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003514}
3515
Daniel Maleaded9f932013-05-08 20:38:31 +00003516/// printInstructionLine - Print an instruction and a newline character.
3517void AssemblyWriter::printInstructionLine(const Instruction &I) {
3518 printInstruction(I);
3519 Out << '\n';
3520}
3521
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003522/// printGCRelocateComment - print comment after call to the gc.relocate
3523/// intrinsic indicating base and derived pointer names.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003524void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003525 Out << " ; (";
Manuel Jacob83eefa62016-01-05 04:03:00 +00003526 writeOperand(Relocate.getBasePtr(), false);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003527 Out << ", ";
Manuel Jacob83eefa62016-01-05 04:03:00 +00003528 writeOperand(Relocate.getDerivedPtr(), false);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003529 Out << ")";
3530}
3531
Misha Brukmanc566ca362004-03-02 00:22:19 +00003532/// printInfoComment - Print a little comment after the instruction indicating
3533/// which slot it occupies.
Chris Lattner113f4f42002-06-25 16:13:24 +00003534void AssemblyWriter::printInfoComment(const Value &V) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00003535 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3536 printGCRelocateComment(*Relocate);
Igor Laevsky2aa8caf2015-05-05 13:20:42 +00003537
Bill Wendling847a5c32013-04-16 20:55:47 +00003538 if (AnnotationWriter)
Dan Gohmane34890f2010-02-10 20:41:46 +00003539 AnnotationWriter->printInfoComment(V, Out);
Chris Lattner862e3382001-10-13 06:42:36 +00003540}
3541
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003542static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3543 raw_ostream &Out) {
3544 // We print the address space of the call if it is non-zero.
3545 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3546 bool PrintAddrSpace = CallAddrSpace != 0;
3547 if (!PrintAddrSpace) {
3548 const Module *Mod = getModuleFromVal(I);
3549 // We also print it if it is zero but not equal to the program address space
3550 // or if we can't find a valid Module* to make it possible to parse
3551 // the resulting file even without a datalayout string.
3552 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3553 PrintAddrSpace = true;
3554 }
3555 if (PrintAddrSpace)
3556 Out << " addrspace(" << CallAddrSpace << ")";
3557}
3558
Reid Spencere7141c82006-08-28 01:02:49 +00003559// This member is called for each Instruction in a function..
Chris Lattner113f4f42002-06-25 16:13:24 +00003560void AssemblyWriter::printInstruction(const Instruction &I) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003561 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
Chris Lattner8339f7d2003-10-30 23:41:03 +00003562
Dan Gohman466876b2009-08-12 23:32:33 +00003563 // Print out indentation for an instruction.
Dan Gohmanb4583b12009-08-13 01:41:52 +00003564 Out << " ";
Chris Lattner2f7c9632001-06-06 20:29:01 +00003565
3566 // Print out name if it exists...
Chris Lattner033935d2008-08-17 04:40:13 +00003567 if (I.hasName()) {
3568 PrintLLVMName(Out, &I);
3569 Out << " = ";
Chris Lattner031560c2009-12-29 07:25:48 +00003570 } else if (!I.getType()->isVoidTy()) {
Chris Lattnerb25e5ea2008-08-29 17:19:30 +00003571 // Print out the def slot taken.
3572 int SlotNum = Machine.getLocalSlot(&I);
3573 if (SlotNum == -1)
3574 Out << "<badref> = ";
3575 else
3576 Out << '%' << SlotNum << " = ";
Chris Lattner033935d2008-08-17 04:40:13 +00003577 }
Andrew Trickec4b6e72011-09-30 19:48:58 +00003578
Reid Kleckner5772b772014-04-24 20:14:34 +00003579 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3580 if (CI->isMustTailCall())
3581 Out << "musttail ";
3582 else if (CI->isTailCall())
3583 Out << "tail ";
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00003584 else if (CI->isNoTailCall())
3585 Out << "notail ";
Reid Kleckner5772b772014-04-24 20:14:34 +00003586 }
Chris Lattner504f9242003-09-08 17:45:59 +00003587
Chris Lattner2f7c9632001-06-06 20:29:01 +00003588 // Print out the opcode...
Misha Brukmana6619a92004-06-21 21:53:56 +00003589 Out << I.getOpcodeName();
Chris Lattner2f7c9632001-06-06 20:29:01 +00003590
Eli Friedman02e737b2011-08-12 22:50:01 +00003591 // If this is an atomic load or store, print out the atomic marker.
3592 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
3593 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3594 Out << " atomic";
3595
Tim Northover420a2162014-06-13 14:24:07 +00003596 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3597 Out << " weak";
3598
Eli Friedman02e737b2011-08-12 22:50:01 +00003599 // If this is a volatile operation, print out the volatile marker.
3600 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
3601 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3602 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3603 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3604 Out << " volatile";
3605
Dan Gohman9c7f8082009-07-27 16:11:46 +00003606 // Print out optimization information.
3607 WriteOptimizationInfo(Out, &I);
3608
Reid Spencer45e52392006-12-03 06:27:29 +00003609 // Print out the compare instruction predicates
Nate Begemand2195702008-05-12 19:01:56 +00003610 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
Tim Northoverde3aea0412016-08-17 20:25:25 +00003611 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
Reid Spencer45e52392006-12-03 06:27:29 +00003612
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003613 // Print out the atomicrmw operation
3614 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3615 writeAtomicRMWOperation(Out, RMWI->getOperation());
3616
Chris Lattner2f7c9632001-06-06 20:29:01 +00003617 // Print out the type of the operands...
Craig Topperc6207612014-04-09 06:08:46 +00003618 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
Chris Lattner2f7c9632001-06-06 20:29:01 +00003619
3620 // Special case conditional branches to swizzle the condition out to the front
Gabor Greifcab008f2009-02-09 15:45:06 +00003621 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
David Blaikieb78e9e52013-02-11 01:16:51 +00003622 const BranchInst &BI(cast<BranchInst>(I));
Dan Gohman81313fd2008-09-14 17:21:12 +00003623 Out << ' ';
Gabor Greifcab008f2009-02-09 15:45:06 +00003624 writeOperand(BI.getCondition(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003625 Out << ", ";
Gabor Greifcab008f2009-02-09 15:45:06 +00003626 writeOperand(BI.getSuccessor(0), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003627 Out << ", ";
Gabor Greifcab008f2009-02-09 15:45:06 +00003628 writeOperand(BI.getSuccessor(1), true);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003629
Chris Lattner8d48df22002-04-13 18:34:38 +00003630 } else if (isa<SwitchInst>(I)) {
David Blaikieb78e9e52013-02-11 01:16:51 +00003631 const SwitchInst& SI(cast<SwitchInst>(I));
Chris Lattner3ed871f2009-10-27 19:13:16 +00003632 // Special case switch instruction to get formatting nice and correct.
Dan Gohman81313fd2008-09-14 17:21:12 +00003633 Out << ' ';
Eli Friedman95031ed2011-09-29 20:21:17 +00003634 writeOperand(SI.getCondition(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003635 Out << ", ";
Eli Friedman95031ed2011-09-29 20:21:17 +00003636 writeOperand(SI.getDefaultDest(), true);
Chris Lattner82ff9232008-08-23 22:52:27 +00003637 Out << " [";
Chandler Carruth927d8e62017-04-12 07:27:28 +00003638 for (auto Case : SI.cases()) {
Dan Gohmanb4583b12009-08-13 01:41:52 +00003639 Out << "\n ";
Chandler Carruth927d8e62017-04-12 07:27:28 +00003640 writeOperand(Case.getCaseValue(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003641 Out << ", ";
Chandler Carruth927d8e62017-04-12 07:27:28 +00003642 writeOperand(Case.getCaseSuccessor(), true);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003643 }
Dan Gohmanb4583b12009-08-13 01:41:52 +00003644 Out << "\n ]";
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003645 } else if (isa<IndirectBrInst>(I)) {
3646 // Special case indirectbr instruction to get formatting nice and correct.
Chris Lattner3ed871f2009-10-27 19:13:16 +00003647 Out << ' ';
3648 writeOperand(Operand, true);
Dan Gohman43c57402009-10-30 02:01:10 +00003649 Out << ", [";
Andrew Trickec4b6e72011-09-30 19:48:58 +00003650
Chris Lattner3ed871f2009-10-27 19:13:16 +00003651 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3652 if (i != 1)
3653 Out << ", ";
3654 writeOperand(I.getOperand(i), true);
3655 }
3656 Out << ']';
Jay Foad372ad642011-06-20 14:18:48 +00003657 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003658 Out << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00003659 TypePrinter.print(I.getType(), Out);
Misha Brukmana6619a92004-06-21 21:53:56 +00003660 Out << ' ';
Chris Lattner2f7c9632001-06-06 20:29:01 +00003661
Jay Foad372ad642011-06-20 14:18:48 +00003662 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003663 if (op) Out << ", ";
Dan Gohman81313fd2008-09-14 17:21:12 +00003664 Out << "[ ";
Jay Foad372ad642011-06-20 14:18:48 +00003665 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3666 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
Chris Lattner931ef3b2001-06-11 15:04:20 +00003667 }
Dan Gohmana76f0f72008-05-31 19:12:39 +00003668 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003669 Out << ' ';
Dan Gohmana76f0f72008-05-31 19:12:39 +00003670 writeOperand(I.getOperand(0), true);
3671 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3672 Out << ", " << *i;
3673 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003674 Out << ' ';
3675 writeOperand(I.getOperand(0), true); Out << ", ";
Dan Gohmana76f0f72008-05-31 19:12:39 +00003676 writeOperand(I.getOperand(1), true);
3677 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3678 Out << ", " << *i;
Bill Wendlingfae14752011-08-12 20:24:12 +00003679 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3680 Out << ' ';
3681 TypePrinter.print(I.getType(), Out);
David Majnemer7fddecc2015-06-17 20:52:32 +00003682 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3683 Out << '\n';
Bill Wendlingfae14752011-08-12 20:24:12 +00003684
3685 if (LPI->isCleanup())
3686 Out << " cleanup";
3687
3688 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3689 if (i != 0 || LPI->isCleanup()) Out << "\n";
3690 if (LPI->isCatch(i))
3691 Out << " catch ";
3692 else
3693 Out << " filter ";
3694
3695 writeOperand(LPI->getClause(i), true);
3696 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003697 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3698 Out << " within ";
3699 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
David Majnemer654e1302015-07-31 17:58:14 +00003700 Out << " [";
David Majnemer8a1c45d2015-12-12 05:38:55 +00003701 unsigned Op = 0;
3702 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3703 if (Op > 0)
3704 Out << ", ";
3705 writeOperand(PadBB, /*PrintType=*/true);
3706 ++Op;
3707 }
3708 Out << "] unwind ";
3709 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3710 writeOperand(UnwindDest, /*PrintType=*/true);
3711 else
3712 Out << "to caller";
3713 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3714 Out << " within ";
3715 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3716 Out << " [";
3717 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
David Majnemer654e1302015-07-31 17:58:14 +00003718 ++Op) {
3719 if (Op > 0)
3720 Out << ", ";
David Majnemer8a1c45d2015-12-12 05:38:55 +00003721 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
David Majnemer654e1302015-07-31 17:58:14 +00003722 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003723 Out << ']';
Devang Patel59643e52008-02-23 00:35:18 +00003724 } else if (isa<ReturnInst>(I) && !Operand) {
3725 Out << " void";
David Majnemer0bc0eef2015-08-15 02:46:08 +00003726 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003727 Out << " from ";
3728 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
David Majnemer0bc0eef2015-08-15 02:46:08 +00003729
3730 Out << " to ";
David Majnemer8a1c45d2015-12-12 05:38:55 +00003731 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
David Majnemer654e1302015-07-31 17:58:14 +00003732 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003733 Out << " from ";
3734 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
David Majnemer654e1302015-07-31 17:58:14 +00003735
3736 Out << " unwind ";
3737 if (CRI->hasUnwindDest())
David Majnemer8a1c45d2015-12-12 05:38:55 +00003738 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003739 else
3740 Out << "to caller";
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003741 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3742 // Print the calling convention being used.
Micah Villmow857186d2012-09-13 15:11:12 +00003743 if (CI->getCallingConv() != CallingConv::C) {
3744 Out << " ";
3745 PrintCallingConv(CI->getCallingConv(), Out);
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003746 }
3747
Gabor Greifc9a92512010-06-23 13:09:06 +00003748 Operand = CI->getCalledValue();
Ahmed Bougachaaa9fe532016-12-21 23:26:13 +00003749 FunctionType *FTy = CI->getFunctionType();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003750 Type *RetTy = FTy->getReturnType();
Reid Klecknerb5180542017-03-21 16:57:19 +00003751 const AttributeList &PAL = CI->getAttributes();
Chris Lattner2f2d9472001-11-06 21:28:12 +00003752
Reid Klecknerb5180542017-03-21 16:57:19 +00003753 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3754 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
Devang Patel221fe422008-09-29 20:49:50 +00003755
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003756 // Only print addrspace(N) if necessary:
3757 maybePrintCallAddrSpace(Operand, &I, Out);
3758
Chris Lattner463d6a52003-08-05 15:34:45 +00003759 // If possible, print out the short form of the call instruction. We can
Chris Lattner6915f8f2002-04-07 22:49:37 +00003760 // only do this if the first argument is a pointer to a nonvararg function,
Chris Lattner463d6a52003-08-05 15:34:45 +00003761 // and if the return type is not a pointer to a function.
Chris Lattner2f2d9472001-11-06 21:28:12 +00003762 //
Dan Gohman81313fd2008-09-14 17:21:12 +00003763 Out << ' ';
David Blaikie23af6482015-04-16 23:24:18 +00003764 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3765 Out << ' ';
3766 writeOperand(Operand, false);
Misha Brukmana6619a92004-06-21 21:53:56 +00003767 Out << '(';
Gabor Greifc9a92512010-06-23 13:09:06 +00003768 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3769 if (op > 0)
Dan Gohman81313fd2008-09-14 17:21:12 +00003770 Out << ", ";
Reid Kleckner6652a522017-04-28 18:37:16 +00003771 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
Chris Lattner2f7c9632001-06-06 20:29:01 +00003772 }
Reid Kleckner83498642014-08-26 00:33:28 +00003773
3774 // Emit an ellipsis if this is a musttail call in a vararg function. This
3775 // is only to aid readability, musttail calls forward varargs by default.
3776 if (CI->isMustTailCall() && CI->getParent() &&
3777 CI->getParent()->getParent() &&
3778 CI->getParent()->getParent()->isVarArg())
3779 Out << ", ...";
3780
Dan Gohman81313fd2008-09-14 17:21:12 +00003781 Out << ')';
Reid Klecknerb5180542017-03-21 16:57:19 +00003782 if (PAL.hasAttributes(AttributeList::FunctionIndex))
Bill Wendlinga0323742013-02-22 09:09:42 +00003783 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003784
3785 writeOperandBundles(CI);
Chris Lattner113f4f42002-06-25 16:13:24 +00003786 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00003787 Operand = II->getCalledValue();
Ahmed Bougachaaa9fe532016-12-21 23:26:13 +00003788 FunctionType *FTy = II->getFunctionType();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003789 Type *RetTy = FTy->getReturnType();
Reid Klecknerb5180542017-03-21 16:57:19 +00003790 const AttributeList &PAL = II->getAttributes();
Chris Lattner463d6a52003-08-05 15:34:45 +00003791
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003792 // Print the calling convention being used.
Micah Villmow857186d2012-09-13 15:11:12 +00003793 if (II->getCallingConv() != CallingConv::C) {
3794 Out << " ";
3795 PrintCallingConv(II->getCallingConv(), Out);
Chris Lattnerf7b6d312005-05-06 20:26:43 +00003796 }
3797
Reid Klecknerb5180542017-03-21 16:57:19 +00003798 if (PAL.hasAttributes(AttributeList::ReturnIndex))
3799 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
Devang Patel221fe422008-09-29 20:49:50 +00003800
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00003801 // Only print addrspace(N) if necessary:
3802 maybePrintCallAddrSpace(Operand, &I, Out);
3803
Chris Lattner463d6a52003-08-05 15:34:45 +00003804 // If possible, print out the short form of the invoke instruction. We can
3805 // only do this if the first argument is a pointer to a nonvararg function,
3806 // and if the return type is not a pointer to a function.
3807 //
Dan Gohmanc7e00ba2008-10-15 18:02:08 +00003808 Out << ' ';
David Blaikie445e3fb2015-04-24 19:32:54 +00003809 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3810 Out << ' ';
3811 writeOperand(Operand, false);
Misha Brukmana6619a92004-06-21 21:53:56 +00003812 Out << '(';
Gabor Greifc9a92512010-06-23 13:09:06 +00003813 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00003814 if (op)
Dan Gohman81313fd2008-09-14 17:21:12 +00003815 Out << ", ";
Reid Kleckner6652a522017-04-28 18:37:16 +00003816 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
Chris Lattner862e3382001-10-13 06:42:36 +00003817 }
3818
Dan Gohman81313fd2008-09-14 17:21:12 +00003819 Out << ')';
Reid Klecknerb5180542017-03-21 16:57:19 +00003820 if (PAL.hasAttributes(AttributeList::FunctionIndex))
Bill Wendlinga0323742013-02-22 09:09:42 +00003821 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
Devang Patela05633e2008-09-26 22:53:05 +00003822
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003823 writeOperandBundles(II);
3824
Dan Gohmanb4583b12009-08-13 01:41:52 +00003825 Out << "\n to ";
Chris Lattner862e3382001-10-13 06:42:36 +00003826 writeOperand(II->getNormalDest(), true);
Dan Gohman81313fd2008-09-14 17:21:12 +00003827 Out << " unwind ";
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003828 writeOperand(II->getUnwindDest(), true);
Victor Hernandez8acf2952009-10-23 21:09:37 +00003829 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003830 Out << ' ';
Reid Kleckner20844032014-01-25 01:24:06 +00003831 if (AI->isUsedWithInAlloca())
David Majnemerc4ab61c2014-03-09 06:41:58 +00003832 Out << "inalloca ";
Manman Ren9bfd0d02016-04-01 21:41:15 +00003833 if (AI->isSwiftError())
3834 Out << "swifterror ";
David Majnemerc4ab61c2014-03-09 06:41:58 +00003835 TypePrinter.print(AI->getAllocatedType(), Out);
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +00003836
3837 // Explicitly write the array size if the code is broken, if it's an array
3838 // allocation, or if the type is not canonical for scalar allocations. The
3839 // latter case prevents the type from mutating when round-tripping through
3840 // assembly.
3841 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3842 !AI->getArraySize()->getType()->isIntegerTy(32)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003843 Out << ", ";
Chris Lattner8d48df22002-04-13 18:34:38 +00003844 writeOperand(AI->getArraySize(), true);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003845 }
Nate Begeman848622f2005-11-05 09:21:28 +00003846 if (AI->getAlignment()) {
Chris Lattner7aeee3a2005-11-05 21:20:34 +00003847 Out << ", align " << AI->getAlignment();
Nate Begeman848622f2005-11-05 09:21:28 +00003848 }
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003849
3850 unsigned AddrSpace = AI->getType()->getAddressSpace();
3851 if (AddrSpace != 0) {
3852 Out << ", addrspace(" << AddrSpace << ')';
3853 }
Chris Lattner862e3382001-10-13 06:42:36 +00003854 } else if (isa<CastInst>(I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003855 if (Operand) {
3856 Out << ' ';
3857 writeOperand(Operand, true); // Work with broken code
3858 }
Misha Brukmana6619a92004-06-21 21:53:56 +00003859 Out << " to ";
Chris Lattnere101c442009-02-28 21:26:53 +00003860 TypePrinter.print(I.getType(), Out);
Chris Lattner5b337482003-10-18 05:57:43 +00003861 } else if (isa<VAArgInst>(I)) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003862 if (Operand) {
3863 Out << ' ';
3864 writeOperand(Operand, true); // Work with broken code
3865 }
Misha Brukmana6619a92004-06-21 21:53:56 +00003866 Out << ", ";
Chris Lattnere101c442009-02-28 21:26:53 +00003867 TypePrinter.print(I.getType(), Out);
3868 } else if (Operand) { // Print the normal way.
David Blaikiea79ac142015-02-27 21:17:42 +00003869 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
David Blaikie79e6c742015-02-27 19:29:02 +00003870 Out << ' ';
3871 TypePrinter.print(GEP->getSourceElementType(), Out);
3872 Out << ',';
David Blaikiea79ac142015-02-27 21:17:42 +00003873 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3874 Out << ' ';
3875 TypePrinter.print(LI->getType(), Out);
Benjamin Kramer257ed692015-03-02 15:24:41 +00003876 Out << ',';
David Blaikie79e6c742015-02-27 19:29:02 +00003877 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003878
Misha Brukmanb1c93172005-04-21 23:48:37 +00003879 // PrintAllTypes - Instructions who have operands of all the same type
Chris Lattner2f7c9632001-06-06 20:29:01 +00003880 // omit the type from all but the first operand. If the instruction has
3881 // different type operands (for example br), then they are all printed.
3882 bool PrintAllTypes = false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003883 Type *TheType = Operand->getType();
Chris Lattner2f7c9632001-06-06 20:29:01 +00003884
Reid Spencer0cdd04f2007-02-02 13:54:55 +00003885 // Select, Store and ShuffleVector always print all types.
Devang Patelce556d92008-03-04 22:05:14 +00003886 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3887 || isa<ReturnInst>(I)) {
Chris Lattnerdeccfaf2003-04-16 20:20:02 +00003888 PrintAllTypes = true;
3889 } else {
3890 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3891 Operand = I.getOperand(i);
Nuno Lopes04fe2f02009-01-15 18:40:57 +00003892 // note that Operand shouldn't be null, but the test helps make dump()
3893 // more tolerant of malformed IR
Nuno Lopes0971e772009-01-14 17:51:41 +00003894 if (Operand && Operand->getType() != TheType) {
Chris Lattnerdeccfaf2003-04-16 20:20:02 +00003895 PrintAllTypes = true; // We have differing types! Print them all!
3896 break;
3897 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003898 }
3899 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003900
Chris Lattner7bfee412001-10-29 16:05:51 +00003901 if (!PrintAllTypes) {
Misha Brukmana6619a92004-06-21 21:53:56 +00003902 Out << ' ';
Chris Lattnere101c442009-02-28 21:26:53 +00003903 TypePrinter.print(TheType, Out);
Chris Lattner7bfee412001-10-29 16:05:51 +00003904 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003905
Dan Gohman81313fd2008-09-14 17:21:12 +00003906 Out << ' ';
Chris Lattner113f4f42002-06-25 16:13:24 +00003907 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
Dan Gohman81313fd2008-09-14 17:21:12 +00003908 if (i) Out << ", ";
Chris Lattner113f4f42002-06-25 16:13:24 +00003909 writeOperand(I.getOperand(i), PrintAllTypes);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003910 }
3911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003912
Eli Friedman59b66882011-08-09 23:02:53 +00003913 // Print atomic ordering/alignment for memory operations
3914 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3915 if (LI->isAtomic())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003916 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
Eli Friedman59b66882011-08-09 23:02:53 +00003917 if (LI->getAlignment())
3918 Out << ", align " << LI->getAlignment();
3919 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3920 if (SI->isAtomic())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003921 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
Eli Friedman59b66882011-08-09 23:02:53 +00003922 if (SI->getAlignment())
3923 Out << ", align " << SI->getAlignment();
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003924 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003925 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3926 CXI->getFailureOrdering(), CXI->getSyncScopeID());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003927 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003928 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3929 RMWI->getSyncScopeID());
Eli Friedmanfee02c62011-07-25 23:16:38 +00003930 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003931 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
Christopher Lamb84485702007-04-22 19:24:39 +00003932 }
Chris Lattner2f7c9632001-06-06 20:29:01 +00003933
Chris Lattnerc9558df2009-12-28 20:10:43 +00003934 // Print Metadata info.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003935 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
Nick Lewyckyba8ec9a2010-02-25 06:53:04 +00003936 I.getAllMetadata(InstMD);
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003937 printMetadataAttachments(InstMD, ", ");
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003938
3939 // Print a nice comment.
Chris Lattner862e3382001-10-13 06:42:36 +00003940 printInfoComment(I);
Chris Lattner2f7c9632001-06-06 20:29:01 +00003941}
3942
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003943void AssemblyWriter::printMetadataAttachments(
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003944 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3945 StringRef Separator) {
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003946 if (MDs.empty())
3947 return;
3948
Duncan P. N. Exon Smithe30f10e2015-04-24 21:03:05 +00003949 if (MDNames.empty())
Mehdi Aminib9b50aa2016-01-07 20:14:30 +00003950 MDs[0].second->getContext().getMDKindNames(MDNames);
Duncan P. N. Exon Smithe30f10e2015-04-24 21:03:05 +00003951
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003952 for (const auto &I : MDs) {
3953 unsigned Kind = I.first;
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003954 Out << Separator;
Filipe Cabecinhas62431b12015-06-02 21:25:08 +00003955 if (Kind < MDNames.size()) {
3956 Out << "!";
3957 printMetadataIdentifier(MDNames[Kind], Out);
3958 } else
Duncan P. N. Exon Smithd3e4c2a2015-04-24 21:06:21 +00003959 Out << "!<unknown kind #" << Kind << ">";
Duncan P. N. Exon Smith86979272015-04-24 20:59:52 +00003960 Out << ' ';
3961 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3962 }
3963}
3964
Daniel Maleaded9f932013-05-08 20:38:31 +00003965void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
Duncan P. N. Exon Smithbe7ea192014-12-15 19:07:53 +00003966 Out << '!' << Slot << " = ";
Daniel Maleaded9f932013-05-08 20:38:31 +00003967 printMDNodeBody(Node);
Duncan P. N. Exon Smith738889f2015-02-25 22:46:38 +00003968 Out << "\n";
Daniel Maleaded9f932013-05-08 20:38:31 +00003969}
3970
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003971void AssemblyWriter::writeAllMDNodes() {
3972 SmallVector<const MDNode *, 16> Nodes;
Chris Lattnercf4a76e2009-12-31 02:20:11 +00003973 Nodes.resize(Machine.mdn_size());
3974 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3975 I != E; ++I)
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003976 Nodes[I->second] = cast<MDNode>(I->first);
Andrew Trickec4b6e72011-09-30 19:48:58 +00003977
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003978 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
Daniel Maleaded9f932013-05-08 20:38:31 +00003979 writeMDNode(i, Nodes[i]);
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003980 }
3981}
3982
3983void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
Dan Gohmana2489d12010-07-20 23:55:01 +00003984 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
Chris Lattnerbddea6a2009-12-31 02:13:35 +00003985}
Chris Lattner2f7c9632001-06-06 20:29:01 +00003986
Bill Wendling829b4782013-02-11 08:43:33 +00003987void AssemblyWriter::writeAllAttributeGroups() {
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003988 std::vector<std::pair<AttributeSet, unsigned>> asVec;
Bill Wendling829b4782013-02-11 08:43:33 +00003989 asVec.resize(Machine.as_size());
3990
3991 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3992 I != E; ++I)
3993 asVec[I->second] = *I;
3994
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00003995 for (const auto &I : asVec)
3996 Out << "attributes #" << I.second << " = { "
Reid Klecknerc2cb5602017-04-12 00:38:00 +00003997 << I.first.getAsString(true) << " }\n";
Bill Wendling829b4782013-02-11 08:43:33 +00003998}
3999
Duncan P. N. Exon Smith0a448fb2014-08-19 21:30:15 +00004000void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4001 bool IsInFunction = Machine.getFunction();
4002 if (IsInFunction)
4003 Out << " ";
4004
4005 Out << "uselistorder";
4006 if (const BasicBlock *BB =
4007 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4008 Out << "_bb ";
4009 writeOperand(BB->getParent(), false);
4010 Out << ", ";
4011 writeOperand(BB, false);
4012 } else {
4013 Out << " ";
4014 writeOperand(Order.V, true);
4015 }
4016 Out << ", { ";
4017
4018 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4019 Out << Order.Shuffle[0];
4020 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4021 Out << ", " << Order.Shuffle[I];
4022 Out << " }\n";
4023}
4024
4025void AssemblyWriter::printUseLists(const Function *F) {
4026 auto hasMore =
4027 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4028 if (!hasMore())
4029 // Nothing to do.
4030 return;
4031
4032 Out << "\n; uselistorder directives\n";
4033 while (hasMore()) {
4034 printUseListOrder(UseListOrders.back());
4035 UseListOrders.pop_back();
4036 }
4037}
4038
Chris Lattner2f7c9632001-06-06 20:29:01 +00004039//===----------------------------------------------------------------------===//
4040// External Interface declarations
4041//===----------------------------------------------------------------------===//
4042
George Burgess IVe1100f52016-02-02 22:46:49 +00004043void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4044 bool ShouldPreserveUseListOrder,
4045 bool IsForDebug) const {
4046 SlotTracker SlotTable(this->getParent());
4047 formatted_raw_ostream OS(ROS);
4048 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4049 IsForDebug,
4050 ShouldPreserveUseListOrder);
4051 W.printFunction(this);
4052}
4053
Duncan P. N. Exon Smithc4f0a322015-04-15 02:12:41 +00004054void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
Justin Bognerd7d1a722015-09-27 22:38:50 +00004055 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
Chris Lattnere36fd8a2008-08-19 04:26:57 +00004056 SlotTracker SlotTable(this);
Dan Gohmane2745262009-08-12 17:23:50 +00004057 formatted_raw_ostream OS(ROS);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004058 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4059 ShouldPreserveUseListOrder);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004060 W.printModule(this);
Chris Lattner2f7c9632001-06-06 20:29:01 +00004061}
4062
Justin Bognerd7d1a722015-09-27 22:38:50 +00004063void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
Dan Gohman2637cc12010-07-21 23:38:33 +00004064 SlotTracker SlotTable(getParent());
4065 formatted_raw_ostream OS(ROS);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004066 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
Dan Gohman2637cc12010-07-21 23:38:33 +00004067 W.printNamedMDNode(this);
4068}
4069
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +00004070void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4071 bool IsForDebug) const {
4072 Optional<SlotTracker> LocalST;
4073 SlotTracker *SlotTable;
4074 if (auto *ST = MST.getMachine())
4075 SlotTable = ST;
4076 else {
4077 LocalST.emplace(getParent());
4078 SlotTable = &*LocalST;
4079 }
4080
4081 formatted_raw_ostream OS(ROS);
4082 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4083 W.printNamedMDNode(this);
4084}
4085
Justin Bognerd7d1a722015-09-27 22:38:50 +00004086void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
David Majnemerdad0a642014-06-27 18:19:56 +00004087 PrintLLVMName(ROS, getName(), ComdatPrefix);
4088 ROS << " = comdat ";
4089
4090 switch (getSelectionKind()) {
4091 case Comdat::Any:
4092 ROS << "any";
4093 break;
4094 case Comdat::ExactMatch:
4095 ROS << "exactmatch";
4096 break;
4097 case Comdat::Largest:
4098 ROS << "largest";
4099 break;
4100 case Comdat::NoDuplicates:
4101 ROS << "noduplicates";
4102 break;
4103 case Comdat::SameSize:
4104 ROS << "samesize";
4105 break;
4106 }
4107
4108 ROS << '\n';
4109}
4110
Quentin Colombet774b1ef2016-03-07 22:32:42 +00004111void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004112 TypePrinting TP;
4113 TP.print(const_cast<Type*>(this), OS);
Andrew Trickec4b6e72011-09-30 19:48:58 +00004114
Quentin Colombet774b1ef2016-03-07 22:32:42 +00004115 if (NoDetails)
4116 return;
4117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004118 // If the type is a named struct type, print the body as well.
4119 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
Chris Lattner01beceb2011-08-12 18:07:07 +00004120 if (!STy->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004121 OS << " = type ";
4122 TP.printStructBody(STy, OS);
4123 }
Chris Lattnerc0b4c7b2002-04-08 22:03:40 +00004124}
4125
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004126static bool isReferencingMDNode(const Instruction &I) {
4127 if (const auto *CI = dyn_cast<CallInst>(&I))
4128 if (Function *F = CI->getCalledFunction())
Justin Lebar9cbc3012016-07-28 23:58:15 +00004129 if (F->isIntrinsic())
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004130 for (auto &Op : I.operands())
4131 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4132 if (isa<MDNode>(V->getMetadata()))
4133 return true;
4134 return false;
4135}
4136
Justin Bognerd7d1a722015-09-27 22:38:50 +00004137void Value::print(raw_ostream &ROS, bool IsForDebug) const {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004138 bool ShouldInitializeAllMetadata = false;
4139 if (auto *I = dyn_cast<Instruction>(this))
4140 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4141 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4142 ShouldInitializeAllMetadata = true;
4143
4144 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004145 print(ROS, MST, IsForDebug);
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004146}
4147
Justin Bognerd7d1a722015-09-27 22:38:50 +00004148void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4149 bool IsForDebug) const {
Dan Gohman12dad632009-08-12 20:56:03 +00004150 formatted_raw_ostream OS(ROS);
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004151 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4152 SlotTracker &SlotTable =
4153 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4154 auto incorporateFunction = [&](const Function *F) {
4155 if (F)
4156 MST.incorporateFunction(*F);
4157 };
4158
Chris Lattner0c19df42008-08-23 22:23:09 +00004159 if (const Instruction *I = dyn_cast<Instruction>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004160 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
Justin Bognerd7d1a722015-09-27 22:38:50 +00004161 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004162 W.printInstruction(*I);
Chris Lattner0c19df42008-08-23 22:23:09 +00004163 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004164 incorporateFunction(BB->getParent());
Justin Bognerd7d1a722015-09-27 22:38:50 +00004165 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004166 W.printBasicBlock(BB);
Chris Lattner0c19df42008-08-23 22:23:09 +00004167 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Justin Bognerd7d1a722015-09-27 22:38:50 +00004168 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
Chris Lattnerefb5e392009-12-31 02:23:35 +00004169 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4170 W.printGlobal(V);
4171 else if (const Function *F = dyn_cast<Function>(GV))
4172 W.printFunction(F);
4173 else
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00004174 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004175 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004176 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
Chris Lattner0c19df42008-08-23 22:23:09 +00004177 } else if (const Constant *C = dyn_cast<Constant>(this)) {
Chris Lattner92c5c122009-02-28 23:20:19 +00004178 TypePrinting TypePrinter;
Chris Lattnere101c442009-02-28 21:26:53 +00004179 TypePrinter.print(C->getType(), OS);
Chris Lattner2ee62d22009-02-28 21:11:05 +00004180 OS << ' ';
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004181 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004182 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004183 this->printAsOperand(OS, /* PrintType */ true, MST);
Chris Lattner0c19df42008-08-23 22:23:09 +00004184 } else {
Nick Lewyckyad1b3d12014-05-09 00:49:03 +00004185 llvm_unreachable("Unknown value to print out!");
Chris Lattner0c19df42008-08-23 22:23:09 +00004186 }
4187}
4188
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004189/// Print without a type, skipping the TypePrinting object.
4190///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004191/// \return \c true iff printing was successful.
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004192static bool printWithoutType(const Value &V, raw_ostream &O,
4193 SlotTracker *Machine, const Module *M) {
4194 if (V.hasName() || isa<GlobalValue>(V) ||
4195 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4196 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4197 return true;
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004198 }
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004199 return false;
4200}
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004201
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004202static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4203 ModuleSlotTracker &MST) {
Roman Tereshind96de6f2018-03-22 21:29:07 +00004204 TypePrinting TypePrinter(MST.getModule());
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004205 if (PrintType) {
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004206 TypePrinter.print(V.getType(), O);
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004207 O << ' ';
4208 }
4209
Duncan P. N. Exon Smith326921542015-06-26 22:04:20 +00004210 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4211 MST.getModule());
4212}
4213
4214void Value::printAsOperand(raw_ostream &O, bool PrintType,
4215 const Module *M) const {
4216 if (!M)
4217 M = getModuleFromVal(this);
4218
4219 if (!PrintType)
4220 if (printWithoutType(*this, O, nullptr, M))
4221 return;
4222
4223 SlotTracker Machine(
4224 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4225 ModuleSlotTracker MST(Machine, M);
4226 printAsOperandImpl(*this, O, PrintType, MST);
4227}
4228
4229void Value::printAsOperand(raw_ostream &O, bool PrintType,
4230 ModuleSlotTracker &MST) const {
4231 if (!PrintType)
4232 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4233 return;
4234
4235 printAsOperandImpl(*this, O, PrintType, MST);
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004236}
4237
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004238static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004239 ModuleSlotTracker &MST, const Module *M,
4240 bool OnlyAsOperand) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004241 formatted_raw_ostream OS(ROS);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004242
Roman Tereshind96de6f2018-03-22 21:29:07 +00004243 TypePrinting TypePrinter(M);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004244
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004245 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004246 /* FromValue */ true);
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004247
4248 auto *N = dyn_cast<MDNode>(&MD);
Reid Klecknerb95b4272017-08-30 20:40:36 +00004249 if (OnlyAsOperand || !N || isa<DIExpression>(MD))
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004250 return;
4251
4252 OS << " = ";
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004253 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004254}
4255
4256void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004257 ModuleSlotTracker MST(M, isa<MDNode>(this));
4258 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4259}
4260
4261void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4262 const Module *M) const {
4263 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004264}
4265
Justin Bognerd7d1a722015-09-27 22:38:50 +00004266void Metadata::print(raw_ostream &OS, const Module *M,
4267 bool /*IsForDebug*/) const {
Duncan P. N. Exon Smith6529ed42015-06-26 22:28:47 +00004268 ModuleSlotTracker MST(M, isa<MDNode>(this));
4269 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004270}
4271
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004272void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
Justin Bognerd7d1a722015-09-27 22:38:50 +00004273 const Module *M, bool /*IsForDebug*/) const {
Duncan P. N. Exon Smith1f8a99a2015-06-27 00:38:26 +00004274 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4275}
4276
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00004277void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4278 SlotTracker SlotTable(this);
4279 formatted_raw_ostream OS(ROS);
4280 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4281 W.printModuleSummaryIndex();
4282}
4283
Aaron Ballman615eb472017-10-15 14:32:27 +00004284#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chris Lattnerdab942552008-08-25 17:03:15 +00004285// Value::dump - allow easy printing of Values from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004286LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004287void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
Reid Spencer52641832004-05-25 18:14:38 +00004288
Chris Lattnerdab942552008-08-25 17:03:15 +00004289// Type::dump - allow easy printing of Types from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004290LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004291void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
Chris Lattner24025262009-02-28 21:05:51 +00004292
Chris Lattnerdab942552008-08-25 17:03:15 +00004293// Module::dump() - Allow printing of Modules from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004294LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004295void Module::dump() const {
4296 print(dbgs(), nullptr,
4297 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4298}
Bill Wendling3681d112011-12-09 23:18:34 +00004299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004300// Allow printing of Comdats from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004301LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004302void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
David Majnemerdad0a642014-06-27 18:19:56 +00004303
Bill Wendling3681d112011-12-09 23:18:34 +00004304// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004305LLVM_DUMP_METHOD
Justin Bognerd7d1a722015-09-27 22:38:50 +00004306void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004307
Duncan P. N. Exon Smith89c1eaa2015-02-25 22:08:21 +00004308LLVM_DUMP_METHOD
Duncan P. N. Exon Smitha66dc8f2015-03-15 06:53:32 +00004309void Metadata::dump() const { dump(nullptr); }
4310
4311LLVM_DUMP_METHOD
Duncan P. N. Exon Smithd6d70e72015-03-14 20:19:36 +00004312void Metadata::dump(const Module *M) const {
Justin Bognerd7d1a722015-09-27 22:38:50 +00004313 print(dbgs(), M, /*IsForDebug=*/true);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004314 dbgs() << '\n';
4315}
Teresa Johnson08d5b4e2018-05-26 02:34:13 +00004316
4317// Allow printing of ModuleSummaryIndex from the debugger.
4318LLVM_DUMP_METHOD
4319void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00004320#endif