Bug Summary

File:lib/Bitcode/Writer/BitcodeWriter.cpp
Warning:line 2949, column 19
Assigned value is garbage or undefined

Annotated Source Code

1//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Bitcode/BitcodeWriter.h"
15#include "ValueEnumerator.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/ADT/Triple.h"
18#include "llvm/Bitcode/BitstreamWriter.h"
19#include "llvm/Bitcode/LLVMBitCodes.h"
20#include "llvm/IR/CallSite.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DebugInfoMetadata.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
29#include "llvm/IR/UseListOrder.h"
30#include "llvm/IR/ValueSymbolTable.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/MathExtras.h"
33#include "llvm/Support/Program.h"
34#include "llvm/Support/SHA1.h"
35#include "llvm/Support/raw_ostream.h"
36#include <cctype>
37#include <map>
38using namespace llvm;
39
40namespace {
41
42cl::opt<unsigned>
43 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
44 cl::desc("Number of metadatas above which we emit an index "
45 "to enable lazy-loading"));
46/// These are manifest constants used by the bitcode writer. They do not need to
47/// be kept in sync with the reader, but need to be consistent within this file.
48enum {
49 // VALUE_SYMTAB_BLOCK abbrev id's.
50 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51 VST_ENTRY_7_ABBREV,
52 VST_ENTRY_6_ABBREV,
53 VST_BBENTRY_6_ABBREV,
54
55 // CONSTANTS_BLOCK abbrev id's.
56 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
57 CONSTANTS_INTEGER_ABBREV,
58 CONSTANTS_CE_CAST_Abbrev,
59 CONSTANTS_NULL_Abbrev,
60
61 // FUNCTION_BLOCK abbrev id's.
62 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
63 FUNCTION_INST_BINOP_ABBREV,
64 FUNCTION_INST_BINOP_FLAGS_ABBREV,
65 FUNCTION_INST_CAST_ABBREV,
66 FUNCTION_INST_RET_VOID_ABBREV,
67 FUNCTION_INST_RET_VAL_ABBREV,
68 FUNCTION_INST_UNREACHABLE_ABBREV,
69 FUNCTION_INST_GEP_ABBREV,
70};
71
72/// Abstract class to manage the bitcode writing, subclassed for each bitcode
73/// file type.
74class BitcodeWriterBase {
75protected:
76 /// The stream created and owned by the client.
77 BitstreamWriter &Stream;
78
79 /// Saves the offset of the VSTOffset record that must eventually be
80 /// backpatched with the offset of the actual VST.
81 uint64_t VSTOffsetPlaceholder = 0;
82
83public:
84 /// Constructs a BitcodeWriterBase object that writes to the provided
85 /// \p Stream.
86 BitcodeWriterBase(BitstreamWriter &Stream) : Stream(Stream) {}
87
88protected:
89 bool hasVSTOffsetPlaceholder() { return VSTOffsetPlaceholder != 0; }
90 void writeValueSymbolTableForwardDecl();
91 void writeBitcodeHeader();
92};
93
94/// Class to manage the bitcode writing for a module.
95class ModuleBitcodeWriter : public BitcodeWriterBase {
96 /// Pointer to the buffer allocated by caller for bitcode writing.
97 const SmallVectorImpl<char> &Buffer;
98
99 /// The Module to write to bitcode.
100 const Module &M;
101
102 /// Enumerates ids for all values in the module.
103 ValueEnumerator VE;
104
105 /// Optional per-module index to write for ThinLTO.
106 const ModuleSummaryIndex *Index;
107
108 /// True if a module hash record should be written.
109 bool GenerateHash;
110
111 /// The start bit of the identification block.
112 uint64_t BitcodeStartBit;
113
114 /// Map that holds the correspondence between GUIDs in the summary index,
115 /// that came from indirect call profiles, and a value id generated by this
116 /// class to use in the VST and summary block records.
117 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
118
119 /// Tracks the last value id recorded in the GUIDToValueMap.
120 unsigned GlobalValueId;
121
122public:
123 /// Constructs a ModuleBitcodeWriter object for the given Module,
124 /// writing to the provided \p Buffer.
125 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
126 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
127 const ModuleSummaryIndex *Index, bool GenerateHash)
128 : BitcodeWriterBase(Stream), Buffer(Buffer), M(*M),
129 VE(*M, ShouldPreserveUseListOrder), Index(Index),
130 GenerateHash(GenerateHash), BitcodeStartBit(Stream.GetCurrentBitNo()) {
131 // Assign ValueIds to any callee values in the index that came from
132 // indirect call profiles and were recorded as a GUID not a Value*
133 // (which would have been assigned an ID by the ValueEnumerator).
134 // The starting ValueId is just after the number of values in the
135 // ValueEnumerator, so that they can be emitted in the VST.
136 GlobalValueId = VE.getValues().size();
137 if (!Index)
138 return;
139 for (const auto &GUIDSummaryLists : *Index)
140 // Examine all summaries for this GUID.
141 for (auto &Summary : GUIDSummaryLists.second)
142 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
143 // For each call in the function summary, see if the call
144 // is to a GUID (which means it is for an indirect call,
145 // otherwise we would have a Value for it). If so, synthesize
146 // a value id.
147 for (auto &CallEdge : FS->calls())
148 if (CallEdge.first.isGUID())
149 assignValueId(CallEdge.first.getGUID());
150 }
151
152 /// Emit the current module to the bitstream.
153 void write();
154
155private:
156 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
157
158 void writeAttributeGroupTable();
159 void writeAttributeTable();
160 void writeTypeTable();
161 void writeComdats();
162 void writeModuleInfo();
163 void writeValueAsMetadata(const ValueAsMetadata *MD,
164 SmallVectorImpl<uint64_t> &Record);
165 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
166 unsigned Abbrev);
167 unsigned createDILocationAbbrev();
168 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
169 unsigned &Abbrev);
170 unsigned createGenericDINodeAbbrev();
171 void writeGenericDINode(const GenericDINode *N,
172 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
173 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
174 unsigned Abbrev);
175 void writeDIEnumerator(const DIEnumerator *N,
176 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
177 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
178 unsigned Abbrev);
179 void writeDIDerivedType(const DIDerivedType *N,
180 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
181 void writeDICompositeType(const DICompositeType *N,
182 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
183 void writeDISubroutineType(const DISubroutineType *N,
184 SmallVectorImpl<uint64_t> &Record,
185 unsigned Abbrev);
186 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
187 unsigned Abbrev);
188 void writeDICompileUnit(const DICompileUnit *N,
189 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
190 void writeDISubprogram(const DISubprogram *N,
191 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
192 void writeDILexicalBlock(const DILexicalBlock *N,
193 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
194 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
195 SmallVectorImpl<uint64_t> &Record,
196 unsigned Abbrev);
197 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
198 unsigned Abbrev);
199 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
200 unsigned Abbrev);
201 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
202 unsigned Abbrev);
203 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
204 unsigned Abbrev);
205 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
206 SmallVectorImpl<uint64_t> &Record,
207 unsigned Abbrev);
208 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
209 SmallVectorImpl<uint64_t> &Record,
210 unsigned Abbrev);
211 void writeDIGlobalVariable(const DIGlobalVariable *N,
212 SmallVectorImpl<uint64_t> &Record,
213 unsigned Abbrev);
214 void writeDILocalVariable(const DILocalVariable *N,
215 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
216 void writeDIExpression(const DIExpression *N,
217 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
218 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
219 SmallVectorImpl<uint64_t> &Record,
220 unsigned Abbrev);
221 void writeDIObjCProperty(const DIObjCProperty *N,
222 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
223 void writeDIImportedEntity(const DIImportedEntity *N,
224 SmallVectorImpl<uint64_t> &Record,
225 unsigned Abbrev);
226 unsigned createNamedMetadataAbbrev();
227 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
228 unsigned createMetadataStringsAbbrev();
229 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
230 SmallVectorImpl<uint64_t> &Record);
231 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
232 SmallVectorImpl<uint64_t> &Record,
233 std::vector<unsigned> *MDAbbrevs = nullptr,
234 std::vector<uint64_t> *IndexPos = nullptr);
235 void writeModuleMetadata();
236 void writeFunctionMetadata(const Function &F);
237 void writeFunctionMetadataAttachment(const Function &F);
238 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
239 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
240 const GlobalObject &GO);
241 void writeModuleMetadataKinds();
242 void writeOperandBundleTags();
243 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
244 void writeModuleConstants();
245 bool pushValueAndType(const Value *V, unsigned InstID,
246 SmallVectorImpl<unsigned> &Vals);
247 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
248 void pushValue(const Value *V, unsigned InstID,
249 SmallVectorImpl<unsigned> &Vals);
250 void pushValueSigned(const Value *V, unsigned InstID,
251 SmallVectorImpl<uint64_t> &Vals);
252 void writeInstruction(const Instruction &I, unsigned InstID,
253 SmallVectorImpl<unsigned> &Vals);
254 void writeValueSymbolTable(
255 const ValueSymbolTable &VST, bool IsModuleLevel = false,
256 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr);
257 void writeUseList(UseListOrder &&Order);
258 void writeUseListBlock(const Function *F);
259 void
260 writeFunction(const Function &F,
261 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
262 void writeBlockInfo();
263 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
264 GlobalValueSummary *Summary,
265 unsigned ValueID,
266 unsigned FSCallsAbbrev,
267 unsigned FSCallsProfileAbbrev,
268 const Function &F);
269 void writeModuleLevelReferences(const GlobalVariable &V,
270 SmallVector<uint64_t, 64> &NameVals,
271 unsigned FSModRefsAbbrev);
272 void writePerModuleGlobalValueSummary();
273 void writeModuleHash(size_t BlockStartPos);
274
275 void assignValueId(GlobalValue::GUID ValGUID) {
276 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
277 }
278 unsigned getValueId(GlobalValue::GUID ValGUID) {
279 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
280 // Expect that any GUID value had a value Id assigned by an
281 // earlier call to assignValueId.
282 assert(VMI != GUIDToValueIdMap.end() &&((VMI != GUIDToValueIdMap.end() && "GUID does not have assigned value Id"
) ? static_cast<void> (0) : __assert_fail ("VMI != GUIDToValueIdMap.end() && \"GUID does not have assigned value Id\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 283, __PRETTY_FUNCTION__))
283 "GUID does not have assigned value Id")((VMI != GUIDToValueIdMap.end() && "GUID does not have assigned value Id"
) ? static_cast<void> (0) : __assert_fail ("VMI != GUIDToValueIdMap.end() && \"GUID does not have assigned value Id\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 283, __PRETTY_FUNCTION__))
;
284 return VMI->second;
285 }
286 // Helper to get the valueId for the type of value recorded in VI.
287 unsigned getValueId(ValueInfo VI) {
288 if (VI.isGUID())
289 return getValueId(VI.getGUID());
290 return VE.getValueID(VI.getValue());
291 }
292 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
293};
294
295/// Class to manage the bitcode writing for a combined index.
296class IndexBitcodeWriter : public BitcodeWriterBase {
297 /// The combined index to write to bitcode.
298 const ModuleSummaryIndex &Index;
299
300 /// When writing a subset of the index for distributed backends, client
301 /// provides a map of modules to the corresponding GUIDs/summaries to write.
302 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
303
304 /// Map that holds the correspondence between the GUID used in the combined
305 /// index and a value id generated by this class to use in references.
306 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
307
308 /// Tracks the last value id recorded in the GUIDToValueMap.
309 unsigned GlobalValueId = 0;
310
311public:
312 /// Constructs a IndexBitcodeWriter object for the given combined index,
313 /// writing to the provided \p Buffer. When writing a subset of the index
314 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
315 IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
316 const std::map<std::string, GVSummaryMapTy>
317 *ModuleToSummariesForIndex = nullptr)
318 : BitcodeWriterBase(Stream), Index(Index),
319 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
320 // Assign unique value ids to all summaries to be written, for use
321 // in writing out the call graph edges. Save the mapping from GUID
322 // to the new global value id to use when writing those edges, which
323 // are currently saved in the index in terms of GUID.
324 for (const auto &I : *this)
325 GUIDToValueIdMap[I.first] = ++GlobalValueId;
326 }
327
328 /// The below iterator returns the GUID and associated summary.
329 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
330
331 /// Iterator over the value GUID and summaries to be written to bitcode,
332 /// hides the details of whether they are being pulled from the entire
333 /// index or just those in a provided ModuleToSummariesForIndex map.
334 class iterator
335 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
336 GVInfo> {
337 /// Enables access to parent class.
338 const IndexBitcodeWriter &Writer;
339
340 // Iterators used when writing only those summaries in a provided
341 // ModuleToSummariesForIndex map:
342
343 /// Points to the last element in outer ModuleToSummariesForIndex map.
344 std::map<std::string, GVSummaryMapTy>::const_iterator ModuleSummariesBack;
345 /// Iterator on outer ModuleToSummariesForIndex map.
346 std::map<std::string, GVSummaryMapTy>::const_iterator ModuleSummariesIter;
347 /// Iterator on an inner global variable summary map.
348 GVSummaryMapTy::const_iterator ModuleGVSummariesIter;
349
350 // Iterators used when writing all summaries in the index:
351
352 /// Points to the last element in the Index outer GlobalValueMap.
353 const_gvsummary_iterator IndexSummariesBack;
354 /// Iterator on outer GlobalValueMap.
355 const_gvsummary_iterator IndexSummariesIter;
356 /// Iterator on an inner GlobalValueSummaryList.
357 GlobalValueSummaryList::const_iterator IndexGVSummariesIter;
358
359 public:
360 /// Construct iterator from parent \p Writer and indicate if we are
361 /// constructing the end iterator.
362 iterator(const IndexBitcodeWriter &Writer, bool IsAtEnd) : Writer(Writer) {
363 // Set up the appropriate set of iterators given whether we are writing
364 // the full index or just a subset.
365 // Can't setup the Back or inner iterators if the corresponding map
366 // is empty. This will be handled specially in operator== as well.
367 if (Writer.ModuleToSummariesForIndex &&
368 !Writer.ModuleToSummariesForIndex->empty()) {
369 for (ModuleSummariesBack = Writer.ModuleToSummariesForIndex->begin();
370 std::next(ModuleSummariesBack) !=
371 Writer.ModuleToSummariesForIndex->end();
372 ModuleSummariesBack++)
373 ;
374 ModuleSummariesIter = !IsAtEnd
375 ? Writer.ModuleToSummariesForIndex->begin()
376 : ModuleSummariesBack;
377 ModuleGVSummariesIter = !IsAtEnd ? ModuleSummariesIter->second.begin()
378 : ModuleSummariesBack->second.end();
379 } else if (!Writer.ModuleToSummariesForIndex &&
380 Writer.Index.begin() != Writer.Index.end()) {
381 for (IndexSummariesBack = Writer.Index.begin();
382 std::next(IndexSummariesBack) != Writer.Index.end();
383 IndexSummariesBack++)
384 ;
385 IndexSummariesIter =
386 !IsAtEnd ? Writer.Index.begin() : IndexSummariesBack;
387 IndexGVSummariesIter = !IsAtEnd ? IndexSummariesIter->second.begin()
388 : IndexSummariesBack->second.end();
389 }
390 }
391
392 /// Increment the appropriate set of iterators.
393 iterator &operator++() {
394 // First the inner iterator is incremented, then if it is at the end
395 // and there are more outer iterations to go, the inner is reset to
396 // the start of the next inner list.
397 if (Writer.ModuleToSummariesForIndex) {
398 ++ModuleGVSummariesIter;
399 if (ModuleGVSummariesIter == ModuleSummariesIter->second.end() &&
400 ModuleSummariesIter != ModuleSummariesBack) {
401 ++ModuleSummariesIter;
402 ModuleGVSummariesIter = ModuleSummariesIter->second.begin();
403 }
404 } else {
405 ++IndexGVSummariesIter;
406 if (IndexGVSummariesIter == IndexSummariesIter->second.end() &&
407 IndexSummariesIter != IndexSummariesBack) {
408 ++IndexSummariesIter;
409 IndexGVSummariesIter = IndexSummariesIter->second.begin();
410 }
411 }
412 return *this;
413 }
414
415 /// Access the <GUID,GlobalValueSummary*> pair corresponding to the current
416 /// outer and inner iterator positions.
417 GVInfo operator*() {
418 if (Writer.ModuleToSummariesForIndex)
419 return std::make_pair(ModuleGVSummariesIter->first,
420 ModuleGVSummariesIter->second);
421 return std::make_pair(IndexSummariesIter->first,
422 IndexGVSummariesIter->get());
423 }
424
425 /// Checks if the iterators are equal, with special handling for empty
426 /// indexes.
427 bool operator==(const iterator &RHS) const {
428 if (Writer.ModuleToSummariesForIndex) {
429 // First ensure that both are writing the same subset.
430 if (Writer.ModuleToSummariesForIndex !=
431 RHS.Writer.ModuleToSummariesForIndex)
432 return false;
433 // Already determined above that maps are the same, so if one is
434 // empty, they both are.
435 if (Writer.ModuleToSummariesForIndex->empty())
436 return true;
437 // Ensure the ModuleGVSummariesIter are iterating over the same
438 // container before checking them below.
439 if (ModuleSummariesIter != RHS.ModuleSummariesIter)
440 return false;
441 return ModuleGVSummariesIter == RHS.ModuleGVSummariesIter;
442 }
443 // First ensure RHS also writing the full index, and that both are
444 // writing the same full index.
445 if (RHS.Writer.ModuleToSummariesForIndex ||
446 &Writer.Index != &RHS.Writer.Index)
447 return false;
448 // Already determined above that maps are the same, so if one is
449 // empty, they both are.
450 if (Writer.Index.begin() == Writer.Index.end())
451 return true;
452 // Ensure the IndexGVSummariesIter are iterating over the same
453 // container before checking them below.
454 if (IndexSummariesIter != RHS.IndexSummariesIter)
455 return false;
456 return IndexGVSummariesIter == RHS.IndexGVSummariesIter;
457 }
458 };
459
460 /// Obtain the start iterator over the summaries to be written.
461 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
462 /// Obtain the end iterator over the summaries to be written.
463 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
464
465 /// Main entry point for writing a combined index to bitcode.
466 void write();
467
468private:
469 void writeIndex();
470 void writeModStrings();
471 void writeCombinedValueSymbolTable();
472 void writeCombinedGlobalValueSummary();
473
474 /// Indicates whether the provided \p ModulePath should be written into
475 /// the module string table, e.g. if full index written or if it is in
476 /// the provided subset.
477 bool doIncludeModule(StringRef ModulePath) {
478 return !ModuleToSummariesForIndex ||
479 ModuleToSummariesForIndex->count(ModulePath);
480 }
481
482 bool hasValueId(GlobalValue::GUID ValGUID) {
483 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
484 return VMI != GUIDToValueIdMap.end();
485 }
486 unsigned getValueId(GlobalValue::GUID ValGUID) {
487 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
488 // If this GUID doesn't have an entry, assign one.
489 if (VMI == GUIDToValueIdMap.end()) {
490 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
491 return GlobalValueId;
492 } else {
493 return VMI->second;
494 }
495 }
496 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
497};
498} // end anonymous namespace
499
500static unsigned getEncodedCastOpcode(unsigned Opcode) {
501 switch (Opcode) {
502 default: llvm_unreachable("Unknown cast instruction!")::llvm::llvm_unreachable_internal("Unknown cast instruction!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 502)
;
503 case Instruction::Trunc : return bitc::CAST_TRUNC;
504 case Instruction::ZExt : return bitc::CAST_ZEXT;
505 case Instruction::SExt : return bitc::CAST_SEXT;
506 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
507 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
508 case Instruction::UIToFP : return bitc::CAST_UITOFP;
509 case Instruction::SIToFP : return bitc::CAST_SITOFP;
510 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
511 case Instruction::FPExt : return bitc::CAST_FPEXT;
512 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
513 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
514 case Instruction::BitCast : return bitc::CAST_BITCAST;
515 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
516 }
517}
518
519static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
520 switch (Opcode) {
521 default: llvm_unreachable("Unknown binary instruction!")::llvm::llvm_unreachable_internal("Unknown binary instruction!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 521)
;
522 case Instruction::Add:
523 case Instruction::FAdd: return bitc::BINOP_ADD;
524 case Instruction::Sub:
525 case Instruction::FSub: return bitc::BINOP_SUB;
526 case Instruction::Mul:
527 case Instruction::FMul: return bitc::BINOP_MUL;
528 case Instruction::UDiv: return bitc::BINOP_UDIV;
529 case Instruction::FDiv:
530 case Instruction::SDiv: return bitc::BINOP_SDIV;
531 case Instruction::URem: return bitc::BINOP_UREM;
532 case Instruction::FRem:
533 case Instruction::SRem: return bitc::BINOP_SREM;
534 case Instruction::Shl: return bitc::BINOP_SHL;
535 case Instruction::LShr: return bitc::BINOP_LSHR;
536 case Instruction::AShr: return bitc::BINOP_ASHR;
537 case Instruction::And: return bitc::BINOP_AND;
538 case Instruction::Or: return bitc::BINOP_OR;
539 case Instruction::Xor: return bitc::BINOP_XOR;
540 }
541}
542
543static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
544 switch (Op) {
545 default: llvm_unreachable("Unknown RMW operation!")::llvm::llvm_unreachable_internal("Unknown RMW operation!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 545)
;
546 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
547 case AtomicRMWInst::Add: return bitc::RMW_ADD;
548 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
549 case AtomicRMWInst::And: return bitc::RMW_AND;
550 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
551 case AtomicRMWInst::Or: return bitc::RMW_OR;
552 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
553 case AtomicRMWInst::Max: return bitc::RMW_MAX;
554 case AtomicRMWInst::Min: return bitc::RMW_MIN;
555 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
556 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
557 }
558}
559
560static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
561 switch (Ordering) {
562 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
563 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
564 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
565 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
566 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
567 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
568 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
569 }
570 llvm_unreachable("Invalid ordering")::llvm::llvm_unreachable_internal("Invalid ordering", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 570)
;
571}
572
573static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
574 switch (SynchScope) {
575 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
576 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
577 }
578 llvm_unreachable("Invalid synch scope")::llvm::llvm_unreachable_internal("Invalid synch scope", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 578)
;
579}
580
581static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
582 StringRef Str, unsigned AbbrevToUse) {
583 SmallVector<unsigned, 64> Vals;
584
585 // Code: [strchar x N]
586 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
587 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
588 AbbrevToUse = 0;
589 Vals.push_back(Str[i]);
590 }
591
592 // Emit the finished record.
593 Stream.EmitRecord(Code, Vals, AbbrevToUse);
594}
595
596static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
597 switch (Kind) {
598 case Attribute::Alignment:
599 return bitc::ATTR_KIND_ALIGNMENT;
600 case Attribute::AllocSize:
601 return bitc::ATTR_KIND_ALLOC_SIZE;
602 case Attribute::AlwaysInline:
603 return bitc::ATTR_KIND_ALWAYS_INLINE;
604 case Attribute::ArgMemOnly:
605 return bitc::ATTR_KIND_ARGMEMONLY;
606 case Attribute::Builtin:
607 return bitc::ATTR_KIND_BUILTIN;
608 case Attribute::ByVal:
609 return bitc::ATTR_KIND_BY_VAL;
610 case Attribute::Convergent:
611 return bitc::ATTR_KIND_CONVERGENT;
612 case Attribute::InAlloca:
613 return bitc::ATTR_KIND_IN_ALLOCA;
614 case Attribute::Cold:
615 return bitc::ATTR_KIND_COLD;
616 case Attribute::InaccessibleMemOnly:
617 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
618 case Attribute::InaccessibleMemOrArgMemOnly:
619 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
620 case Attribute::InlineHint:
621 return bitc::ATTR_KIND_INLINE_HINT;
622 case Attribute::InReg:
623 return bitc::ATTR_KIND_IN_REG;
624 case Attribute::JumpTable:
625 return bitc::ATTR_KIND_JUMP_TABLE;
626 case Attribute::MinSize:
627 return bitc::ATTR_KIND_MIN_SIZE;
628 case Attribute::Naked:
629 return bitc::ATTR_KIND_NAKED;
630 case Attribute::Nest:
631 return bitc::ATTR_KIND_NEST;
632 case Attribute::NoAlias:
633 return bitc::ATTR_KIND_NO_ALIAS;
634 case Attribute::NoBuiltin:
635 return bitc::ATTR_KIND_NO_BUILTIN;
636 case Attribute::NoCapture:
637 return bitc::ATTR_KIND_NO_CAPTURE;
638 case Attribute::NoDuplicate:
639 return bitc::ATTR_KIND_NO_DUPLICATE;
640 case Attribute::NoImplicitFloat:
641 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
642 case Attribute::NoInline:
643 return bitc::ATTR_KIND_NO_INLINE;
644 case Attribute::NoRecurse:
645 return bitc::ATTR_KIND_NO_RECURSE;
646 case Attribute::NonLazyBind:
647 return bitc::ATTR_KIND_NON_LAZY_BIND;
648 case Attribute::NonNull:
649 return bitc::ATTR_KIND_NON_NULL;
650 case Attribute::Dereferenceable:
651 return bitc::ATTR_KIND_DEREFERENCEABLE;
652 case Attribute::DereferenceableOrNull:
653 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
654 case Attribute::NoRedZone:
655 return bitc::ATTR_KIND_NO_RED_ZONE;
656 case Attribute::NoReturn:
657 return bitc::ATTR_KIND_NO_RETURN;
658 case Attribute::NoUnwind:
659 return bitc::ATTR_KIND_NO_UNWIND;
660 case Attribute::OptimizeForSize:
661 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
662 case Attribute::OptimizeNone:
663 return bitc::ATTR_KIND_OPTIMIZE_NONE;
664 case Attribute::ReadNone:
665 return bitc::ATTR_KIND_READ_NONE;
666 case Attribute::ReadOnly:
667 return bitc::ATTR_KIND_READ_ONLY;
668 case Attribute::Returned:
669 return bitc::ATTR_KIND_RETURNED;
670 case Attribute::ReturnsTwice:
671 return bitc::ATTR_KIND_RETURNS_TWICE;
672 case Attribute::SExt:
673 return bitc::ATTR_KIND_S_EXT;
674 case Attribute::StackAlignment:
675 return bitc::ATTR_KIND_STACK_ALIGNMENT;
676 case Attribute::StackProtect:
677 return bitc::ATTR_KIND_STACK_PROTECT;
678 case Attribute::StackProtectReq:
679 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
680 case Attribute::StackProtectStrong:
681 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
682 case Attribute::SafeStack:
683 return bitc::ATTR_KIND_SAFESTACK;
684 case Attribute::StructRet:
685 return bitc::ATTR_KIND_STRUCT_RET;
686 case Attribute::SanitizeAddress:
687 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
688 case Attribute::SanitizeThread:
689 return bitc::ATTR_KIND_SANITIZE_THREAD;
690 case Attribute::SanitizeMemory:
691 return bitc::ATTR_KIND_SANITIZE_MEMORY;
692 case Attribute::SwiftError:
693 return bitc::ATTR_KIND_SWIFT_ERROR;
694 case Attribute::SwiftSelf:
695 return bitc::ATTR_KIND_SWIFT_SELF;
696 case Attribute::UWTable:
697 return bitc::ATTR_KIND_UW_TABLE;
698 case Attribute::WriteOnly:
699 return bitc::ATTR_KIND_WRITEONLY;
700 case Attribute::ZExt:
701 return bitc::ATTR_KIND_Z_EXT;
702 case Attribute::EndAttrKinds:
703 llvm_unreachable("Can not encode end-attribute kinds marker.")::llvm::llvm_unreachable_internal("Can not encode end-attribute kinds marker."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 703)
;
704 case Attribute::None:
705 llvm_unreachable("Can not encode none-attribute.")::llvm::llvm_unreachable_internal("Can not encode none-attribute."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 705)
;
706 }
707
708 llvm_unreachable("Trying to encode unknown attribute")::llvm::llvm_unreachable_internal("Trying to encode unknown attribute"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 708)
;
709}
710
711void ModuleBitcodeWriter::writeAttributeGroupTable() {
712 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
713 if (AttrGrps.empty()) return;
714
715 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
716
717 SmallVector<uint64_t, 64> Record;
718 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
719 AttributeSet AS = AttrGrps[i];
720 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
721 AttributeSet A = AS.getSlotAttributes(i);
722
723 Record.push_back(VE.getAttributeGroupID(A));
724 Record.push_back(AS.getSlotIndex(i));
725
726 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
727 I != E; ++I) {
728 Attribute Attr = *I;
729 if (Attr.isEnumAttribute()) {
730 Record.push_back(0);
731 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
732 } else if (Attr.isIntAttribute()) {
733 Record.push_back(1);
734 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
735 Record.push_back(Attr.getValueAsInt());
736 } else {
737 StringRef Kind = Attr.getKindAsString();
738 StringRef Val = Attr.getValueAsString();
739
740 Record.push_back(Val.empty() ? 3 : 4);
741 Record.append(Kind.begin(), Kind.end());
742 Record.push_back(0);
743 if (!Val.empty()) {
744 Record.append(Val.begin(), Val.end());
745 Record.push_back(0);
746 }
747 }
748 }
749
750 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
751 Record.clear();
752 }
753 }
754
755 Stream.ExitBlock();
756}
757
758void ModuleBitcodeWriter::writeAttributeTable() {
759 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
760 if (Attrs.empty()) return;
761
762 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
763
764 SmallVector<uint64_t, 64> Record;
765 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
766 const AttributeSet &A = Attrs[i];
767 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
768 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
769
770 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
771 Record.clear();
772 }
773
774 Stream.ExitBlock();
775}
776
777/// WriteTypeTable - Write out the type table for a module.
778void ModuleBitcodeWriter::writeTypeTable() {
779 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
780
781 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
782 SmallVector<uint64_t, 64> TypeVals;
783
784 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
785
786 // Abbrev for TYPE_CODE_POINTER.
787 auto Abbv = std::make_shared<BitCodeAbbrev>();
788 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
790 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
791 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
792
793 // Abbrev for TYPE_CODE_FUNCTION.
794 Abbv = std::make_shared<BitCodeAbbrev>();
795 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
799
800 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
801
802 // Abbrev for TYPE_CODE_STRUCT_ANON.
803 Abbv = std::make_shared<BitCodeAbbrev>();
804 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
808
809 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
810
811 // Abbrev for TYPE_CODE_STRUCT_NAME.
812 Abbv = std::make_shared<BitCodeAbbrev>();
813 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
816 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
817
818 // Abbrev for TYPE_CODE_STRUCT_NAMED.
819 Abbv = std::make_shared<BitCodeAbbrev>();
820 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
824
825 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
826
827 // Abbrev for TYPE_CODE_ARRAY.
828 Abbv = std::make_shared<BitCodeAbbrev>();
829 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
832
833 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
834
835 // Emit an entry count so the reader can reserve space.
836 TypeVals.push_back(TypeList.size());
837 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
838 TypeVals.clear();
839
840 // Loop over all of the types, emitting each in turn.
841 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
842 Type *T = TypeList[i];
843 int AbbrevToUse = 0;
844 unsigned Code = 0;
845
846 switch (T->getTypeID()) {
847 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
848 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
849 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
850 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
851 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
852 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
853 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
854 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
855 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
856 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
857 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
858 case Type::IntegerTyID:
859 // INTEGER: [width]
860 Code = bitc::TYPE_CODE_INTEGER;
861 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
862 break;
863 case Type::PointerTyID: {
864 PointerType *PTy = cast<PointerType>(T);
865 // POINTER: [pointee type, address space]
866 Code = bitc::TYPE_CODE_POINTER;
867 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
868 unsigned AddressSpace = PTy->getAddressSpace();
869 TypeVals.push_back(AddressSpace);
870 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
871 break;
872 }
873 case Type::FunctionTyID: {
874 FunctionType *FT = cast<FunctionType>(T);
875 // FUNCTION: [isvararg, retty, paramty x N]
876 Code = bitc::TYPE_CODE_FUNCTION;
877 TypeVals.push_back(FT->isVarArg());
878 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
879 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
880 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
881 AbbrevToUse = FunctionAbbrev;
882 break;
883 }
884 case Type::StructTyID: {
885 StructType *ST = cast<StructType>(T);
886 // STRUCT: [ispacked, eltty x N]
887 TypeVals.push_back(ST->isPacked());
888 // Output all of the element types.
889 for (StructType::element_iterator I = ST->element_begin(),
890 E = ST->element_end(); I != E; ++I)
891 TypeVals.push_back(VE.getTypeID(*I));
892
893 if (ST->isLiteral()) {
894 Code = bitc::TYPE_CODE_STRUCT_ANON;
895 AbbrevToUse = StructAnonAbbrev;
896 } else {
897 if (ST->isOpaque()) {
898 Code = bitc::TYPE_CODE_OPAQUE;
899 } else {
900 Code = bitc::TYPE_CODE_STRUCT_NAMED;
901 AbbrevToUse = StructNamedAbbrev;
902 }
903
904 // Emit the name if it is present.
905 if (!ST->getName().empty())
906 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
907 StructNameAbbrev);
908 }
909 break;
910 }
911 case Type::ArrayTyID: {
912 ArrayType *AT = cast<ArrayType>(T);
913 // ARRAY: [numelts, eltty]
914 Code = bitc::TYPE_CODE_ARRAY;
915 TypeVals.push_back(AT->getNumElements());
916 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
917 AbbrevToUse = ArrayAbbrev;
918 break;
919 }
920 case Type::VectorTyID: {
921 VectorType *VT = cast<VectorType>(T);
922 // VECTOR [numelts, eltty]
923 Code = bitc::TYPE_CODE_VECTOR;
924 TypeVals.push_back(VT->getNumElements());
925 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
926 break;
927 }
928 }
929
930 // Emit the finished record.
931 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
932 TypeVals.clear();
933 }
934
935 Stream.ExitBlock();
936}
937
938static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
939 switch (Linkage) {
940 case GlobalValue::ExternalLinkage:
941 return 0;
942 case GlobalValue::WeakAnyLinkage:
943 return 16;
944 case GlobalValue::AppendingLinkage:
945 return 2;
946 case GlobalValue::InternalLinkage:
947 return 3;
948 case GlobalValue::LinkOnceAnyLinkage:
949 return 18;
950 case GlobalValue::ExternalWeakLinkage:
951 return 7;
952 case GlobalValue::CommonLinkage:
953 return 8;
954 case GlobalValue::PrivateLinkage:
955 return 9;
956 case GlobalValue::WeakODRLinkage:
957 return 17;
958 case GlobalValue::LinkOnceODRLinkage:
959 return 19;
960 case GlobalValue::AvailableExternallyLinkage:
961 return 12;
962 }
963 llvm_unreachable("Invalid linkage")::llvm::llvm_unreachable_internal("Invalid linkage", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 963)
;
964}
965
966static unsigned getEncodedLinkage(const GlobalValue &GV) {
967 return getEncodedLinkage(GV.getLinkage());
968}
969
970// Decode the flags for GlobalValue in the summary
971static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
972 uint64_t RawFlags = 0;
973
974 RawFlags |= Flags.NotEligibleToImport; // bool
975 RawFlags |= (Flags.LiveRoot << 1);
976 // Linkage don't need to be remapped at that time for the summary. Any future
977 // change to the getEncodedLinkage() function will need to be taken into
978 // account here as well.
979 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
980
981 return RawFlags;
982}
983
984static unsigned getEncodedVisibility(const GlobalValue &GV) {
985 switch (GV.getVisibility()) {
986 case GlobalValue::DefaultVisibility: return 0;
987 case GlobalValue::HiddenVisibility: return 1;
988 case GlobalValue::ProtectedVisibility: return 2;
989 }
990 llvm_unreachable("Invalid visibility")::llvm::llvm_unreachable_internal("Invalid visibility", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 990)
;
991}
992
993static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
994 switch (GV.getDLLStorageClass()) {
995 case GlobalValue::DefaultStorageClass: return 0;
996 case GlobalValue::DLLImportStorageClass: return 1;
997 case GlobalValue::DLLExportStorageClass: return 2;
998 }
999 llvm_unreachable("Invalid DLL storage class")::llvm::llvm_unreachable_internal("Invalid DLL storage class"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 999)
;
1000}
1001
1002static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1003 switch (GV.getThreadLocalMode()) {
1004 case GlobalVariable::NotThreadLocal: return 0;
1005 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1006 case GlobalVariable::LocalDynamicTLSModel: return 2;
1007 case GlobalVariable::InitialExecTLSModel: return 3;
1008 case GlobalVariable::LocalExecTLSModel: return 4;
1009 }
1010 llvm_unreachable("Invalid TLS model")::llvm::llvm_unreachable_internal("Invalid TLS model", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1010)
;
1011}
1012
1013static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1014 switch (C.getSelectionKind()) {
1015 case Comdat::Any:
1016 return bitc::COMDAT_SELECTION_KIND_ANY;
1017 case Comdat::ExactMatch:
1018 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1019 case Comdat::Largest:
1020 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1021 case Comdat::NoDuplicates:
1022 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1023 case Comdat::SameSize:
1024 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1025 }
1026 llvm_unreachable("Invalid selection kind")::llvm::llvm_unreachable_internal("Invalid selection kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1026)
;
1027}
1028
1029static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1030 switch (GV.getUnnamedAddr()) {
1031 case GlobalValue::UnnamedAddr::None: return 0;
1032 case GlobalValue::UnnamedAddr::Local: return 2;
1033 case GlobalValue::UnnamedAddr::Global: return 1;
1034 }
1035 llvm_unreachable("Invalid unnamed_addr")::llvm::llvm_unreachable_internal("Invalid unnamed_addr", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1035)
;
1036}
1037
1038void ModuleBitcodeWriter::writeComdats() {
1039 SmallVector<unsigned, 64> Vals;
1040 for (const Comdat *C : VE.getComdats()) {
1041 // COMDAT: [selection_kind, name]
1042 Vals.push_back(getEncodedComdatSelectionKind(*C));
1043 size_t Size = C->getName().size();
1044 assert(isUInt<32>(Size))((isUInt<32>(Size)) ? static_cast<void> (0) : __assert_fail
("isUInt<32>(Size)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1044, __PRETTY_FUNCTION__))
;
1045 Vals.push_back(Size);
1046 for (char Chr : C->getName())
1047 Vals.push_back((unsigned char)Chr);
1048 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1049 Vals.clear();
1050 }
1051}
1052
1053/// Write a record that will eventually hold the word offset of the
1054/// module-level VST. For now the offset is 0, which will be backpatched
1055/// after the real VST is written. Saves the bit offset to backpatch.
1056void BitcodeWriterBase::writeValueSymbolTableForwardDecl() {
1057 // Write a placeholder value in for the offset of the real VST,
1058 // which is written after the function blocks so that it can include
1059 // the offset of each function. The placeholder offset will be
1060 // updated when the real VST is written.
1061 auto Abbv = std::make_shared<BitCodeAbbrev>();
1062 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1063 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1064 // hold the real VST offset. Must use fixed instead of VBR as we don't
1065 // know how many VBR chunks to reserve ahead of time.
1066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1067 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1068
1069 // Emit the placeholder
1070 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1071 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1072
1073 // Compute and save the bit offset to the placeholder, which will be
1074 // patched when the real VST is written. We can simply subtract the 32-bit
1075 // fixed size from the current bit number to get the location to backpatch.
1076 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1077}
1078
1079enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1080
1081/// Determine the encoding to use for the given string name and length.
1082static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
1083 bool isChar6 = true;
1084 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
1085 if (isChar6)
1086 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1087 if ((unsigned char)*C & 128)
1088 // don't bother scanning the rest.
1089 return SE_Fixed8;
1090 }
1091 if (isChar6)
1092 return SE_Char6;
1093 else
1094 return SE_Fixed7;
1095}
1096
1097/// Emit top-level description of module, including target triple, inline asm,
1098/// descriptors for global variables, and function prototype info.
1099/// Returns the bit offset to backpatch with the location of the real VST.
1100void ModuleBitcodeWriter::writeModuleInfo() {
1101 // Emit various pieces of data attached to a module.
1102 if (!M.getTargetTriple().empty())
1103 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1104 0 /*TODO*/);
1105 const std::string &DL = M.getDataLayoutStr();
1106 if (!DL.empty())
1107 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1108 if (!M.getModuleInlineAsm().empty())
1109 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1110 0 /*TODO*/);
1111
1112 // Emit information about sections and GC, computing how many there are. Also
1113 // compute the maximum alignment value.
1114 std::map<std::string, unsigned> SectionMap;
1115 std::map<std::string, unsigned> GCMap;
1116 unsigned MaxAlignment = 0;
1117 unsigned MaxGlobalType = 0;
1118 for (const GlobalValue &GV : M.globals()) {
1119 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
1120 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1121 if (GV.hasSection()) {
1122 // Give section names unique ID's.
1123 unsigned &Entry = SectionMap[GV.getSection()];
1124 if (!Entry) {
1125 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1126 0 /*TODO*/);
1127 Entry = SectionMap.size();
1128 }
1129 }
1130 }
1131 for (const Function &F : M) {
1132 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1133 if (F.hasSection()) {
1134 // Give section names unique ID's.
1135 unsigned &Entry = SectionMap[F.getSection()];
1136 if (!Entry) {
1137 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1138 0 /*TODO*/);
1139 Entry = SectionMap.size();
1140 }
1141 }
1142 if (F.hasGC()) {
1143 // Same for GC names.
1144 unsigned &Entry = GCMap[F.getGC()];
1145 if (!Entry) {
1146 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1147 0 /*TODO*/);
1148 Entry = GCMap.size();
1149 }
1150 }
1151 }
1152
1153 // Emit abbrev for globals, now that we know # sections and max alignment.
1154 unsigned SimpleGVarAbbrev = 0;
1155 if (!M.global_empty()) {
1156 // Add an abbrev for common globals with no visibility or thread localness.
1157 auto Abbv = std::make_shared<BitCodeAbbrev>();
1158 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
1159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1160 Log2_32_Ceil(MaxGlobalType+1)));
1161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1162 //| explicitType << 1
1163 //| constant
1164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1166 if (MaxAlignment == 0) // Alignment.
1167 Abbv->Add(BitCodeAbbrevOp(0));
1168 else {
1169 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
1170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1171 Log2_32_Ceil(MaxEncAlignment+1)));
1172 }
1173 if (SectionMap.empty()) // Section.
1174 Abbv->Add(BitCodeAbbrevOp(0));
1175 else
1176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1177 Log2_32_Ceil(SectionMap.size()+1)));
1178 // Don't bother emitting vis + thread local.
1179 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1180 }
1181
1182 // Emit the global variable information.
1183 SmallVector<unsigned, 64> Vals;
1184 for (const GlobalVariable &GV : M.globals()) {
1185 unsigned AbbrevToUse = 0;
1186
1187 // GLOBALVAR: [type, isconst, initid,
1188 // linkage, alignment, section, visibility, threadlocal,
1189 // unnamed_addr, externally_initialized, dllstorageclass,
1190 // comdat]
1191 Vals.push_back(VE.getTypeID(GV.getValueType()));
1192 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1193 Vals.push_back(GV.isDeclaration() ? 0 :
1194 (VE.getValueID(GV.getInitializer()) + 1));
1195 Vals.push_back(getEncodedLinkage(GV));
1196 Vals.push_back(Log2_32(GV.getAlignment())+1);
1197 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1198 if (GV.isThreadLocal() ||
1199 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1200 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1201 GV.isExternallyInitialized() ||
1202 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1203 GV.hasComdat()) {
1204 Vals.push_back(getEncodedVisibility(GV));
1205 Vals.push_back(getEncodedThreadLocalMode(GV));
1206 Vals.push_back(getEncodedUnnamedAddr(GV));
1207 Vals.push_back(GV.isExternallyInitialized());
1208 Vals.push_back(getEncodedDLLStorageClass(GV));
1209 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1210 } else {
1211 AbbrevToUse = SimpleGVarAbbrev;
1212 }
1213
1214 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1215 Vals.clear();
1216 }
1217
1218 // Emit the function proto information.
1219 for (const Function &F : M) {
1220 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
1221 // section, visibility, gc, unnamed_addr, prologuedata,
1222 // dllstorageclass, comdat, prefixdata, personalityfn]
1223 Vals.push_back(VE.getTypeID(F.getFunctionType()));
1224 Vals.push_back(F.getCallingConv());
1225 Vals.push_back(F.isDeclaration());
1226 Vals.push_back(getEncodedLinkage(F));
1227 Vals.push_back(VE.getAttributeID(F.getAttributes()));
1228 Vals.push_back(Log2_32(F.getAlignment())+1);
1229 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
1230 Vals.push_back(getEncodedVisibility(F));
1231 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1232 Vals.push_back(getEncodedUnnamedAddr(F));
1233 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1234 : 0);
1235 Vals.push_back(getEncodedDLLStorageClass(F));
1236 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1237 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1238 : 0);
1239 Vals.push_back(
1240 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1241
1242 unsigned AbbrevToUse = 0;
1243 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1244 Vals.clear();
1245 }
1246
1247 // Emit the alias information.
1248 for (const GlobalAlias &A : M.aliases()) {
1249 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass,
1250 // threadlocal, unnamed_addr]
1251 Vals.push_back(VE.getTypeID(A.getValueType()));
1252 Vals.push_back(A.getType()->getAddressSpace());
1253 Vals.push_back(VE.getValueID(A.getAliasee()));
1254 Vals.push_back(getEncodedLinkage(A));
1255 Vals.push_back(getEncodedVisibility(A));
1256 Vals.push_back(getEncodedDLLStorageClass(A));
1257 Vals.push_back(getEncodedThreadLocalMode(A));
1258 Vals.push_back(getEncodedUnnamedAddr(A));
1259 unsigned AbbrevToUse = 0;
1260 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1261 Vals.clear();
1262 }
1263
1264 // Emit the ifunc information.
1265 for (const GlobalIFunc &I : M.ifuncs()) {
1266 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
1267 Vals.push_back(VE.getTypeID(I.getValueType()));
1268 Vals.push_back(I.getType()->getAddressSpace());
1269 Vals.push_back(VE.getValueID(I.getResolver()));
1270 Vals.push_back(getEncodedLinkage(I));
1271 Vals.push_back(getEncodedVisibility(I));
1272 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1273 Vals.clear();
1274 }
1275
1276 // Emit the module's source file name.
1277 {
1278 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1279 M.getSourceFileName().size());
1280 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1281 if (Bits == SE_Char6)
1282 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1283 else if (Bits == SE_Fixed7)
1284 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1285
1286 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1287 auto Abbv = std::make_shared<BitCodeAbbrev>();
1288 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1290 Abbv->Add(AbbrevOpToUse);
1291 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1292
1293 for (const auto P : M.getSourceFileName())
1294 Vals.push_back((unsigned char)P);
1295
1296 // Emit the finished record.
1297 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1298 Vals.clear();
1299 }
1300
1301 // If we have a VST, write the VSTOFFSET record placeholder.
1302 if (M.getValueSymbolTable().empty())
1303 return;
1304 writeValueSymbolTableForwardDecl();
1305}
1306
1307static uint64_t getOptimizationFlags(const Value *V) {
1308 uint64_t Flags = 0;
1309
1310 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1311 if (OBO->hasNoSignedWrap())
1312 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1313 if (OBO->hasNoUnsignedWrap())
1314 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1315 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1316 if (PEO->isExact())
1317 Flags |= 1 << bitc::PEO_EXACT;
1318 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1319 if (FPMO->hasUnsafeAlgebra())
1320 Flags |= FastMathFlags::UnsafeAlgebra;
1321 if (FPMO->hasNoNaNs())
1322 Flags |= FastMathFlags::NoNaNs;
1323 if (FPMO->hasNoInfs())
1324 Flags |= FastMathFlags::NoInfs;
1325 if (FPMO->hasNoSignedZeros())
1326 Flags |= FastMathFlags::NoSignedZeros;
1327 if (FPMO->hasAllowReciprocal())
1328 Flags |= FastMathFlags::AllowReciprocal;
1329 }
1330
1331 return Flags;
1332}
1333
1334void ModuleBitcodeWriter::writeValueAsMetadata(
1335 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
1336 // Mimic an MDNode with a value as one operand.
1337 Value *V = MD->getValue();
1338 Record.push_back(VE.getTypeID(V->getType()));
1339 Record.push_back(VE.getValueID(V));
1340 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1341 Record.clear();
1342}
1343
1344void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1345 SmallVectorImpl<uint64_t> &Record,
1346 unsigned Abbrev) {
1347 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1348 Metadata *MD = N->getOperand(i);
1349 assert(!(MD && isa<LocalAsMetadata>(MD)) &&((!(MD && isa<LocalAsMetadata>(MD)) && "Unexpected function-local metadata"
) ? static_cast<void> (0) : __assert_fail ("!(MD && isa<LocalAsMetadata>(MD)) && \"Unexpected function-local metadata\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1350, __PRETTY_FUNCTION__))
1350 "Unexpected function-local metadata")((!(MD && isa<LocalAsMetadata>(MD)) && "Unexpected function-local metadata"
) ? static_cast<void> (0) : __assert_fail ("!(MD && isa<LocalAsMetadata>(MD)) && \"Unexpected function-local metadata\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1350, __PRETTY_FUNCTION__))
;
1351 Record.push_back(VE.getMetadataOrNullID(MD));
1352 }
1353 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1354 : bitc::METADATA_NODE,
1355 Record, Abbrev);
1356 Record.clear();
1357}
1358
1359unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1360 // Assume the column is usually under 128, and always output the inlined-at
1361 // location (it's never more expensive than building an array size 1).
1362 auto Abbv = std::make_shared<BitCodeAbbrev>();
1363 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1369 return Stream.EmitAbbrev(std::move(Abbv));
1370}
1371
1372void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1373 SmallVectorImpl<uint64_t> &Record,
1374 unsigned &Abbrev) {
1375 if (!Abbrev)
1376 Abbrev = createDILocationAbbrev();
1377
1378 Record.push_back(N->isDistinct());
1379 Record.push_back(N->getLine());
1380 Record.push_back(N->getColumn());
1381 Record.push_back(VE.getMetadataID(N->getScope()));
1382 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1383
1384 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1385 Record.clear();
1386}
1387
1388unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1389 // Assume the column is usually under 128, and always output the inlined-at
1390 // location (it's never more expensive than building an array size 1).
1391 auto Abbv = std::make_shared<BitCodeAbbrev>();
1392 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1393 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1394 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1399 return Stream.EmitAbbrev(std::move(Abbv));
1400}
1401
1402void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1403 SmallVectorImpl<uint64_t> &Record,
1404 unsigned &Abbrev) {
1405 if (!Abbrev)
1406 Abbrev = createGenericDINodeAbbrev();
1407
1408 Record.push_back(N->isDistinct());
1409 Record.push_back(N->getTag());
1410 Record.push_back(0); // Per-tag version field; unused for now.
1411
1412 for (auto &I : N->operands())
1413 Record.push_back(VE.getMetadataOrNullID(I));
1414
1415 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1416 Record.clear();
1417}
1418
1419static uint64_t rotateSign(int64_t I) {
1420 uint64_t U = I;
1421 return I < 0 ? ~(U << 1) : U << 1;
1422}
1423
1424void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1425 SmallVectorImpl<uint64_t> &Record,
1426 unsigned Abbrev) {
1427 Record.push_back(N->isDistinct());
1428 Record.push_back(N->getCount());
1429 Record.push_back(rotateSign(N->getLowerBound()));
1430
1431 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1432 Record.clear();
1433}
1434
1435void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1436 SmallVectorImpl<uint64_t> &Record,
1437 unsigned Abbrev) {
1438 Record.push_back(N->isDistinct());
1439 Record.push_back(rotateSign(N->getValue()));
1440 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1441
1442 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1443 Record.clear();
1444}
1445
1446void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1447 SmallVectorImpl<uint64_t> &Record,
1448 unsigned Abbrev) {
1449 Record.push_back(N->isDistinct());
1450 Record.push_back(N->getTag());
1451 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1452 Record.push_back(N->getSizeInBits());
1453 Record.push_back(N->getAlignInBits());
1454 Record.push_back(N->getEncoding());
1455
1456 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1457 Record.clear();
1458}
1459
1460void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1461 SmallVectorImpl<uint64_t> &Record,
1462 unsigned Abbrev) {
1463 Record.push_back(N->isDistinct());
1464 Record.push_back(N->getTag());
1465 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1466 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1467 Record.push_back(N->getLine());
1468 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1469 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1470 Record.push_back(N->getSizeInBits());
1471 Record.push_back(N->getAlignInBits());
1472 Record.push_back(N->getOffsetInBits());
1473 Record.push_back(N->getFlags());
1474 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1475
1476 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1477 // that there is no DWARF address space associated with DIDerivedType.
1478 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1479 Record.push_back(*DWARFAddressSpace + 1);
1480 else
1481 Record.push_back(0);
1482
1483 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1484 Record.clear();
1485}
1486
1487void ModuleBitcodeWriter::writeDICompositeType(
1488 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1489 unsigned Abbrev) {
1490 const unsigned IsNotUsedInOldTypeRef = 0x2;
1491 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1492 Record.push_back(N->getTag());
1493 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1494 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1495 Record.push_back(N->getLine());
1496 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1497 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1498 Record.push_back(N->getSizeInBits());
1499 Record.push_back(N->getAlignInBits());
1500 Record.push_back(N->getOffsetInBits());
1501 Record.push_back(N->getFlags());
1502 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1503 Record.push_back(N->getRuntimeLang());
1504 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1505 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1506 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1507
1508 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1509 Record.clear();
1510}
1511
1512void ModuleBitcodeWriter::writeDISubroutineType(
1513 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1514 unsigned Abbrev) {
1515 const unsigned HasNoOldTypeRefs = 0x2;
1516 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1517 Record.push_back(N->getFlags());
1518 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1519 Record.push_back(N->getCC());
1520
1521 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1522 Record.clear();
1523}
1524
1525void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1526 SmallVectorImpl<uint64_t> &Record,
1527 unsigned Abbrev) {
1528 Record.push_back(N->isDistinct());
1529 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1530 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1531 Record.push_back(N->getChecksumKind());
1532 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1533
1534 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1535 Record.clear();
1536}
1537
1538void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1539 SmallVectorImpl<uint64_t> &Record,
1540 unsigned Abbrev) {
1541 assert(N->isDistinct() && "Expected distinct compile units")((N->isDistinct() && "Expected distinct compile units"
) ? static_cast<void> (0) : __assert_fail ("N->isDistinct() && \"Expected distinct compile units\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1541, __PRETTY_FUNCTION__))
;
1542 Record.push_back(/* IsDistinct */ true);
1543 Record.push_back(N->getSourceLanguage());
1544 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1545 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1546 Record.push_back(N->isOptimized());
1547 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1548 Record.push_back(N->getRuntimeVersion());
1549 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1550 Record.push_back(N->getEmissionKind());
1551 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1552 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1553 Record.push_back(/* subprograms */ 0);
1554 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1555 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1556 Record.push_back(N->getDWOId());
1557 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1558 Record.push_back(N->getSplitDebugInlining());
1559 Record.push_back(N->getDebugInfoForProfiling());
1560
1561 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1562 Record.clear();
1563}
1564
1565void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1566 SmallVectorImpl<uint64_t> &Record,
1567 unsigned Abbrev) {
1568 uint64_t HasUnitFlag = 1 << 1;
1569 Record.push_back(N->isDistinct() | HasUnitFlag);
1570 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1571 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1572 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1573 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1574 Record.push_back(N->getLine());
1575 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1576 Record.push_back(N->isLocalToUnit());
1577 Record.push_back(N->isDefinition());
1578 Record.push_back(N->getScopeLine());
1579 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1580 Record.push_back(N->getVirtuality());
1581 Record.push_back(N->getVirtualIndex());
1582 Record.push_back(N->getFlags());
1583 Record.push_back(N->isOptimized());
1584 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1585 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1586 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1587 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1588 Record.push_back(N->getThisAdjustment());
1589
1590 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1591 Record.clear();
1592}
1593
1594void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1595 SmallVectorImpl<uint64_t> &Record,
1596 unsigned Abbrev) {
1597 Record.push_back(N->isDistinct());
1598 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1599 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1600 Record.push_back(N->getLine());
1601 Record.push_back(N->getColumn());
1602
1603 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1604 Record.clear();
1605}
1606
1607void ModuleBitcodeWriter::writeDILexicalBlockFile(
1608 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1609 unsigned Abbrev) {
1610 Record.push_back(N->isDistinct());
1611 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1612 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1613 Record.push_back(N->getDiscriminator());
1614
1615 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1616 Record.clear();
1617}
1618
1619void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1620 SmallVectorImpl<uint64_t> &Record,
1621 unsigned Abbrev) {
1622 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1623 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1624 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1625 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1626 Record.push_back(N->getLine());
1627
1628 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1629 Record.clear();
1630}
1631
1632void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1633 SmallVectorImpl<uint64_t> &Record,
1634 unsigned Abbrev) {
1635 Record.push_back(N->isDistinct());
1636 Record.push_back(N->getMacinfoType());
1637 Record.push_back(N->getLine());
1638 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1639 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1640
1641 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1642 Record.clear();
1643}
1644
1645void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1646 SmallVectorImpl<uint64_t> &Record,
1647 unsigned Abbrev) {
1648 Record.push_back(N->isDistinct());
1649 Record.push_back(N->getMacinfoType());
1650 Record.push_back(N->getLine());
1651 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1652 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1653
1654 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1655 Record.clear();
1656}
1657
1658void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1659 SmallVectorImpl<uint64_t> &Record,
1660 unsigned Abbrev) {
1661 Record.push_back(N->isDistinct());
1662 for (auto &I : N->operands())
1663 Record.push_back(VE.getMetadataOrNullID(I));
1664
1665 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1666 Record.clear();
1667}
1668
1669void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1670 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1671 unsigned Abbrev) {
1672 Record.push_back(N->isDistinct());
1673 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1674 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1675
1676 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1677 Record.clear();
1678}
1679
1680void ModuleBitcodeWriter::writeDITemplateValueParameter(
1681 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1682 unsigned Abbrev) {
1683 Record.push_back(N->isDistinct());
1684 Record.push_back(N->getTag());
1685 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1686 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1687 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1688
1689 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1690 Record.clear();
1691}
1692
1693void ModuleBitcodeWriter::writeDIGlobalVariable(
1694 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1695 unsigned Abbrev) {
1696 const uint64_t Version = 1 << 1;
1697 Record.push_back((uint64_t)N->isDistinct() | Version);
1698 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1699 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1700 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1701 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1702 Record.push_back(N->getLine());
1703 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1704 Record.push_back(N->isLocalToUnit());
1705 Record.push_back(N->isDefinition());
1706 Record.push_back(/* expr */ 0);
1707 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1708 Record.push_back(N->getAlignInBits());
1709
1710 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1711 Record.clear();
1712}
1713
1714void ModuleBitcodeWriter::writeDILocalVariable(
1715 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1716 unsigned Abbrev) {
1717 // In order to support all possible bitcode formats in BitcodeReader we need
1718 // to distinguish the following cases:
1719 // 1) Record has no artificial tag (Record[1]),
1720 // has no obsolete inlinedAt field (Record[9]).
1721 // In this case Record size will be 8, HasAlignment flag is false.
1722 // 2) Record has artificial tag (Record[1]),
1723 // has no obsolete inlignedAt field (Record[9]).
1724 // In this case Record size will be 9, HasAlignment flag is false.
1725 // 3) Record has both artificial tag (Record[1]) and
1726 // obsolete inlignedAt field (Record[9]).
1727 // In this case Record size will be 10, HasAlignment flag is false.
1728 // 4) Record has neither artificial tag, nor inlignedAt field, but
1729 // HasAlignment flag is true and Record[8] contains alignment value.
1730 const uint64_t HasAlignmentFlag = 1 << 1;
1731 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1732 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1733 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1734 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1735 Record.push_back(N->getLine());
1736 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1737 Record.push_back(N->getArg());
1738 Record.push_back(N->getFlags());
1739 Record.push_back(N->getAlignInBits());
1740
1741 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1742 Record.clear();
1743}
1744
1745void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1746 SmallVectorImpl<uint64_t> &Record,
1747 unsigned Abbrev) {
1748 Record.reserve(N->getElements().size() + 1);
1749
1750 const uint64_t HasOpFragmentFlag = 1 << 1;
1751 Record.push_back((uint64_t)N->isDistinct() | HasOpFragmentFlag);
1752 Record.append(N->elements_begin(), N->elements_end());
1753
1754 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1755 Record.clear();
1756}
1757
1758void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1759 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1760 unsigned Abbrev) {
1761 Record.push_back(N->isDistinct());
1762 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1763 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1764
1765 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1766 Record.clear();
1767}
1768
1769void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1770 SmallVectorImpl<uint64_t> &Record,
1771 unsigned Abbrev) {
1772 Record.push_back(N->isDistinct());
1773 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1774 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1775 Record.push_back(N->getLine());
1776 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1777 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1778 Record.push_back(N->getAttributes());
1779 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1780
1781 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1782 Record.clear();
1783}
1784
1785void ModuleBitcodeWriter::writeDIImportedEntity(
1786 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1787 unsigned Abbrev) {
1788 Record.push_back(N->isDistinct());
1789 Record.push_back(N->getTag());
1790 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1791 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1792 Record.push_back(N->getLine());
1793 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1794
1795 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1796 Record.clear();
1797}
1798
1799unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1800 auto Abbv = std::make_shared<BitCodeAbbrev>();
1801 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1804 return Stream.EmitAbbrev(std::move(Abbv));
1805}
1806
1807void ModuleBitcodeWriter::writeNamedMetadata(
1808 SmallVectorImpl<uint64_t> &Record) {
1809 if (M.named_metadata_empty())
1810 return;
1811
1812 unsigned Abbrev = createNamedMetadataAbbrev();
1813 for (const NamedMDNode &NMD : M.named_metadata()) {
1814 // Write name.
1815 StringRef Str = NMD.getName();
1816 Record.append(Str.bytes_begin(), Str.bytes_end());
1817 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1818 Record.clear();
1819
1820 // Write named metadata operands.
1821 for (const MDNode *N : NMD.operands())
1822 Record.push_back(VE.getMetadataID(N));
1823 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1824 Record.clear();
1825 }
1826}
1827
1828unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1829 auto Abbv = std::make_shared<BitCodeAbbrev>();
1830 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1833 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1834 return Stream.EmitAbbrev(std::move(Abbv));
1835}
1836
1837/// Write out a record for MDString.
1838///
1839/// All the metadata strings in a metadata block are emitted in a single
1840/// record. The sizes and strings themselves are shoved into a blob.
1841void ModuleBitcodeWriter::writeMetadataStrings(
1842 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1843 if (Strings.empty())
1844 return;
1845
1846 // Start the record with the number of strings.
1847 Record.push_back(bitc::METADATA_STRINGS);
1848 Record.push_back(Strings.size());
1849
1850 // Emit the sizes of the strings in the blob.
1851 SmallString<256> Blob;
1852 {
1853 BitstreamWriter W(Blob);
1854 for (const Metadata *MD : Strings)
1855 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1856 W.FlushToWord();
1857 }
1858
1859 // Add the offset to the strings to the record.
1860 Record.push_back(Blob.size());
1861
1862 // Add the strings to the blob.
1863 for (const Metadata *MD : Strings)
1864 Blob.append(cast<MDString>(MD)->getString());
1865
1866 // Emit the final record.
1867 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1868 Record.clear();
1869}
1870
1871// Generates an enum to use as an index in the Abbrev array of Metadata record.
1872enum MetadataAbbrev : unsigned {
1873#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1874#include "llvm/IR/Metadata.def"
1875 LastPlusOne
1876};
1877
1878void ModuleBitcodeWriter::writeMetadataRecords(
1879 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1880 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1881 if (MDs.empty())
1882 return;
1883
1884 // Initialize MDNode abbreviations.
1885#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1886#include "llvm/IR/Metadata.def"
1887
1888 for (const Metadata *MD : MDs) {
1889 if (IndexPos)
1890 IndexPos->push_back(Stream.GetCurrentBitNo());
1891 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1892 assert(N->isResolved() && "Expected forward references to be resolved")((N->isResolved() && "Expected forward references to be resolved"
) ? static_cast<void> (0) : __assert_fail ("N->isResolved() && \"Expected forward references to be resolved\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1892, __PRETTY_FUNCTION__))
;
1893
1894 switch (N->getMetadataID()) {
1895 default:
1896 llvm_unreachable("Invalid MDNode subclass")::llvm::llvm_unreachable_internal("Invalid MDNode subclass", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1896)
;
1897#define HANDLE_MDNODE_LEAF(CLASS) \
1898 case Metadata::CLASS##Kind: \
1899 if (MDAbbrevs) \
1900 write##CLASS(cast<CLASS>(N), Record, \
1901 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1902 else \
1903 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1904 continue;
1905#include "llvm/IR/Metadata.def"
1906 }
1907 }
1908 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1909 }
1910}
1911
1912void ModuleBitcodeWriter::writeModuleMetadata() {
1913 if (!VE.hasMDs() && M.named_metadata_empty())
1914 return;
1915
1916 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1917 SmallVector<uint64_t, 64> Record;
1918
1919 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1920 // block and load any metadata.
1921 std::vector<unsigned> MDAbbrevs;
1922
1923 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1924 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1925 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1926 createGenericDINodeAbbrev();
1927
1928 auto Abbv = std::make_shared<BitCodeAbbrev>();
1929 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1931 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1932 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1933
1934 Abbv = std::make_shared<BitCodeAbbrev>();
1935 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1936 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1937 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1938 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1939
1940 // Emit MDStrings together upfront.
1941 writeMetadataStrings(VE.getMDStrings(), Record);
1942
1943 // We only emit an index for the metadata record if we have more than a given
1944 // (naive) threshold of metadatas, otherwise it is not worth it.
1945 if (VE.getNonMDStrings().size() > IndexThreshold) {
1946 // Write a placeholder value in for the offset of the metadata index,
1947 // which is written after the records, so that it can include
1948 // the offset of each entry. The placeholder offset will be
1949 // updated after all records are emitted.
1950 uint64_t Vals[] = {0, 0};
1951 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1952 }
1953
1954 // Compute and save the bit offset to the current position, which will be
1955 // patched when we emit the index later. We can simply subtract the 64-bit
1956 // fixed size from the current bit number to get the location to backpatch.
1957 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1958
1959 // This index will contain the bitpos for each individual record.
1960 std::vector<uint64_t> IndexPos;
1961 IndexPos.reserve(VE.getNonMDStrings().size());
1962
1963 // Write all the records
1964 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1965
1966 if (VE.getNonMDStrings().size() > IndexThreshold) {
1967 // Now that we have emitted all the records we will emit the index. But
1968 // first
1969 // backpatch the forward reference so that the reader can skip the records
1970 // efficiently.
1971 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1972 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1973
1974 // Delta encode the index.
1975 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1976 for (auto &Elt : IndexPos) {
1977 auto EltDelta = Elt - PreviousValue;
1978 PreviousValue = Elt;
1979 Elt = EltDelta;
1980 }
1981 // Emit the index record.
1982 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1983 IndexPos.clear();
1984 }
1985
1986 // Write the named metadata now.
1987 writeNamedMetadata(Record);
1988
1989 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1990 SmallVector<uint64_t, 4> Record;
1991 Record.push_back(VE.getValueID(&GO));
1992 pushGlobalMetadataAttachment(Record, GO);
1993 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1994 };
1995 for (const Function &F : M)
1996 if (F.isDeclaration() && F.hasMetadata())
1997 AddDeclAttachedMetadata(F);
1998 // FIXME: Only store metadata for declarations here, and move data for global
1999 // variable definitions to a separate block (PR28134).
2000 for (const GlobalVariable &GV : M.globals())
2001 if (GV.hasMetadata())
2002 AddDeclAttachedMetadata(GV);
2003
2004 Stream.ExitBlock();
2005}
2006
2007void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2008 if (!VE.hasMDs())
2009 return;
2010
2011 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2012 SmallVector<uint64_t, 64> Record;
2013 writeMetadataStrings(VE.getMDStrings(), Record);
2014 writeMetadataRecords(VE.getNonMDStrings(), Record);
2015 Stream.ExitBlock();
2016}
2017
2018void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2019 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2020 // [n x [id, mdnode]]
2021 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2022 GO.getAllMetadata(MDs);
2023 for (const auto &I : MDs) {
2024 Record.push_back(I.first);
2025 Record.push_back(VE.getMetadataID(I.second));
2026 }
2027}
2028
2029void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2030 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2031
2032 SmallVector<uint64_t, 64> Record;
2033
2034 if (F.hasMetadata()) {
2035 pushGlobalMetadataAttachment(Record, F);
2036 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2037 Record.clear();
2038 }
2039
2040 // Write metadata attachments
2041 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2042 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2043 for (const BasicBlock &BB : F)
2044 for (const Instruction &I : BB) {
2045 MDs.clear();
2046 I.getAllMetadataOtherThanDebugLoc(MDs);
2047
2048 // If no metadata, ignore instruction.
2049 if (MDs.empty()) continue;
2050
2051 Record.push_back(VE.getInstructionID(&I));
2052
2053 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2054 Record.push_back(MDs[i].first);
2055 Record.push_back(VE.getMetadataID(MDs[i].second));
2056 }
2057 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2058 Record.clear();
2059 }
2060
2061 Stream.ExitBlock();
2062}
2063
2064void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2065 SmallVector<uint64_t, 64> Record;
2066
2067 // Write metadata kinds
2068 // METADATA_KIND - [n x [id, name]]
2069 SmallVector<StringRef, 8> Names;
2070 M.getMDKindNames(Names);
2071
2072 if (Names.empty()) return;
2073
2074 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2075
2076 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2077 Record.push_back(MDKindID);
2078 StringRef KName = Names[MDKindID];
2079 Record.append(KName.begin(), KName.end());
2080
2081 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2082 Record.clear();
2083 }
2084
2085 Stream.ExitBlock();
2086}
2087
2088void ModuleBitcodeWriter::writeOperandBundleTags() {
2089 // Write metadata kinds
2090 //
2091 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2092 //
2093 // OPERAND_BUNDLE_TAG - [strchr x N]
2094
2095 SmallVector<StringRef, 8> Tags;
2096 M.getOperandBundleTags(Tags);
2097
2098 if (Tags.empty())
2099 return;
2100
2101 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2102
2103 SmallVector<uint64_t, 64> Record;
2104
2105 for (auto Tag : Tags) {
2106 Record.append(Tag.begin(), Tag.end());
2107
2108 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2109 Record.clear();
2110 }
2111
2112 Stream.ExitBlock();
2113}
2114
2115static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2116 if ((int64_t)V >= 0)
2117 Vals.push_back(V << 1);
2118 else
2119 Vals.push_back((-V << 1) | 1);
2120}
2121
2122void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2123 bool isGlobal) {
2124 if (FirstVal == LastVal) return;
2125
2126 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2127
2128 unsigned AggregateAbbrev = 0;
2129 unsigned String8Abbrev = 0;
2130 unsigned CString7Abbrev = 0;
2131 unsigned CString6Abbrev = 0;
2132 // If this is a constant pool for the module, emit module-specific abbrevs.
2133 if (isGlobal) {
2134 // Abbrev for CST_CODE_AGGREGATE.
2135 auto Abbv = std::make_shared<BitCodeAbbrev>();
2136 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2139 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2140
2141 // Abbrev for CST_CODE_STRING.
2142 Abbv = std::make_shared<BitCodeAbbrev>();
2143 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2146 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2147 // Abbrev for CST_CODE_CSTRING.
2148 Abbv = std::make_shared<BitCodeAbbrev>();
2149 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2152 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2153 // Abbrev for CST_CODE_CSTRING.
2154 Abbv = std::make_shared<BitCodeAbbrev>();
2155 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2158 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2159 }
2160
2161 SmallVector<uint64_t, 64> Record;
2162
2163 const ValueEnumerator::ValueList &Vals = VE.getValues();
2164 Type *LastTy = nullptr;
2165 for (unsigned i = FirstVal; i != LastVal; ++i) {
2166 const Value *V = Vals[i].first;
2167 // If we need to switch types, do so now.
2168 if (V->getType() != LastTy) {
2169 LastTy = V->getType();
2170 Record.push_back(VE.getTypeID(LastTy));
2171 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2172 CONSTANTS_SETTYPE_ABBREV);
2173 Record.clear();
2174 }
2175
2176 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2177 Record.push_back(unsigned(IA->hasSideEffects()) |
2178 unsigned(IA->isAlignStack()) << 1 |
2179 unsigned(IA->getDialect()&1) << 2);
2180
2181 // Add the asm string.
2182 const std::string &AsmStr = IA->getAsmString();
2183 Record.push_back(AsmStr.size());
2184 Record.append(AsmStr.begin(), AsmStr.end());
2185
2186 // Add the constraint string.
2187 const std::string &ConstraintStr = IA->getConstraintString();
2188 Record.push_back(ConstraintStr.size());
2189 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2190 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2191 Record.clear();
2192 continue;
2193 }
2194 const Constant *C = cast<Constant>(V);
2195 unsigned Code = -1U;
2196 unsigned AbbrevToUse = 0;
2197 if (C->isNullValue()) {
2198 Code = bitc::CST_CODE_NULL;
2199 } else if (isa<UndefValue>(C)) {
2200 Code = bitc::CST_CODE_UNDEF;
2201 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2202 if (IV->getBitWidth() <= 64) {
2203 uint64_t V = IV->getSExtValue();
2204 emitSignedInt64(Record, V);
2205 Code = bitc::CST_CODE_INTEGER;
2206 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2207 } else { // Wide integers, > 64 bits in size.
2208 // We have an arbitrary precision integer value to write whose
2209 // bit width is > 64. However, in canonical unsigned integer
2210 // format it is likely that the high bits are going to be zero.
2211 // So, we only write the number of active words.
2212 unsigned NWords = IV->getValue().getActiveWords();
2213 const uint64_t *RawWords = IV->getValue().getRawData();
2214 for (unsigned i = 0; i != NWords; ++i) {
2215 emitSignedInt64(Record, RawWords[i]);
2216 }
2217 Code = bitc::CST_CODE_WIDE_INTEGER;
2218 }
2219 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2220 Code = bitc::CST_CODE_FLOAT;
2221 Type *Ty = CFP->getType();
2222 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2223 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2224 } else if (Ty->isX86_FP80Ty()) {
2225 // api needed to prevent premature destruction
2226 // bits are not in the same order as a normal i80 APInt, compensate.
2227 APInt api = CFP->getValueAPF().bitcastToAPInt();
2228 const uint64_t *p = api.getRawData();
2229 Record.push_back((p[1] << 48) | (p[0] >> 16));
2230 Record.push_back(p[0] & 0xffffLL);
2231 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2232 APInt api = CFP->getValueAPF().bitcastToAPInt();
2233 const uint64_t *p = api.getRawData();
2234 Record.push_back(p[0]);
2235 Record.push_back(p[1]);
2236 } else {
2237 assert (0 && "Unknown FP type!")((0 && "Unknown FP type!") ? static_cast<void> (
0) : __assert_fail ("0 && \"Unknown FP type!\"", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2237, __PRETTY_FUNCTION__))
;
2238 }
2239 } else if (isa<ConstantDataSequential>(C) &&
2240 cast<ConstantDataSequential>(C)->isString()) {
2241 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2242 // Emit constant strings specially.
2243 unsigned NumElts = Str->getNumElements();
2244 // If this is a null-terminated string, use the denser CSTRING encoding.
2245 if (Str->isCString()) {
2246 Code = bitc::CST_CODE_CSTRING;
2247 --NumElts; // Don't encode the null, which isn't allowed by char6.
2248 } else {
2249 Code = bitc::CST_CODE_STRING;
2250 AbbrevToUse = String8Abbrev;
2251 }
2252 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2253 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2254 for (unsigned i = 0; i != NumElts; ++i) {
2255 unsigned char V = Str->getElementAsInteger(i);
2256 Record.push_back(V);
2257 isCStr7 &= (V & 128) == 0;
2258 if (isCStrChar6)
2259 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2260 }
2261
2262 if (isCStrChar6)
2263 AbbrevToUse = CString6Abbrev;
2264 else if (isCStr7)
2265 AbbrevToUse = CString7Abbrev;
2266 } else if (const ConstantDataSequential *CDS =
2267 dyn_cast<ConstantDataSequential>(C)) {
2268 Code = bitc::CST_CODE_DATA;
2269 Type *EltTy = CDS->getType()->getElementType();
2270 if (isa<IntegerType>(EltTy)) {
2271 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2272 Record.push_back(CDS->getElementAsInteger(i));
2273 } else {
2274 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2275 Record.push_back(
2276 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2277 }
2278 } else if (isa<ConstantAggregate>(C)) {
2279 Code = bitc::CST_CODE_AGGREGATE;
2280 for (const Value *Op : C->operands())
2281 Record.push_back(VE.getValueID(Op));
2282 AbbrevToUse = AggregateAbbrev;
2283 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2284 switch (CE->getOpcode()) {
2285 default:
2286 if (Instruction::isCast(CE->getOpcode())) {
2287 Code = bitc::CST_CODE_CE_CAST;
2288 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2289 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2290 Record.push_back(VE.getValueID(C->getOperand(0)));
2291 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2292 } else {
2293 assert(CE->getNumOperands() == 2 && "Unknown constant expr!")((CE->getNumOperands() == 2 && "Unknown constant expr!"
) ? static_cast<void> (0) : __assert_fail ("CE->getNumOperands() == 2 && \"Unknown constant expr!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2293, __PRETTY_FUNCTION__))
;
2294 Code = bitc::CST_CODE_CE_BINOP;
2295 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2296 Record.push_back(VE.getValueID(C->getOperand(0)));
2297 Record.push_back(VE.getValueID(C->getOperand(1)));
2298 uint64_t Flags = getOptimizationFlags(CE);
2299 if (Flags != 0)
2300 Record.push_back(Flags);
2301 }
2302 break;
2303 case Instruction::GetElementPtr: {
2304 Code = bitc::CST_CODE_CE_GEP;
2305 const auto *GO = cast<GEPOperator>(C);
2306 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2307 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2308 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2309 Record.push_back((*Idx << 1) | GO->isInBounds());
2310 } else if (GO->isInBounds())
2311 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2312 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2313 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2314 Record.push_back(VE.getValueID(C->getOperand(i)));
2315 }
2316 break;
2317 }
2318 case Instruction::Select:
2319 Code = bitc::CST_CODE_CE_SELECT;
2320 Record.push_back(VE.getValueID(C->getOperand(0)));
2321 Record.push_back(VE.getValueID(C->getOperand(1)));
2322 Record.push_back(VE.getValueID(C->getOperand(2)));
2323 break;
2324 case Instruction::ExtractElement:
2325 Code = bitc::CST_CODE_CE_EXTRACTELT;
2326 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2327 Record.push_back(VE.getValueID(C->getOperand(0)));
2328 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2329 Record.push_back(VE.getValueID(C->getOperand(1)));
2330 break;
2331 case Instruction::InsertElement:
2332 Code = bitc::CST_CODE_CE_INSERTELT;
2333 Record.push_back(VE.getValueID(C->getOperand(0)));
2334 Record.push_back(VE.getValueID(C->getOperand(1)));
2335 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2336 Record.push_back(VE.getValueID(C->getOperand(2)));
2337 break;
2338 case Instruction::ShuffleVector:
2339 // If the return type and argument types are the same, this is a
2340 // standard shufflevector instruction. If the types are different,
2341 // then the shuffle is widening or truncating the input vectors, and
2342 // the argument type must also be encoded.
2343 if (C->getType() == C->getOperand(0)->getType()) {
2344 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2345 } else {
2346 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2347 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2348 }
2349 Record.push_back(VE.getValueID(C->getOperand(0)));
2350 Record.push_back(VE.getValueID(C->getOperand(1)));
2351 Record.push_back(VE.getValueID(C->getOperand(2)));
2352 break;
2353 case Instruction::ICmp:
2354 case Instruction::FCmp:
2355 Code = bitc::CST_CODE_CE_CMP;
2356 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2357 Record.push_back(VE.getValueID(C->getOperand(0)));
2358 Record.push_back(VE.getValueID(C->getOperand(1)));
2359 Record.push_back(CE->getPredicate());
2360 break;
2361 }
2362 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2363 Code = bitc::CST_CODE_BLOCKADDRESS;
2364 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2365 Record.push_back(VE.getValueID(BA->getFunction()));
2366 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2367 } else {
2368#ifndef NDEBUG
2369 C->dump();
2370#endif
2371 llvm_unreachable("Unknown constant!")::llvm::llvm_unreachable_internal("Unknown constant!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2371)
;
2372 }
2373 Stream.EmitRecord(Code, Record, AbbrevToUse);
2374 Record.clear();
2375 }
2376
2377 Stream.ExitBlock();
2378}
2379
2380void ModuleBitcodeWriter::writeModuleConstants() {
2381 const ValueEnumerator::ValueList &Vals = VE.getValues();
2382
2383 // Find the first constant to emit, which is the first non-globalvalue value.
2384 // We know globalvalues have been emitted by WriteModuleInfo.
2385 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2386 if (!isa<GlobalValue>(Vals[i].first)) {
2387 writeConstants(i, Vals.size(), true);
2388 return;
2389 }
2390 }
2391}
2392
2393/// pushValueAndType - The file has to encode both the value and type id for
2394/// many values, because we need to know what type to create for forward
2395/// references. However, most operands are not forward references, so this type
2396/// field is not needed.
2397///
2398/// This function adds V's value ID to Vals. If the value ID is higher than the
2399/// instruction ID, then it is a forward reference, and it also includes the
2400/// type ID. The value ID that is written is encoded relative to the InstID.
2401bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2402 SmallVectorImpl<unsigned> &Vals) {
2403 unsigned ValID = VE.getValueID(V);
2404 // Make encoding relative to the InstID.
2405 Vals.push_back(InstID - ValID);
2406 if (ValID >= InstID) {
2407 Vals.push_back(VE.getTypeID(V->getType()));
2408 return true;
2409 }
2410 return false;
2411}
2412
2413void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2414 unsigned InstID) {
2415 SmallVector<unsigned, 64> Record;
2416 LLVMContext &C = CS.getInstruction()->getContext();
2417
2418 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2419 const auto &Bundle = CS.getOperandBundleAt(i);
2420 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2421
2422 for (auto &Input : Bundle.Inputs)
2423 pushValueAndType(Input, InstID, Record);
2424
2425 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2426 Record.clear();
2427 }
2428}
2429
2430/// pushValue - Like pushValueAndType, but where the type of the value is
2431/// omitted (perhaps it was already encoded in an earlier operand).
2432void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2433 SmallVectorImpl<unsigned> &Vals) {
2434 unsigned ValID = VE.getValueID(V);
2435 Vals.push_back(InstID - ValID);
2436}
2437
2438void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2439 SmallVectorImpl<uint64_t> &Vals) {
2440 unsigned ValID = VE.getValueID(V);
2441 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2442 emitSignedInt64(Vals, diff);
2443}
2444
2445/// WriteInstruction - Emit an instruction to the specified stream.
2446void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2447 unsigned InstID,
2448 SmallVectorImpl<unsigned> &Vals) {
2449 unsigned Code = 0;
2450 unsigned AbbrevToUse = 0;
2451 VE.setInstructionID(&I);
2452 switch (I.getOpcode()) {
2453 default:
2454 if (Instruction::isCast(I.getOpcode())) {
2455 Code = bitc::FUNC_CODE_INST_CAST;
2456 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2457 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2458 Vals.push_back(VE.getTypeID(I.getType()));
2459 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2460 } else {
2461 assert(isa<BinaryOperator>(I) && "Unknown instruction!")((isa<BinaryOperator>(I) && "Unknown instruction!"
) ? static_cast<void> (0) : __assert_fail ("isa<BinaryOperator>(I) && \"Unknown instruction!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2461, __PRETTY_FUNCTION__))
;
2462 Code = bitc::FUNC_CODE_INST_BINOP;
2463 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2464 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2465 pushValue(I.getOperand(1), InstID, Vals);
2466 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2467 uint64_t Flags = getOptimizationFlags(&I);
2468 if (Flags != 0) {
2469 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2470 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2471 Vals.push_back(Flags);
2472 }
2473 }
2474 break;
2475
2476 case Instruction::GetElementPtr: {
2477 Code = bitc::FUNC_CODE_INST_GEP;
2478 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2479 auto &GEPInst = cast<GetElementPtrInst>(I);
2480 Vals.push_back(GEPInst.isInBounds());
2481 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2482 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2483 pushValueAndType(I.getOperand(i), InstID, Vals);
2484 break;
2485 }
2486 case Instruction::ExtractValue: {
2487 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2488 pushValueAndType(I.getOperand(0), InstID, Vals);
2489 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2490 Vals.append(EVI->idx_begin(), EVI->idx_end());
2491 break;
2492 }
2493 case Instruction::InsertValue: {
2494 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2495 pushValueAndType(I.getOperand(0), InstID, Vals);
2496 pushValueAndType(I.getOperand(1), InstID, Vals);
2497 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2498 Vals.append(IVI->idx_begin(), IVI->idx_end());
2499 break;
2500 }
2501 case Instruction::Select:
2502 Code = bitc::FUNC_CODE_INST_VSELECT;
2503 pushValueAndType(I.getOperand(1), InstID, Vals);
2504 pushValue(I.getOperand(2), InstID, Vals);
2505 pushValueAndType(I.getOperand(0), InstID, Vals);
2506 break;
2507 case Instruction::ExtractElement:
2508 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2509 pushValueAndType(I.getOperand(0), InstID, Vals);
2510 pushValueAndType(I.getOperand(1), InstID, Vals);
2511 break;
2512 case Instruction::InsertElement:
2513 Code = bitc::FUNC_CODE_INST_INSERTELT;
2514 pushValueAndType(I.getOperand(0), InstID, Vals);
2515 pushValue(I.getOperand(1), InstID, Vals);
2516 pushValueAndType(I.getOperand(2), InstID, Vals);
2517 break;
2518 case Instruction::ShuffleVector:
2519 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2520 pushValueAndType(I.getOperand(0), InstID, Vals);
2521 pushValue(I.getOperand(1), InstID, Vals);
2522 pushValue(I.getOperand(2), InstID, Vals);
2523 break;
2524 case Instruction::ICmp:
2525 case Instruction::FCmp: {
2526 // compare returning Int1Ty or vector of Int1Ty
2527 Code = bitc::FUNC_CODE_INST_CMP2;
2528 pushValueAndType(I.getOperand(0), InstID, Vals);
2529 pushValue(I.getOperand(1), InstID, Vals);
2530 Vals.push_back(cast<CmpInst>(I).getPredicate());
2531 uint64_t Flags = getOptimizationFlags(&I);
2532 if (Flags != 0)
2533 Vals.push_back(Flags);
2534 break;
2535 }
2536
2537 case Instruction::Ret:
2538 {
2539 Code = bitc::FUNC_CODE_INST_RET;
2540 unsigned NumOperands = I.getNumOperands();
2541 if (NumOperands == 0)
2542 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2543 else if (NumOperands == 1) {
2544 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2545 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2546 } else {
2547 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2548 pushValueAndType(I.getOperand(i), InstID, Vals);
2549 }
2550 }
2551 break;
2552 case Instruction::Br:
2553 {
2554 Code = bitc::FUNC_CODE_INST_BR;
2555 const BranchInst &II = cast<BranchInst>(I);
2556 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2557 if (II.isConditional()) {
2558 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2559 pushValue(II.getCondition(), InstID, Vals);
2560 }
2561 }
2562 break;
2563 case Instruction::Switch:
2564 {
2565 Code = bitc::FUNC_CODE_INST_SWITCH;
2566 const SwitchInst &SI = cast<SwitchInst>(I);
2567 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2568 pushValue(SI.getCondition(), InstID, Vals);
2569 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2570 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2571 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2572 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2573 }
2574 }
2575 break;
2576 case Instruction::IndirectBr:
2577 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2578 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2579 // Encode the address operand as relative, but not the basic blocks.
2580 pushValue(I.getOperand(0), InstID, Vals);
2581 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2582 Vals.push_back(VE.getValueID(I.getOperand(i)));
2583 break;
2584
2585 case Instruction::Invoke: {
2586 const InvokeInst *II = cast<InvokeInst>(&I);
2587 const Value *Callee = II->getCalledValue();
2588 FunctionType *FTy = II->getFunctionType();
2589
2590 if (II->hasOperandBundles())
2591 writeOperandBundles(II, InstID);
2592
2593 Code = bitc::FUNC_CODE_INST_INVOKE;
2594
2595 Vals.push_back(VE.getAttributeID(II->getAttributes()));
2596 Vals.push_back(II->getCallingConv() | 1 << 13);
2597 Vals.push_back(VE.getValueID(II->getNormalDest()));
2598 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2599 Vals.push_back(VE.getTypeID(FTy));
2600 pushValueAndType(Callee, InstID, Vals);
2601
2602 // Emit value #'s for the fixed parameters.
2603 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2604 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2605
2606 // Emit type/value pairs for varargs params.
2607 if (FTy->isVarArg()) {
2608 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2609 i != e; ++i)
2610 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2611 }
2612 break;
2613 }
2614 case Instruction::Resume:
2615 Code = bitc::FUNC_CODE_INST_RESUME;
2616 pushValueAndType(I.getOperand(0), InstID, Vals);
2617 break;
2618 case Instruction::CleanupRet: {
2619 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2620 const auto &CRI = cast<CleanupReturnInst>(I);
2621 pushValue(CRI.getCleanupPad(), InstID, Vals);
2622 if (CRI.hasUnwindDest())
2623 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2624 break;
2625 }
2626 case Instruction::CatchRet: {
2627 Code = bitc::FUNC_CODE_INST_CATCHRET;
2628 const auto &CRI = cast<CatchReturnInst>(I);
2629 pushValue(CRI.getCatchPad(), InstID, Vals);
2630 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2631 break;
2632 }
2633 case Instruction::CleanupPad:
2634 case Instruction::CatchPad: {
2635 const auto &FuncletPad = cast<FuncletPadInst>(I);
2636 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2637 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2638 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2639
2640 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2641 Vals.push_back(NumArgOperands);
2642 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2643 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2644 break;
2645 }
2646 case Instruction::CatchSwitch: {
2647 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2648 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2649
2650 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2651
2652 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2653 Vals.push_back(NumHandlers);
2654 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2655 Vals.push_back(VE.getValueID(CatchPadBB));
2656
2657 if (CatchSwitch.hasUnwindDest())
2658 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2659 break;
2660 }
2661 case Instruction::Unreachable:
2662 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2663 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2664 break;
2665
2666 case Instruction::PHI: {
2667 const PHINode &PN = cast<PHINode>(I);
2668 Code = bitc::FUNC_CODE_INST_PHI;
2669 // With the newer instruction encoding, forward references could give
2670 // negative valued IDs. This is most common for PHIs, so we use
2671 // signed VBRs.
2672 SmallVector<uint64_t, 128> Vals64;
2673 Vals64.push_back(VE.getTypeID(PN.getType()));
2674 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2675 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2676 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2677 }
2678 // Emit a Vals64 vector and exit.
2679 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2680 Vals64.clear();
2681 return;
2682 }
2683
2684 case Instruction::LandingPad: {
2685 const LandingPadInst &LP = cast<LandingPadInst>(I);
2686 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2687 Vals.push_back(VE.getTypeID(LP.getType()));
2688 Vals.push_back(LP.isCleanup());
2689 Vals.push_back(LP.getNumClauses());
2690 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2691 if (LP.isCatch(I))
2692 Vals.push_back(LandingPadInst::Catch);
2693 else
2694 Vals.push_back(LandingPadInst::Filter);
2695 pushValueAndType(LP.getClause(I), InstID, Vals);
2696 }
2697 break;
2698 }
2699
2700 case Instruction::Alloca: {
2701 Code = bitc::FUNC_CODE_INST_ALLOCA;
2702 const AllocaInst &AI = cast<AllocaInst>(I);
2703 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2704 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2705 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2706 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2707 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&((Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
"not enough bits for maximum alignment") ? static_cast<void
> (0) : __assert_fail ("Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 && \"not enough bits for maximum alignment\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2708, __PRETTY_FUNCTION__))
2708 "not enough bits for maximum alignment")((Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
"not enough bits for maximum alignment") ? static_cast<void
> (0) : __assert_fail ("Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 && \"not enough bits for maximum alignment\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2708, __PRETTY_FUNCTION__))
;
2709 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64")((AlignRecord < 1 << 5 && "alignment greater than 1 << 64"
) ? static_cast<void> (0) : __assert_fail ("AlignRecord < 1 << 5 && \"alignment greater than 1 << 64\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2709, __PRETTY_FUNCTION__))
;
2710 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2711 AlignRecord |= 1 << 6;
2712 AlignRecord |= AI.isSwiftError() << 7;
2713 Vals.push_back(AlignRecord);
2714 break;
2715 }
2716
2717 case Instruction::Load:
2718 if (cast<LoadInst>(I).isAtomic()) {
2719 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2720 pushValueAndType(I.getOperand(0), InstID, Vals);
2721 } else {
2722 Code = bitc::FUNC_CODE_INST_LOAD;
2723 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2724 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2725 }
2726 Vals.push_back(VE.getTypeID(I.getType()));
2727 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2728 Vals.push_back(cast<LoadInst>(I).isVolatile());
2729 if (cast<LoadInst>(I).isAtomic()) {
2730 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2731 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2732 }
2733 break;
2734 case Instruction::Store:
2735 if (cast<StoreInst>(I).isAtomic())
2736 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2737 else
2738 Code = bitc::FUNC_CODE_INST_STORE;
2739 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2740 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2741 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2742 Vals.push_back(cast<StoreInst>(I).isVolatile());
2743 if (cast<StoreInst>(I).isAtomic()) {
2744 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2745 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2746 }
2747 break;
2748 case Instruction::AtomicCmpXchg:
2749 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2750 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2751 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2752 pushValue(I.getOperand(2), InstID, Vals); // newval.
2753 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2754 Vals.push_back(
2755 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2756 Vals.push_back(
2757 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2758 Vals.push_back(
2759 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2760 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2761 break;
2762 case Instruction::AtomicRMW:
2763 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2764 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2765 pushValue(I.getOperand(1), InstID, Vals); // val.
2766 Vals.push_back(
2767 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2768 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2769 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2770 Vals.push_back(
2771 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2772 break;
2773 case Instruction::Fence:
2774 Code = bitc::FUNC_CODE_INST_FENCE;
2775 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2776 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2777 break;
2778 case Instruction::Call: {
2779 const CallInst &CI = cast<CallInst>(I);
2780 FunctionType *FTy = CI.getFunctionType();
2781
2782 if (CI.hasOperandBundles())
2783 writeOperandBundles(&CI, InstID);
2784
2785 Code = bitc::FUNC_CODE_INST_CALL;
2786
2787 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2788
2789 unsigned Flags = getOptimizationFlags(&I);
2790 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2791 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2792 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2793 1 << bitc::CALL_EXPLICIT_TYPE |
2794 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2795 unsigned(Flags != 0) << bitc::CALL_FMF);
2796 if (Flags != 0)
2797 Vals.push_back(Flags);
2798
2799 Vals.push_back(VE.getTypeID(FTy));
2800 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2801
2802 // Emit value #'s for the fixed parameters.
2803 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2804 // Check for labels (can happen with asm labels).
2805 if (FTy->getParamType(i)->isLabelTy())
2806 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2807 else
2808 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2809 }
2810
2811 // Emit type/value pairs for varargs params.
2812 if (FTy->isVarArg()) {
2813 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2814 i != e; ++i)
2815 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2816 }
2817 break;
2818 }
2819 case Instruction::VAArg:
2820 Code = bitc::FUNC_CODE_INST_VAARG;
2821 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2822 pushValue(I.getOperand(0), InstID, Vals); // valist.
2823 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2824 break;
2825 }
2826
2827 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2828 Vals.clear();
2829}
2830
2831/// Emit names for globals/functions etc. \p IsModuleLevel is true when
2832/// we are writing the module-level VST, where we are including a function
2833/// bitcode index and need to backpatch the VST forward declaration record.
2834void ModuleBitcodeWriter::writeValueSymbolTable(
2835 const ValueSymbolTable &VST, bool IsModuleLevel,
2836 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
2837 if (VST.empty()) {
1
Assuming the condition is false
2
Taking false branch
2838 // writeValueSymbolTableForwardDecl should have returned early as
2839 // well. Ensure this handling remains in sync by asserting that
2840 // the placeholder offset is not set.
2841 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder())((!IsModuleLevel || !hasVSTOffsetPlaceholder()) ? static_cast
<void> (0) : __assert_fail ("!IsModuleLevel || !hasVSTOffsetPlaceholder()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2841, __PRETTY_FUNCTION__))
;
2842 return;
2843 }
2844
2845 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
3
Assuming 'IsModuleLevel' is 0
2846 // Get the offset of the VST we are writing, and backpatch it into
2847 // the VST forward declaration record.
2848 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2849 // The BitcodeStartBit was the stream offset of the identification block.
2850 VSTOffset -= bitcodeStartBit();
2851 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned")(((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"
) ? static_cast<void> (0) : __assert_fail ("(VSTOffset & 31) == 0 && \"VST block not 32-bit aligned\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2851, __PRETTY_FUNCTION__))
;
2852 // Note that we add 1 here because the offset is relative to one word
2853 // before the start of the identification block, which was historically
2854 // always the start of the regular bitcode header.
2855 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2856 }
2857
2858 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2859
2860 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2861 // records, which are not used in the per-function VSTs.
2862 unsigned FnEntry8BitAbbrev;
4
'FnEntry8BitAbbrev' declared without an initial value
2863 unsigned FnEntry7BitAbbrev;
2864 unsigned FnEntry6BitAbbrev;
2865 unsigned GUIDEntryAbbrev;
2866 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2867 // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2868 auto Abbv = std::make_shared<BitCodeAbbrev>();
2869 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2870 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2871 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2872 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2873 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2874 FnEntry8BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2875
2876 // 7-bit fixed width VST_CODE_FNENTRY function strings.
2877 Abbv = std::make_shared<BitCodeAbbrev>();
2878 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2879 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2880 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2883 FnEntry7BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2884
2885 // 6-bit char6 VST_CODE_FNENTRY function strings.
2886 Abbv = std::make_shared<BitCodeAbbrev>();
2887 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2888 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2889 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2890 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2892 FnEntry6BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2893
2894 // FIXME: Change the name of this record as it is now used by
2895 // the per-module index as well.
2896 Abbv = std::make_shared<BitCodeAbbrev>();
2897 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2898 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2899 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2900 GUIDEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2901 }
2902
2903 // FIXME: Set up the abbrev, we know how many values there are!
2904 // FIXME: We know if the type names can use 7-bit ascii.
2905 SmallVector<uint64_t, 64> NameVals;
2906
2907 for (const ValueName &Name : VST) {
2908 // Figure out the encoding to use for the name.
2909 StringEncoding Bits =
2910 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2911
2912 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2913 NameVals.push_back(VE.getValueID(Name.getValue()));
2914
2915 Function *F = dyn_cast<Function>(Name.getValue());
2916 if (!F) {
5
Taking true branch
12
Taking true branch
19
Taking true branch
24
Assuming 'F' is non-null
25
Taking false branch
2917 // If value is an alias, need to get the aliased base object to
2918 // see if it is a function.
2919 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2920 if (GA && GA->getBaseObject())
2921 F = dyn_cast<Function>(GA->getBaseObject());
2922 }
2923
2924 // VST_CODE_ENTRY: [valueid, namechar x N]
2925 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2926 // VST_CODE_BBENTRY: [bbid, namechar x N]
2927 unsigned Code;
2928 if (isa<BasicBlock>(Name.getValue())) {
6
Taking false branch
13
Taking false branch
20
Taking true branch
26
Taking false branch
2929 Code = bitc::VST_CODE_BBENTRY;
2930 if (Bits == SE_Char6)
21
Assuming 'Bits' is not equal to SE_Char6
22
Taking false branch
2931 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2932 } else if (F && !F->isDeclaration()) {
27
Assuming the condition is true
28
Taking true branch
2933 // Must be the module-level VST, where we pass in the Index and
2934 // have a VSTOffsetPlaceholder. The function-level VST should not
2935 // contain any Function symbols.
2936 assert(FunctionToBitcodeIndex)((FunctionToBitcodeIndex) ? static_cast<void> (0) : __assert_fail
("FunctionToBitcodeIndex", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2936, __PRETTY_FUNCTION__))
;
2937 assert(hasVSTOffsetPlaceholder())((hasVSTOffsetPlaceholder()) ? static_cast<void> (0) : __assert_fail
("hasVSTOffsetPlaceholder()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2937, __PRETTY_FUNCTION__))
;
2938
2939 // Save the word offset of the function (from the start of the
2940 // actual bitcode written to the stream).
2941 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
2942 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned")(((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned"
) ? static_cast<void> (0) : __assert_fail ("(BitcodeIndex & 31) == 0 && \"function block not 32-bit aligned\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2942, __PRETTY_FUNCTION__))
;
2943 // Note that we add 1 here because the offset is relative to one word
2944 // before the start of the identification block, which was historically
2945 // always the start of the regular bitcode header.
2946 NameVals.push_back(BitcodeIndex / 32 + 1);
2947
2948 Code = bitc::VST_CODE_FNENTRY;
2949 AbbrevToUse = FnEntry8BitAbbrev;
29
Assigned value is garbage or undefined
2950 if (Bits == SE_Char6)
2951 AbbrevToUse = FnEntry6BitAbbrev;
2952 else if (Bits == SE_Fixed7)
2953 AbbrevToUse = FnEntry7BitAbbrev;
2954 } else {
2955 Code = bitc::VST_CODE_ENTRY;
2956 if (Bits == SE_Char6)
7
Assuming 'Bits' is not equal to SE_Char6
8
Taking false branch
14
Assuming 'Bits' is not equal to SE_Char6
15
Taking false branch
2957 AbbrevToUse = VST_ENTRY_6_ABBREV;
2958 else if (Bits == SE_Fixed7)
9
Assuming 'Bits' is not equal to SE_Fixed7
10
Taking false branch
16
Assuming 'Bits' is not equal to SE_Fixed7
17
Taking false branch
2959 AbbrevToUse = VST_ENTRY_7_ABBREV;
2960 }
2961
2962 for (const auto P : Name.getKey())
11
Assuming '__begin' is equal to '__end'
18
Assuming '__begin' is equal to '__end'
23
Assuming '__begin' is equal to '__end'
2963 NameVals.push_back((unsigned char)P);
2964
2965 // Emit the finished record.
2966 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2967 NameVals.clear();
2968 }
2969 // Emit any GUID valueIDs created for indirect call edges into the
2970 // module-level VST.
2971 if (IsModuleLevel && hasVSTOffsetPlaceholder())
2972 for (const auto &GI : valueIds()) {
2973 NameVals.push_back(GI.second);
2974 NameVals.push_back(GI.first);
2975 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals,
2976 GUIDEntryAbbrev);
2977 NameVals.clear();
2978 }
2979 Stream.ExitBlock();
2980}
2981
2982/// Emit function names and summary offsets for the combined index
2983/// used by ThinLTO.
2984void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2985 assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder")((hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder"
) ? static_cast<void> (0) : __assert_fail ("hasVSTOffsetPlaceholder() && \"Expected non-zero VSTOffsetPlaceholder\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2985, __PRETTY_FUNCTION__))
;
2986 // Get the offset of the VST we are writing, and backpatch it into
2987 // the VST forward declaration record.
2988 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2989 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned")(((VSTOffset & 31) == 0 && "VST block not 32-bit aligned"
) ? static_cast<void> (0) : __assert_fail ("(VSTOffset & 31) == 0 && \"VST block not 32-bit aligned\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2989, __PRETTY_FUNCTION__))
;
2990 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2991
2992 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2993
2994 auto Abbv = std::make_shared<BitCodeAbbrev>();
2995 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2997 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2998 unsigned EntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2999
3000 SmallVector<uint64_t, 64> NameVals;
3001 for (const auto &GVI : valueIds()) {
3002 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
3003 NameVals.push_back(GVI.second);
3004 NameVals.push_back(GVI.first);
3005
3006 // Emit the finished record.
3007 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
3008 NameVals.clear();
3009 }
3010 Stream.ExitBlock();
3011}
3012
3013void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3014 assert(Order.Shuffle.size() >= 2 && "Shuffle too small")((Order.Shuffle.size() >= 2 && "Shuffle too small"
) ? static_cast<void> (0) : __assert_fail ("Order.Shuffle.size() >= 2 && \"Shuffle too small\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3014, __PRETTY_FUNCTION__))
;
3015 unsigned Code;
3016 if (isa<BasicBlock>(Order.V))
3017 Code = bitc::USELIST_CODE_BB;
3018 else
3019 Code = bitc::USELIST_CODE_DEFAULT;
3020
3021 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3022 Record.push_back(VE.getValueID(Order.V));
3023 Stream.EmitRecord(Code, Record);
3024}
3025
3026void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3027 assert(VE.shouldPreserveUseListOrder() &&((VE.shouldPreserveUseListOrder() && "Expected to be preserving use-list order"
) ? static_cast<void> (0) : __assert_fail ("VE.shouldPreserveUseListOrder() && \"Expected to be preserving use-list order\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3028, __PRETTY_FUNCTION__))
3028 "Expected to be preserving use-list order")((VE.shouldPreserveUseListOrder() && "Expected to be preserving use-list order"
) ? static_cast<void> (0) : __assert_fail ("VE.shouldPreserveUseListOrder() && \"Expected to be preserving use-list order\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3028, __PRETTY_FUNCTION__))
;
3029
3030 auto hasMore = [&]() {
3031 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3032 };
3033 if (!hasMore())
3034 // Nothing to do.
3035 return;
3036
3037 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3038 while (hasMore()) {
3039 writeUseList(std::move(VE.UseListOrders.back()));
3040 VE.UseListOrders.pop_back();
3041 }
3042 Stream.ExitBlock();
3043}
3044
3045/// Emit a function body to the module stream.
3046void ModuleBitcodeWriter::writeFunction(
3047 const Function &F,
3048 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3049 // Save the bitcode index of the start of this function block for recording
3050 // in the VST.
3051 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3052
3053 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3054 VE.incorporateFunction(F);
3055
3056 SmallVector<unsigned, 64> Vals;
3057
3058 // Emit the number of basic blocks, so the reader can create them ahead of
3059 // time.
3060 Vals.push_back(VE.getBasicBlocks().size());
3061 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3062 Vals.clear();
3063
3064 // If there are function-local constants, emit them now.
3065 unsigned CstStart, CstEnd;
3066 VE.getFunctionConstantRange(CstStart, CstEnd);
3067 writeConstants(CstStart, CstEnd, false);
3068
3069 // If there is function-local metadata, emit it now.
3070 writeFunctionMetadata(F);
3071
3072 // Keep a running idea of what the instruction ID is.
3073 unsigned InstID = CstEnd;
3074
3075 bool NeedsMetadataAttachment = F.hasMetadata();
3076
3077 DILocation *LastDL = nullptr;
3078 // Finally, emit all the instructions, in order.
3079 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3080 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3081 I != E; ++I) {
3082 writeInstruction(*I, InstID, Vals);
3083
3084 if (!I->getType()->isVoidTy())
3085 ++InstID;
3086
3087 // If the instruction has metadata, write a metadata attachment later.
3088 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3089
3090 // If the instruction has a debug location, emit it.
3091 DILocation *DL = I->getDebugLoc();
3092 if (!DL)
3093 continue;
3094
3095 if (DL == LastDL) {
3096 // Just repeat the same debug loc as last time.
3097 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3098 continue;
3099 }
3100
3101 Vals.push_back(DL->getLine());
3102 Vals.push_back(DL->getColumn());
3103 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3104 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3105 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3106 Vals.clear();
3107
3108 LastDL = DL;
3109 }
3110
3111 // Emit names for all the instructions etc.
3112 if (auto *Symtab = F.getValueSymbolTable())
3113 writeValueSymbolTable(*Symtab);
3114
3115 if (NeedsMetadataAttachment)
3116 writeFunctionMetadataAttachment(F);
3117 if (VE.shouldPreserveUseListOrder())
3118 writeUseListBlock(&F);
3119 VE.purgeFunction();
3120 Stream.ExitBlock();
3121}
3122
3123// Emit blockinfo, which defines the standard abbreviations etc.
3124void ModuleBitcodeWriter::writeBlockInfo() {
3125 // We only want to emit block info records for blocks that have multiple
3126 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3127 // Other blocks can define their abbrevs inline.
3128 Stream.EnterBlockInfoBlock();
3129
3130 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3131 auto Abbv = std::make_shared<BitCodeAbbrev>();
3132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3133 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3136 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3137 VST_ENTRY_8_ABBREV)
3138 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3138)
;
3139 }
3140
3141 { // 7-bit fixed width VST_CODE_ENTRY strings.
3142 auto Abbv = std::make_shared<BitCodeAbbrev>();
3143 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3147 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3148 VST_ENTRY_7_ABBREV)
3149 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3149)
;
3150 }
3151 { // 6-bit char6 VST_CODE_ENTRY strings.
3152 auto Abbv = std::make_shared<BitCodeAbbrev>();
3153 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3157 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3158 VST_ENTRY_6_ABBREV)
3159 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3159)
;
3160 }
3161 { // 6-bit char6 VST_CODE_BBENTRY strings.
3162 auto Abbv = std::make_shared<BitCodeAbbrev>();
3163 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3167 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3168 VST_BBENTRY_6_ABBREV)
3169 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3169)
;
3170 }
3171
3172
3173
3174 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3175 auto Abbv = std::make_shared<BitCodeAbbrev>();
3176 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3178 VE.computeBitsRequiredForTypeIndicies()));
3179 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3180 CONSTANTS_SETTYPE_ABBREV)
3181 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3181)
;
3182 }
3183
3184 { // INTEGER abbrev for CONSTANTS_BLOCK.
3185 auto Abbv = std::make_shared<BitCodeAbbrev>();
3186 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3188 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3189 CONSTANTS_INTEGER_ABBREV)
3190 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3190)
;
3191 }
3192
3193 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3194 auto Abbv = std::make_shared<BitCodeAbbrev>();
3195 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3196 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3197 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3198 VE.computeBitsRequiredForTypeIndicies()));
3199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3200
3201 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3202 CONSTANTS_CE_CAST_Abbrev)
3203 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3203)
;
3204 }
3205 { // NULL abbrev for CONSTANTS_BLOCK.
3206 auto Abbv = std::make_shared<BitCodeAbbrev>();
3207 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3208 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3209 CONSTANTS_NULL_Abbrev)
3210 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3210)
;
3211 }
3212
3213 // FIXME: This should only use space for first class types!
3214
3215 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3216 auto Abbv = std::make_shared<BitCodeAbbrev>();
3217 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3220 VE.computeBitsRequiredForTypeIndicies()));
3221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3223 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3224 FUNCTION_INST_LOAD_ABBREV)
3225 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3225)
;
3226 }
3227 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3228 auto Abbv = std::make_shared<BitCodeAbbrev>();
3229 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3233 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3234 FUNCTION_INST_BINOP_ABBREV)
3235 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3235)
;
3236 }
3237 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3238 auto Abbv = std::make_shared<BitCodeAbbrev>();
3239 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3240 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3244 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3245 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3246 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3246)
;
3247 }
3248 { // INST_CAST abbrev for FUNCTION_BLOCK.
3249 auto Abbv = std::make_shared<BitCodeAbbrev>();
3250 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3253 VE.computeBitsRequiredForTypeIndicies()));
3254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3255 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3256 FUNCTION_INST_CAST_ABBREV)
3257 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3257)
;
3258 }
3259
3260 { // INST_RET abbrev for FUNCTION_BLOCK.
3261 auto Abbv = std::make_shared<BitCodeAbbrev>();
3262 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3263 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3264 FUNCTION_INST_RET_VOID_ABBREV)
3265 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3265)
;
3266 }
3267 { // INST_RET abbrev for FUNCTION_BLOCK.
3268 auto Abbv = std::make_shared<BitCodeAbbrev>();
3269 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3271 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3272 FUNCTION_INST_RET_VAL_ABBREV)
3273 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3273)
;
3274 }
3275 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3276 auto Abbv = std::make_shared<BitCodeAbbrev>();
3277 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3278 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3279 FUNCTION_INST_UNREACHABLE_ABBREV)
3280 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3280)
;
3281 }
3282 {
3283 auto Abbv = std::make_shared<BitCodeAbbrev>();
3284 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3287 Log2_32_Ceil(VE.getTypes().size() + 1)));
3288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3290 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3291 FUNCTION_INST_GEP_ABBREV)
3292 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3292)
;
3293 }
3294
3295 Stream.ExitBlock();
3296}
3297
3298/// Write the module path strings, currently only used when generating
3299/// a combined index file.
3300void IndexBitcodeWriter::writeModStrings() {
3301 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3302
3303 // TODO: See which abbrev sizes we actually need to emit
3304
3305 // 8-bit fixed-width MST_ENTRY strings.
3306 auto Abbv = std::make_shared<BitCodeAbbrev>();
3307 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3311 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3312
3313 // 7-bit fixed width MST_ENTRY strings.
3314 Abbv = std::make_shared<BitCodeAbbrev>();
3315 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3319 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3320
3321 // 6-bit char6 MST_ENTRY strings.
3322 Abbv = std::make_shared<BitCodeAbbrev>();
3323 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3327 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3328
3329 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3330 Abbv = std::make_shared<BitCodeAbbrev>();
3331 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3337 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3338
3339 SmallVector<unsigned, 64> Vals;
3340 for (const auto &MPSE : Index.modulePaths()) {
3341 if (!doIncludeModule(MPSE.getKey()))
3342 continue;
3343 StringEncoding Bits =
3344 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3345 unsigned AbbrevToUse = Abbrev8Bit;
3346 if (Bits == SE_Char6)
3347 AbbrevToUse = Abbrev6Bit;
3348 else if (Bits == SE_Fixed7)
3349 AbbrevToUse = Abbrev7Bit;
3350
3351 Vals.push_back(MPSE.getValue().first);
3352
3353 for (const auto P : MPSE.getKey())
3354 Vals.push_back((unsigned char)P);
3355
3356 // Emit the finished record.
3357 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3358
3359 Vals.clear();
3360 // Emit an optional hash for the module now
3361 auto &Hash = MPSE.getValue().second;
3362 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3363 for (auto Val : Hash) {
3364 if (Val)
3365 AllZero = false;
3366 Vals.push_back(Val);
3367 }
3368 if (!AllZero) {
3369 // Emit the hash record.
3370 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3371 }
3372
3373 Vals.clear();
3374 }
3375 Stream.ExitBlock();
3376}
3377
3378/// Write the function type metadata related records that need to appear before
3379/// a function summary entry (whether per-module or combined).
3380static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3381 FunctionSummary *FS) {
3382 if (!FS->type_tests().empty())
3383 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3384
3385 SmallVector<uint64_t, 64> Record;
3386
3387 auto WriteVFuncIdVec = [&](uint64_t Ty,
3388 ArrayRef<FunctionSummary::VFuncId> VFs) {
3389 if (VFs.empty())
3390 return;
3391 Record.clear();
3392 for (auto &VF : VFs) {
3393 Record.push_back(VF.GUID);
3394 Record.push_back(VF.Offset);
3395 }
3396 Stream.EmitRecord(Ty, Record);
3397 };
3398
3399 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3400 FS->type_test_assume_vcalls());
3401 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3402 FS->type_checked_load_vcalls());
3403
3404 auto WriteConstVCallVec = [&](uint64_t Ty,
3405 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3406 for (auto &VC : VCs) {
3407 Record.clear();
3408 Record.push_back(VC.VFunc.GUID);
3409 Record.push_back(VC.VFunc.Offset);
3410 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3411 Stream.EmitRecord(Ty, Record);
3412 }
3413 };
3414
3415 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3416 FS->type_test_assume_const_vcalls());
3417 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3418 FS->type_checked_load_const_vcalls());
3419}
3420
3421// Helper to emit a single function summary record.
3422void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3423 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3424 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3425 const Function &F) {
3426 NameVals.push_back(ValueID);
3427
3428 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3429 writeFunctionTypeMetadataRecords(Stream, FS);
3430
3431 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3432 NameVals.push_back(FS->instCount());
3433 NameVals.push_back(FS->refs().size());
3434
3435 for (auto &RI : FS->refs())
3436 NameVals.push_back(VE.getValueID(RI.getValue()));
3437
3438 bool HasProfileData = F.getEntryCount().hasValue();
3439 for (auto &ECI : FS->calls()) {
3440 NameVals.push_back(getValueId(ECI.first));
3441 if (HasProfileData)
3442 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3443 }
3444
3445 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3446 unsigned Code =
3447 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3448
3449 // Emit the finished record.
3450 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3451 NameVals.clear();
3452}
3453
3454// Collect the global value references in the given variable's initializer,
3455// and emit them in a summary record.
3456void ModuleBitcodeWriter::writeModuleLevelReferences(
3457 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3458 unsigned FSModRefsAbbrev) {
3459 auto Summaries =
3460 Index->findGlobalValueSummaryList(GlobalValue::getGUID(V.getName()));
3461 if (Summaries == Index->end()) {
3462 // Only declarations should not have a summary (a declaration might however
3463 // have a summary if the def was in module level asm).
3464 assert(V.isDeclaration())((V.isDeclaration()) ? static_cast<void> (0) : __assert_fail
("V.isDeclaration()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3464, __PRETTY_FUNCTION__))
;
3465 return;
3466 }
3467 auto *Summary = Summaries->second.front().get();
3468 NameVals.push_back(VE.getValueID(&V));
3469 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3470 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3471
3472 unsigned SizeBeforeRefs = NameVals.size();
3473 for (auto &RI : VS->refs())
3474 NameVals.push_back(VE.getValueID(RI.getValue()));
3475 // Sort the refs for determinism output, the vector returned by FS->refs() has
3476 // been initialized from a DenseSet.
3477 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3478
3479 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3480 FSModRefsAbbrev);
3481 NameVals.clear();
3482}
3483
3484// Current version for the summary.
3485// This is bumped whenever we introduce changes in the way some record are
3486// interpreted, like flags for instance.
3487static const uint64_t INDEX_VERSION = 3;
3488
3489/// Emit the per-module summary section alongside the rest of
3490/// the module's bitcode.
3491void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3492 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
3493
3494 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3495
3496 if (Index->begin() == Index->end()) {
3497 Stream.ExitBlock();
3498 return;
3499 }
3500
3501 // Abbrev for FS_PERMODULE.
3502 auto Abbv = std::make_shared<BitCodeAbbrev>();
3503 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3504 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3505 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3506 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3507 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3508 // numrefs x valueid, n x (valueid)
3509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3511 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3512
3513 // Abbrev for FS_PERMODULE_PROFILE.
3514 Abbv = std::make_shared<BitCodeAbbrev>();
3515 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3516 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3517 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3518 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3519 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3520 // numrefs x valueid, n x (valueid, hotness)
3521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3523 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3524
3525 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3526 Abbv = std::make_shared<BitCodeAbbrev>();
3527 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3528 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3529 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3530 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3531 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3532 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3533
3534 // Abbrev for FS_ALIAS.
3535 Abbv = std::make_shared<BitCodeAbbrev>();
3536 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3538 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3539 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3540 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3541
3542 SmallVector<uint64_t, 64> NameVals;
3543 // Iterate over the list of functions instead of the Index to
3544 // ensure the ordering is stable.
3545 for (const Function &F : M) {
3546 // Summary emission does not support anonymous functions, they have to
3547 // renamed using the anonymous function renaming pass.
3548 if (!F.hasName())
3549 report_fatal_error("Unexpected anonymous function when writing summary");
3550
3551 auto Summaries =
3552 Index->findGlobalValueSummaryList(GlobalValue::getGUID(F.getName()));
3553 if (Summaries == Index->end()) {
3554 // Only declarations should not have a summary (a declaration might
3555 // however have a summary if the def was in module level asm).
3556 assert(F.isDeclaration())((F.isDeclaration()) ? static_cast<void> (0) : __assert_fail
("F.isDeclaration()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3556, __PRETTY_FUNCTION__))
;
3557 continue;
3558 }
3559 auto *Summary = Summaries->second.front().get();
3560 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3561 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3562 }
3563
3564 // Capture references from GlobalVariable initializers, which are outside
3565 // of a function scope.
3566 for (const GlobalVariable &G : M.globals())
3567 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3568
3569 for (const GlobalAlias &A : M.aliases()) {
3570 auto *Aliasee = A.getBaseObject();
3571 if (!Aliasee->hasName())
3572 // Nameless function don't have an entry in the summary, skip it.
3573 continue;
3574 auto AliasId = VE.getValueID(&A);
3575 auto AliaseeId = VE.getValueID(Aliasee);
3576 NameVals.push_back(AliasId);
3577 auto *Summary = Index->getGlobalValueSummary(A);
3578 AliasSummary *AS = cast<AliasSummary>(Summary);
3579 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3580 NameVals.push_back(AliaseeId);
3581 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3582 NameVals.clear();
3583 }
3584
3585 Stream.ExitBlock();
3586}
3587
3588/// Emit the combined summary section into the combined index file.
3589void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3590 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3591 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3592
3593 // Abbrev for FS_COMBINED.
3594 auto Abbv = std::make_shared<BitCodeAbbrev>();
3595 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3596 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3597 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3598 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3599 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3601 // numrefs x valueid, n x (valueid)
3602 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3603 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3604 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3605
3606 // Abbrev for FS_COMBINED_PROFILE.
3607 Abbv = std::make_shared<BitCodeAbbrev>();
3608 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3611 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3612 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3614 // numrefs x valueid, n x (valueid, hotness)
3615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3617 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3618
3619 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3620 Abbv = std::make_shared<BitCodeAbbrev>();
3621 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3622 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3623 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3624 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3627 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3628
3629 // Abbrev for FS_COMBINED_ALIAS.
3630 Abbv = std::make_shared<BitCodeAbbrev>();
3631 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3636 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3637
3638 // The aliases are emitted as a post-pass, and will point to the value
3639 // id of the aliasee. Save them in a vector for post-processing.
3640 SmallVector<AliasSummary *, 64> Aliases;
3641
3642 // Save the value id for each summary for alias emission.
3643 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3644
3645 SmallVector<uint64_t, 64> NameVals;
3646
3647 // For local linkage, we also emit the original name separately
3648 // immediately after the record.
3649 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3650 if (!GlobalValue::isLocalLinkage(S.linkage()))
3651 return;
3652 NameVals.push_back(S.getOriginalName());
3653 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3654 NameVals.clear();
3655 };
3656
3657 for (const auto &I : *this) {
3658 GlobalValueSummary *S = I.second;
3659 assert(S)((S) ? static_cast<void> (0) : __assert_fail ("S", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3659, __PRETTY_FUNCTION__))
;
3660
3661 assert(hasValueId(I.first))((hasValueId(I.first)) ? static_cast<void> (0) : __assert_fail
("hasValueId(I.first)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3661, __PRETTY_FUNCTION__))
;
3662 unsigned ValueId = getValueId(I.first);
3663 SummaryToValueIdMap[S] = ValueId;
3664
3665 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3666 // Will process aliases as a post-pass because the reader wants all
3667 // global to be loaded first.
3668 Aliases.push_back(AS);
3669 continue;
3670 }
3671
3672 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3673 NameVals.push_back(ValueId);
3674 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3675 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3676 for (auto &RI : VS->refs()) {
3677 NameVals.push_back(getValueId(RI.getGUID()));
3678 }
3679
3680 // Emit the finished record.
3681 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3682 FSModRefsAbbrev);
3683 NameVals.clear();
3684 MaybeEmitOriginalName(*S);
3685 continue;
3686 }
3687
3688 auto *FS = cast<FunctionSummary>(S);
3689 writeFunctionTypeMetadataRecords(Stream, FS);
3690
3691 NameVals.push_back(ValueId);
3692 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3693 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3694 NameVals.push_back(FS->instCount());
3695 NameVals.push_back(FS->refs().size());
3696
3697 for (auto &RI : FS->refs()) {
3698 NameVals.push_back(getValueId(RI.getGUID()));
3699 }
3700
3701 bool HasProfileData = false;
3702 for (auto &EI : FS->calls()) {
3703 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3704 if (HasProfileData)
3705 break;
3706 }
3707
3708 for (auto &EI : FS->calls()) {
3709 // If this GUID doesn't have a value id, it doesn't have a function
3710 // summary and we don't need to record any calls to it.
3711 GlobalValue::GUID GUID = EI.first.getGUID();
3712 if (!hasValueId(GUID)) {
3713 // For SamplePGO, the indirect call targets for local functions will
3714 // have its original name annotated in profile. We try to find the
3715 // corresponding PGOFuncName as the GUID.
3716 GUID = Index.getGUIDFromOriginalID(GUID);
3717 if (GUID == 0 || !hasValueId(GUID))
3718 continue;
3719 }
3720 NameVals.push_back(getValueId(GUID));
3721 if (HasProfileData)
3722 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3723 }
3724
3725 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3726 unsigned Code =
3727 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3728
3729 // Emit the finished record.
3730 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3731 NameVals.clear();
3732 MaybeEmitOriginalName(*S);
3733 }
3734
3735 for (auto *AS : Aliases) {
3736 auto AliasValueId = SummaryToValueIdMap[AS];
3737 assert(AliasValueId)((AliasValueId) ? static_cast<void> (0) : __assert_fail
("AliasValueId", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3737, __PRETTY_FUNCTION__))
;
3738 NameVals.push_back(AliasValueId);
3739 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3740 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3741 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3742 assert(AliaseeValueId)((AliaseeValueId) ? static_cast<void> (0) : __assert_fail
("AliaseeValueId", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3742, __PRETTY_FUNCTION__))
;
3743 NameVals.push_back(AliaseeValueId);
3744
3745 // Emit the finished record.
3746 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3747 NameVals.clear();
3748 MaybeEmitOriginalName(*AS);
3749 }
3750
3751 Stream.ExitBlock();
3752}
3753
3754/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3755/// current llvm version, and a record for the epoch number.
3756static void writeIdentificationBlock(BitstreamWriter &Stream) {
3757 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3758
3759 // Write the "user readable" string identifying the bitcode producer
3760 auto Abbv = std::make_shared<BitCodeAbbrev>();
3761 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3764 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3765 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3766 "LLVM" LLVM_VERSION_STRING"5.0.0", StringAbbrev);
3767
3768 // Write the epoch version
3769 Abbv = std::make_shared<BitCodeAbbrev>();
3770 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3772 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3773 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3774 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3775 Stream.ExitBlock();
3776}
3777
3778void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3779 // Emit the module's hash.
3780 // MODULE_CODE_HASH: [5*i32]
3781 SHA1 Hasher;
3782 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3783 Buffer.size() - BlockStartPos));
3784 StringRef Hash = Hasher.result();
3785 uint32_t Vals[5];
3786 for (int Pos = 0; Pos < 20; Pos += 4) {
3787 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3788 }
3789
3790 // Emit the finished record.
3791 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3792}
3793
3794void ModuleBitcodeWriter::write() {
3795 writeIdentificationBlock(Stream);
3796
3797 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3798 size_t BlockStartPos = Buffer.size();
3799
3800 SmallVector<unsigned, 1> Vals;
3801 unsigned CurVersion = 1;
3802 Vals.push_back(CurVersion);
3803 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3804
3805 // Emit blockinfo, which defines the standard abbreviations etc.
3806 writeBlockInfo();
3807
3808 // Emit information about attribute groups.
3809 writeAttributeGroupTable();
3810
3811 // Emit information about parameter attributes.
3812 writeAttributeTable();
3813
3814 // Emit information describing all of the types in the module.
3815 writeTypeTable();
3816
3817 writeComdats();
3818
3819 // Emit top-level description of module, including target triple, inline asm,
3820 // descriptors for global variables, and function prototype info.
3821 writeModuleInfo();
3822
3823 // Emit constants.
3824 writeModuleConstants();
3825
3826 // Emit metadata kind names.
3827 writeModuleMetadataKinds();
3828
3829 // Emit metadata.
3830 writeModuleMetadata();
3831
3832 // Emit module-level use-lists.
3833 if (VE.shouldPreserveUseListOrder())
3834 writeUseListBlock(nullptr);
3835
3836 writeOperandBundleTags();
3837
3838 // Emit function bodies.
3839 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3840 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3841 if (!F->isDeclaration())
3842 writeFunction(*F, FunctionToBitcodeIndex);
3843
3844 // Need to write after the above call to WriteFunction which populates
3845 // the summary information in the index.
3846 if (Index)
3847 writePerModuleGlobalValueSummary();
3848
3849 writeValueSymbolTable(M.getValueSymbolTable(),
3850 /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
3851
3852 if (GenerateHash) {
3853 writeModuleHash(BlockStartPos);
3854 }
3855
3856 Stream.ExitBlock();
3857}
3858
3859static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3860 uint32_t &Position) {
3861 support::endian::write32le(&Buffer[Position], Value);
3862 Position += 4;
3863}
3864
3865/// If generating a bc file on darwin, we have to emit a
3866/// header and trailer to make it compatible with the system archiver. To do
3867/// this we emit the following header, and then emit a trailer that pads the
3868/// file out to be a multiple of 16 bytes.
3869///
3870/// struct bc_header {
3871/// uint32_t Magic; // 0x0B17C0DE
3872/// uint32_t Version; // Version, currently always 0.
3873/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3874/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3875/// uint32_t CPUType; // CPU specifier.
3876/// ... potentially more later ...
3877/// };
3878static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3879 const Triple &TT) {
3880 unsigned CPUType = ~0U;
3881
3882 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3883 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3884 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3885 // specific constants here because they are implicitly part of the Darwin ABI.
3886 enum {
3887 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3888 DARWIN_CPU_TYPE_X86 = 7,
3889 DARWIN_CPU_TYPE_ARM = 12,
3890 DARWIN_CPU_TYPE_POWERPC = 18
3891 };
3892
3893 Triple::ArchType Arch = TT.getArch();
3894 if (Arch == Triple::x86_64)
3895 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3896 else if (Arch == Triple::x86)
3897 CPUType = DARWIN_CPU_TYPE_X86;
3898 else if (Arch == Triple::ppc)
3899 CPUType = DARWIN_CPU_TYPE_POWERPC;
3900 else if (Arch == Triple::ppc64)
3901 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3902 else if (Arch == Triple::arm || Arch == Triple::thumb)
3903 CPUType = DARWIN_CPU_TYPE_ARM;
3904
3905 // Traditional Bitcode starts after header.
3906 assert(Buffer.size() >= BWH_HeaderSize &&((Buffer.size() >= BWH_HeaderSize && "Expected header size to be reserved"
) ? static_cast<void> (0) : __assert_fail ("Buffer.size() >= BWH_HeaderSize && \"Expected header size to be reserved\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3907, __PRETTY_FUNCTION__))
3907 "Expected header size to be reserved")((Buffer.size() >= BWH_HeaderSize && "Expected header size to be reserved"
) ? static_cast<void> (0) : __assert_fail ("Buffer.size() >= BWH_HeaderSize && \"Expected header size to be reserved\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3907, __PRETTY_FUNCTION__))
;
3908 unsigned BCOffset = BWH_HeaderSize;
3909 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3910
3911 // Write the magic and version.
3912 unsigned Position = 0;
3913 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3914 writeInt32ToBuffer(0, Buffer, Position); // Version.
3915 writeInt32ToBuffer(BCOffset, Buffer, Position);
3916 writeInt32ToBuffer(BCSize, Buffer, Position);
3917 writeInt32ToBuffer(CPUType, Buffer, Position);
3918
3919 // If the file is not a multiple of 16 bytes, insert dummy padding.
3920 while (Buffer.size() & 15)
3921 Buffer.push_back(0);
3922}
3923
3924/// Helper to write the header common to all bitcode files.
3925static void writeBitcodeHeader(BitstreamWriter &Stream) {
3926 // Emit the file header.
3927 Stream.Emit((unsigned)'B', 8);
3928 Stream.Emit((unsigned)'C', 8);
3929 Stream.Emit(0x0, 4);
3930 Stream.Emit(0xC, 4);
3931 Stream.Emit(0xE, 4);
3932 Stream.Emit(0xD, 4);
3933}
3934
3935BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3936 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3937 writeBitcodeHeader(*Stream);
3938}
3939
3940BitcodeWriter::~BitcodeWriter() = default;
3941
3942void BitcodeWriter::writeModule(const Module *M,
3943 bool ShouldPreserveUseListOrder,
3944 const ModuleSummaryIndex *Index,
3945 bool GenerateHash) {
3946 ModuleBitcodeWriter ModuleWriter(
3947 M, Buffer, *Stream, ShouldPreserveUseListOrder, Index, GenerateHash);
3948 ModuleWriter.write();
3949}
3950
3951/// WriteBitcodeToFile - Write the specified module to the specified output
3952/// stream.
3953void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3954 bool ShouldPreserveUseListOrder,
3955 const ModuleSummaryIndex *Index,
3956 bool GenerateHash) {
3957 SmallVector<char, 0> Buffer;
3958 Buffer.reserve(256*1024);
3959
3960 // If this is darwin or another generic macho target, reserve space for the
3961 // header.
3962 Triple TT(M->getTargetTriple());
3963 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3964 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3965
3966 BitcodeWriter Writer(Buffer);
3967 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash);
3968
3969 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3970 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3971
3972 // Write the generated bitstream to "Out".
3973 Out.write((char*)&Buffer.front(), Buffer.size());
3974}
3975
3976void IndexBitcodeWriter::write() {
3977 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3978
3979 SmallVector<unsigned, 1> Vals;
3980 unsigned CurVersion = 1;
3981 Vals.push_back(CurVersion);
3982 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3983
3984 // If we have a VST, write the VSTOFFSET record placeholder.
3985 writeValueSymbolTableForwardDecl();
3986
3987 // Write the module paths in the combined index.
3988 writeModStrings();
3989
3990 // Write the summary combined index records.
3991 writeCombinedGlobalValueSummary();
3992
3993 // Need a special VST writer for the combined index (we don't have a
3994 // real VST and real values when this is invoked).
3995 writeCombinedValueSymbolTable();
3996
3997 Stream.ExitBlock();
3998}
3999
4000// Write the specified module summary index to the given raw output stream,
4001// where it will be written in a new bitcode block. This is used when
4002// writing the combined index file for ThinLTO. When writing a subset of the
4003// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4004void llvm::WriteIndexToFile(
4005 const ModuleSummaryIndex &Index, raw_ostream &Out,
4006 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4007 SmallVector<char, 0> Buffer;
4008 Buffer.reserve(256 * 1024);
4009
4010 BitstreamWriter Stream(Buffer);
4011 writeBitcodeHeader(Stream);
4012
4013 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
4014 IndexWriter.write();
4015
4016 Out.write((char *)&Buffer.front(), Buffer.size());
4017}