Bug Summary

File:lib/Bitcode/Writer/BitcodeWriter.cpp
Warning:line 2942, 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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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~svn296300/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 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1477 Record.clear();
1478}
1479
1480void ModuleBitcodeWriter::writeDICompositeType(
1481 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1482 unsigned Abbrev) {
1483 const unsigned IsNotUsedInOldTypeRef = 0x2;
1484 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1485 Record.push_back(N->getTag());
1486 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1487 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1488 Record.push_back(N->getLine());
1489 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1490 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1491 Record.push_back(N->getSizeInBits());
1492 Record.push_back(N->getAlignInBits());
1493 Record.push_back(N->getOffsetInBits());
1494 Record.push_back(N->getFlags());
1495 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1496 Record.push_back(N->getRuntimeLang());
1497 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1498 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1499 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1500
1501 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1502 Record.clear();
1503}
1504
1505void ModuleBitcodeWriter::writeDISubroutineType(
1506 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1507 unsigned Abbrev) {
1508 const unsigned HasNoOldTypeRefs = 0x2;
1509 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1510 Record.push_back(N->getFlags());
1511 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1512 Record.push_back(N->getCC());
1513
1514 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1515 Record.clear();
1516}
1517
1518void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1519 SmallVectorImpl<uint64_t> &Record,
1520 unsigned Abbrev) {
1521 Record.push_back(N->isDistinct());
1522 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1523 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1524 Record.push_back(N->getChecksumKind());
1525 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
1526
1527 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1528 Record.clear();
1529}
1530
1531void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1532 SmallVectorImpl<uint64_t> &Record,
1533 unsigned Abbrev) {
1534 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1534, __PRETTY_FUNCTION__))
;
1535 Record.push_back(/* IsDistinct */ true);
1536 Record.push_back(N->getSourceLanguage());
1537 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1538 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1539 Record.push_back(N->isOptimized());
1540 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1541 Record.push_back(N->getRuntimeVersion());
1542 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1543 Record.push_back(N->getEmissionKind());
1544 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1545 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1546 Record.push_back(/* subprograms */ 0);
1547 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1548 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1549 Record.push_back(N->getDWOId());
1550 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1551 Record.push_back(N->getSplitDebugInlining());
1552 Record.push_back(N->getDebugInfoForProfiling());
1553
1554 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1555 Record.clear();
1556}
1557
1558void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1559 SmallVectorImpl<uint64_t> &Record,
1560 unsigned Abbrev) {
1561 uint64_t HasUnitFlag = 1 << 1;
1562 Record.push_back(N->isDistinct() | HasUnitFlag);
1563 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1564 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1565 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1566 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1567 Record.push_back(N->getLine());
1568 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1569 Record.push_back(N->isLocalToUnit());
1570 Record.push_back(N->isDefinition());
1571 Record.push_back(N->getScopeLine());
1572 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1573 Record.push_back(N->getVirtuality());
1574 Record.push_back(N->getVirtualIndex());
1575 Record.push_back(N->getFlags());
1576 Record.push_back(N->isOptimized());
1577 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1578 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1579 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1580 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
1581 Record.push_back(N->getThisAdjustment());
1582
1583 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1584 Record.clear();
1585}
1586
1587void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1588 SmallVectorImpl<uint64_t> &Record,
1589 unsigned Abbrev) {
1590 Record.push_back(N->isDistinct());
1591 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1592 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1593 Record.push_back(N->getLine());
1594 Record.push_back(N->getColumn());
1595
1596 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1597 Record.clear();
1598}
1599
1600void ModuleBitcodeWriter::writeDILexicalBlockFile(
1601 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1602 unsigned Abbrev) {
1603 Record.push_back(N->isDistinct());
1604 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1605 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1606 Record.push_back(N->getDiscriminator());
1607
1608 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1609 Record.clear();
1610}
1611
1612void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1613 SmallVectorImpl<uint64_t> &Record,
1614 unsigned Abbrev) {
1615 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1616 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1618 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1619 Record.push_back(N->getLine());
1620
1621 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1622 Record.clear();
1623}
1624
1625void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1626 SmallVectorImpl<uint64_t> &Record,
1627 unsigned Abbrev) {
1628 Record.push_back(N->isDistinct());
1629 Record.push_back(N->getMacinfoType());
1630 Record.push_back(N->getLine());
1631 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1632 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1633
1634 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1635 Record.clear();
1636}
1637
1638void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1639 SmallVectorImpl<uint64_t> &Record,
1640 unsigned Abbrev) {
1641 Record.push_back(N->isDistinct());
1642 Record.push_back(N->getMacinfoType());
1643 Record.push_back(N->getLine());
1644 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1645 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1646
1647 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1648 Record.clear();
1649}
1650
1651void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1652 SmallVectorImpl<uint64_t> &Record,
1653 unsigned Abbrev) {
1654 Record.push_back(N->isDistinct());
1655 for (auto &I : N->operands())
1656 Record.push_back(VE.getMetadataOrNullID(I));
1657
1658 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1659 Record.clear();
1660}
1661
1662void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1663 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1664 unsigned Abbrev) {
1665 Record.push_back(N->isDistinct());
1666 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1667 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1668
1669 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1670 Record.clear();
1671}
1672
1673void ModuleBitcodeWriter::writeDITemplateValueParameter(
1674 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1675 unsigned Abbrev) {
1676 Record.push_back(N->isDistinct());
1677 Record.push_back(N->getTag());
1678 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1679 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1680 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1681
1682 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1683 Record.clear();
1684}
1685
1686void ModuleBitcodeWriter::writeDIGlobalVariable(
1687 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1688 unsigned Abbrev) {
1689 const uint64_t Version = 1 << 1;
1690 Record.push_back((uint64_t)N->isDistinct() | Version);
1691 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1692 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1694 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1695 Record.push_back(N->getLine());
1696 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1697 Record.push_back(N->isLocalToUnit());
1698 Record.push_back(N->isDefinition());
1699 Record.push_back(/* expr */ 0);
1700 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1701 Record.push_back(N->getAlignInBits());
1702
1703 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1704 Record.clear();
1705}
1706
1707void ModuleBitcodeWriter::writeDILocalVariable(
1708 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1709 unsigned Abbrev) {
1710 // In order to support all possible bitcode formats in BitcodeReader we need
1711 // to distinguish the following cases:
1712 // 1) Record has no artificial tag (Record[1]),
1713 // has no obsolete inlinedAt field (Record[9]).
1714 // In this case Record size will be 8, HasAlignment flag is false.
1715 // 2) Record has artificial tag (Record[1]),
1716 // has no obsolete inlignedAt field (Record[9]).
1717 // In this case Record size will be 9, HasAlignment flag is false.
1718 // 3) Record has both artificial tag (Record[1]) and
1719 // obsolete inlignedAt field (Record[9]).
1720 // In this case Record size will be 10, HasAlignment flag is false.
1721 // 4) Record has neither artificial tag, nor inlignedAt field, but
1722 // HasAlignment flag is true and Record[8] contains alignment value.
1723 const uint64_t HasAlignmentFlag = 1 << 1;
1724 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
1725 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1726 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1727 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1728 Record.push_back(N->getLine());
1729 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1730 Record.push_back(N->getArg());
1731 Record.push_back(N->getFlags());
1732 Record.push_back(N->getAlignInBits());
1733
1734 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
1735 Record.clear();
1736}
1737
1738void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1739 SmallVectorImpl<uint64_t> &Record,
1740 unsigned Abbrev) {
1741 Record.reserve(N->getElements().size() + 1);
1742
1743 const uint64_t HasOpFragmentFlag = 1 << 1;
1744 Record.push_back((uint64_t)N->isDistinct() | HasOpFragmentFlag);
1745 Record.append(N->elements_begin(), N->elements_end());
1746
1747 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
1748 Record.clear();
1749}
1750
1751void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1752 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1753 unsigned Abbrev) {
1754 Record.push_back(N->isDistinct());
1755 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1756 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1757
1758 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1759 Record.clear();
1760}
1761
1762void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1763 SmallVectorImpl<uint64_t> &Record,
1764 unsigned Abbrev) {
1765 Record.push_back(N->isDistinct());
1766 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1767 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1768 Record.push_back(N->getLine());
1769 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1770 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1771 Record.push_back(N->getAttributes());
1772 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1773
1774 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
1775 Record.clear();
1776}
1777
1778void ModuleBitcodeWriter::writeDIImportedEntity(
1779 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1780 unsigned Abbrev) {
1781 Record.push_back(N->isDistinct());
1782 Record.push_back(N->getTag());
1783 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1784 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1785 Record.push_back(N->getLine());
1786 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1787
1788 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
1789 Record.clear();
1790}
1791
1792unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
1793 auto Abbv = std::make_shared<BitCodeAbbrev>();
1794 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1797 return Stream.EmitAbbrev(std::move(Abbv));
1798}
1799
1800void ModuleBitcodeWriter::writeNamedMetadata(
1801 SmallVectorImpl<uint64_t> &Record) {
1802 if (M.named_metadata_empty())
1803 return;
1804
1805 unsigned Abbrev = createNamedMetadataAbbrev();
1806 for (const NamedMDNode &NMD : M.named_metadata()) {
1807 // Write name.
1808 StringRef Str = NMD.getName();
1809 Record.append(Str.bytes_begin(), Str.bytes_end());
1810 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
1811 Record.clear();
1812
1813 // Write named metadata operands.
1814 for (const MDNode *N : NMD.operands())
1815 Record.push_back(VE.getMetadataID(N));
1816 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
1817 Record.clear();
1818 }
1819}
1820
1821unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
1822 auto Abbv = std::make_shared<BitCodeAbbrev>();
1823 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1825 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1826 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1827 return Stream.EmitAbbrev(std::move(Abbv));
1828}
1829
1830/// Write out a record for MDString.
1831///
1832/// All the metadata strings in a metadata block are emitted in a single
1833/// record. The sizes and strings themselves are shoved into a blob.
1834void ModuleBitcodeWriter::writeMetadataStrings(
1835 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
1836 if (Strings.empty())
1837 return;
1838
1839 // Start the record with the number of strings.
1840 Record.push_back(bitc::METADATA_STRINGS);
1841 Record.push_back(Strings.size());
1842
1843 // Emit the sizes of the strings in the blob.
1844 SmallString<256> Blob;
1845 {
1846 BitstreamWriter W(Blob);
1847 for (const Metadata *MD : Strings)
1848 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1849 W.FlushToWord();
1850 }
1851
1852 // Add the offset to the strings to the record.
1853 Record.push_back(Blob.size());
1854
1855 // Add the strings to the blob.
1856 for (const Metadata *MD : Strings)
1857 Blob.append(cast<MDString>(MD)->getString());
1858
1859 // Emit the final record.
1860 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
1861 Record.clear();
1862}
1863
1864// Generates an enum to use as an index in the Abbrev array of Metadata record.
1865enum MetadataAbbrev : unsigned {
1866#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1867#include "llvm/IR/Metadata.def"
1868 LastPlusOne
1869};
1870
1871void ModuleBitcodeWriter::writeMetadataRecords(
1872 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1873 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
1874 if (MDs.empty())
1875 return;
1876
1877 // Initialize MDNode abbreviations.
1878#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1879#include "llvm/IR/Metadata.def"
1880
1881 for (const Metadata *MD : MDs) {
1882 if (IndexPos)
1883 IndexPos->push_back(Stream.GetCurrentBitNo());
1884 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1885 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1885, __PRETTY_FUNCTION__))
;
1886
1887 switch (N->getMetadataID()) {
1888 default:
1889 llvm_unreachable("Invalid MDNode subclass")::llvm::llvm_unreachable_internal("Invalid MDNode subclass", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 1889)
;
1890#define HANDLE_MDNODE_LEAF(CLASS) \
1891 case Metadata::CLASS##Kind: \
1892 if (MDAbbrevs) \
1893 write##CLASS(cast<CLASS>(N), Record, \
1894 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1895 else \
1896 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
1897 continue;
1898#include "llvm/IR/Metadata.def"
1899 }
1900 }
1901 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
1902 }
1903}
1904
1905void ModuleBitcodeWriter::writeModuleMetadata() {
1906 if (!VE.hasMDs() && M.named_metadata_empty())
1907 return;
1908
1909 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
1910 SmallVector<uint64_t, 64> Record;
1911
1912 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1913 // block and load any metadata.
1914 std::vector<unsigned> MDAbbrevs;
1915
1916 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1917 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1918 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1919 createGenericDINodeAbbrev();
1920
1921 auto Abbv = std::make_shared<BitCodeAbbrev>();
1922 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
1923 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1924 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1925 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1926
1927 Abbv = std::make_shared<BitCodeAbbrev>();
1928 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1931 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1932
1933 // Emit MDStrings together upfront.
1934 writeMetadataStrings(VE.getMDStrings(), Record);
1935
1936 // We only emit an index for the metadata record if we have more than a given
1937 // (naive) threshold of metadatas, otherwise it is not worth it.
1938 if (VE.getNonMDStrings().size() > IndexThreshold) {
1939 // Write a placeholder value in for the offset of the metadata index,
1940 // which is written after the records, so that it can include
1941 // the offset of each entry. The placeholder offset will be
1942 // updated after all records are emitted.
1943 uint64_t Vals[] = {0, 0};
1944 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1945 }
1946
1947 // Compute and save the bit offset to the current position, which will be
1948 // patched when we emit the index later. We can simply subtract the 64-bit
1949 // fixed size from the current bit number to get the location to backpatch.
1950 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1951
1952 // This index will contain the bitpos for each individual record.
1953 std::vector<uint64_t> IndexPos;
1954 IndexPos.reserve(VE.getNonMDStrings().size());
1955
1956 // Write all the records
1957 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1958
1959 if (VE.getNonMDStrings().size() > IndexThreshold) {
1960 // Now that we have emitted all the records we will emit the index. But
1961 // first
1962 // backpatch the forward reference so that the reader can skip the records
1963 // efficiently.
1964 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1965 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1966
1967 // Delta encode the index.
1968 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1969 for (auto &Elt : IndexPos) {
1970 auto EltDelta = Elt - PreviousValue;
1971 PreviousValue = Elt;
1972 Elt = EltDelta;
1973 }
1974 // Emit the index record.
1975 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1976 IndexPos.clear();
1977 }
1978
1979 // Write the named metadata now.
1980 writeNamedMetadata(Record);
1981
1982 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1983 SmallVector<uint64_t, 4> Record;
1984 Record.push_back(VE.getValueID(&GO));
1985 pushGlobalMetadataAttachment(Record, GO);
1986 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1987 };
1988 for (const Function &F : M)
1989 if (F.isDeclaration() && F.hasMetadata())
1990 AddDeclAttachedMetadata(F);
1991 // FIXME: Only store metadata for declarations here, and move data for global
1992 // variable definitions to a separate block (PR28134).
1993 for (const GlobalVariable &GV : M.globals())
1994 if (GV.hasMetadata())
1995 AddDeclAttachedMetadata(GV);
1996
1997 Stream.ExitBlock();
1998}
1999
2000void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2001 if (!VE.hasMDs())
2002 return;
2003
2004 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2005 SmallVector<uint64_t, 64> Record;
2006 writeMetadataStrings(VE.getMDStrings(), Record);
2007 writeMetadataRecords(VE.getNonMDStrings(), Record);
2008 Stream.ExitBlock();
2009}
2010
2011void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2012 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2013 // [n x [id, mdnode]]
2014 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2015 GO.getAllMetadata(MDs);
2016 for (const auto &I : MDs) {
2017 Record.push_back(I.first);
2018 Record.push_back(VE.getMetadataID(I.second));
2019 }
2020}
2021
2022void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2023 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2024
2025 SmallVector<uint64_t, 64> Record;
2026
2027 if (F.hasMetadata()) {
2028 pushGlobalMetadataAttachment(Record, F);
2029 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2030 Record.clear();
2031 }
2032
2033 // Write metadata attachments
2034 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2035 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2036 for (const BasicBlock &BB : F)
2037 for (const Instruction &I : BB) {
2038 MDs.clear();
2039 I.getAllMetadataOtherThanDebugLoc(MDs);
2040
2041 // If no metadata, ignore instruction.
2042 if (MDs.empty()) continue;
2043
2044 Record.push_back(VE.getInstructionID(&I));
2045
2046 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2047 Record.push_back(MDs[i].first);
2048 Record.push_back(VE.getMetadataID(MDs[i].second));
2049 }
2050 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2051 Record.clear();
2052 }
2053
2054 Stream.ExitBlock();
2055}
2056
2057void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2058 SmallVector<uint64_t, 64> Record;
2059
2060 // Write metadata kinds
2061 // METADATA_KIND - [n x [id, name]]
2062 SmallVector<StringRef, 8> Names;
2063 M.getMDKindNames(Names);
2064
2065 if (Names.empty()) return;
2066
2067 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2068
2069 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2070 Record.push_back(MDKindID);
2071 StringRef KName = Names[MDKindID];
2072 Record.append(KName.begin(), KName.end());
2073
2074 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2075 Record.clear();
2076 }
2077
2078 Stream.ExitBlock();
2079}
2080
2081void ModuleBitcodeWriter::writeOperandBundleTags() {
2082 // Write metadata kinds
2083 //
2084 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2085 //
2086 // OPERAND_BUNDLE_TAG - [strchr x N]
2087
2088 SmallVector<StringRef, 8> Tags;
2089 M.getOperandBundleTags(Tags);
2090
2091 if (Tags.empty())
2092 return;
2093
2094 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2095
2096 SmallVector<uint64_t, 64> Record;
2097
2098 for (auto Tag : Tags) {
2099 Record.append(Tag.begin(), Tag.end());
2100
2101 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2102 Record.clear();
2103 }
2104
2105 Stream.ExitBlock();
2106}
2107
2108static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2109 if ((int64_t)V >= 0)
2110 Vals.push_back(V << 1);
2111 else
2112 Vals.push_back((-V << 1) | 1);
2113}
2114
2115void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2116 bool isGlobal) {
2117 if (FirstVal == LastVal) return;
2118
2119 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2120
2121 unsigned AggregateAbbrev = 0;
2122 unsigned String8Abbrev = 0;
2123 unsigned CString7Abbrev = 0;
2124 unsigned CString6Abbrev = 0;
2125 // If this is a constant pool for the module, emit module-specific abbrevs.
2126 if (isGlobal) {
2127 // Abbrev for CST_CODE_AGGREGATE.
2128 auto Abbv = std::make_shared<BitCodeAbbrev>();
2129 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2132 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2133
2134 // Abbrev for CST_CODE_STRING.
2135 Abbv = std::make_shared<BitCodeAbbrev>();
2136 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2139 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2140 // Abbrev for CST_CODE_CSTRING.
2141 Abbv = std::make_shared<BitCodeAbbrev>();
2142 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2145 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2146 // Abbrev for CST_CODE_CSTRING.
2147 Abbv = std::make_shared<BitCodeAbbrev>();
2148 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2151 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2152 }
2153
2154 SmallVector<uint64_t, 64> Record;
2155
2156 const ValueEnumerator::ValueList &Vals = VE.getValues();
2157 Type *LastTy = nullptr;
2158 for (unsigned i = FirstVal; i != LastVal; ++i) {
2159 const Value *V = Vals[i].first;
2160 // If we need to switch types, do so now.
2161 if (V->getType() != LastTy) {
2162 LastTy = V->getType();
2163 Record.push_back(VE.getTypeID(LastTy));
2164 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2165 CONSTANTS_SETTYPE_ABBREV);
2166 Record.clear();
2167 }
2168
2169 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2170 Record.push_back(unsigned(IA->hasSideEffects()) |
2171 unsigned(IA->isAlignStack()) << 1 |
2172 unsigned(IA->getDialect()&1) << 2);
2173
2174 // Add the asm string.
2175 const std::string &AsmStr = IA->getAsmString();
2176 Record.push_back(AsmStr.size());
2177 Record.append(AsmStr.begin(), AsmStr.end());
2178
2179 // Add the constraint string.
2180 const std::string &ConstraintStr = IA->getConstraintString();
2181 Record.push_back(ConstraintStr.size());
2182 Record.append(ConstraintStr.begin(), ConstraintStr.end());
2183 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2184 Record.clear();
2185 continue;
2186 }
2187 const Constant *C = cast<Constant>(V);
2188 unsigned Code = -1U;
2189 unsigned AbbrevToUse = 0;
2190 if (C->isNullValue()) {
2191 Code = bitc::CST_CODE_NULL;
2192 } else if (isa<UndefValue>(C)) {
2193 Code = bitc::CST_CODE_UNDEF;
2194 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2195 if (IV->getBitWidth() <= 64) {
2196 uint64_t V = IV->getSExtValue();
2197 emitSignedInt64(Record, V);
2198 Code = bitc::CST_CODE_INTEGER;
2199 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2200 } else { // Wide integers, > 64 bits in size.
2201 // We have an arbitrary precision integer value to write whose
2202 // bit width is > 64. However, in canonical unsigned integer
2203 // format it is likely that the high bits are going to be zero.
2204 // So, we only write the number of active words.
2205 unsigned NWords = IV->getValue().getActiveWords();
2206 const uint64_t *RawWords = IV->getValue().getRawData();
2207 for (unsigned i = 0; i != NWords; ++i) {
2208 emitSignedInt64(Record, RawWords[i]);
2209 }
2210 Code = bitc::CST_CODE_WIDE_INTEGER;
2211 }
2212 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2213 Code = bitc::CST_CODE_FLOAT;
2214 Type *Ty = CFP->getType();
2215 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
2216 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2217 } else if (Ty->isX86_FP80Ty()) {
2218 // api needed to prevent premature destruction
2219 // bits are not in the same order as a normal i80 APInt, compensate.
2220 APInt api = CFP->getValueAPF().bitcastToAPInt();
2221 const uint64_t *p = api.getRawData();
2222 Record.push_back((p[1] << 48) | (p[0] >> 16));
2223 Record.push_back(p[0] & 0xffffLL);
2224 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2225 APInt api = CFP->getValueAPF().bitcastToAPInt();
2226 const uint64_t *p = api.getRawData();
2227 Record.push_back(p[0]);
2228 Record.push_back(p[1]);
2229 } else {
2230 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2230, __PRETTY_FUNCTION__))
;
2231 }
2232 } else if (isa<ConstantDataSequential>(C) &&
2233 cast<ConstantDataSequential>(C)->isString()) {
2234 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2235 // Emit constant strings specially.
2236 unsigned NumElts = Str->getNumElements();
2237 // If this is a null-terminated string, use the denser CSTRING encoding.
2238 if (Str->isCString()) {
2239 Code = bitc::CST_CODE_CSTRING;
2240 --NumElts; // Don't encode the null, which isn't allowed by char6.
2241 } else {
2242 Code = bitc::CST_CODE_STRING;
2243 AbbrevToUse = String8Abbrev;
2244 }
2245 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2246 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2247 for (unsigned i = 0; i != NumElts; ++i) {
2248 unsigned char V = Str->getElementAsInteger(i);
2249 Record.push_back(V);
2250 isCStr7 &= (V & 128) == 0;
2251 if (isCStrChar6)
2252 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2253 }
2254
2255 if (isCStrChar6)
2256 AbbrevToUse = CString6Abbrev;
2257 else if (isCStr7)
2258 AbbrevToUse = CString7Abbrev;
2259 } else if (const ConstantDataSequential *CDS =
2260 dyn_cast<ConstantDataSequential>(C)) {
2261 Code = bitc::CST_CODE_DATA;
2262 Type *EltTy = CDS->getType()->getElementType();
2263 if (isa<IntegerType>(EltTy)) {
2264 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2265 Record.push_back(CDS->getElementAsInteger(i));
2266 } else {
2267 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2268 Record.push_back(
2269 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2270 }
2271 } else if (isa<ConstantAggregate>(C)) {
2272 Code = bitc::CST_CODE_AGGREGATE;
2273 for (const Value *Op : C->operands())
2274 Record.push_back(VE.getValueID(Op));
2275 AbbrevToUse = AggregateAbbrev;
2276 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2277 switch (CE->getOpcode()) {
2278 default:
2279 if (Instruction::isCast(CE->getOpcode())) {
2280 Code = bitc::CST_CODE_CE_CAST;
2281 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2282 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2283 Record.push_back(VE.getValueID(C->getOperand(0)));
2284 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2285 } else {
2286 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2286, __PRETTY_FUNCTION__))
;
2287 Code = bitc::CST_CODE_CE_BINOP;
2288 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2289 Record.push_back(VE.getValueID(C->getOperand(0)));
2290 Record.push_back(VE.getValueID(C->getOperand(1)));
2291 uint64_t Flags = getOptimizationFlags(CE);
2292 if (Flags != 0)
2293 Record.push_back(Flags);
2294 }
2295 break;
2296 case Instruction::GetElementPtr: {
2297 Code = bitc::CST_CODE_CE_GEP;
2298 const auto *GO = cast<GEPOperator>(C);
2299 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2300 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2301 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2302 Record.push_back((*Idx << 1) | GO->isInBounds());
2303 } else if (GO->isInBounds())
2304 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
2305 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2306 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2307 Record.push_back(VE.getValueID(C->getOperand(i)));
2308 }
2309 break;
2310 }
2311 case Instruction::Select:
2312 Code = bitc::CST_CODE_CE_SELECT;
2313 Record.push_back(VE.getValueID(C->getOperand(0)));
2314 Record.push_back(VE.getValueID(C->getOperand(1)));
2315 Record.push_back(VE.getValueID(C->getOperand(2)));
2316 break;
2317 case Instruction::ExtractElement:
2318 Code = bitc::CST_CODE_CE_EXTRACTELT;
2319 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2320 Record.push_back(VE.getValueID(C->getOperand(0)));
2321 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2322 Record.push_back(VE.getValueID(C->getOperand(1)));
2323 break;
2324 case Instruction::InsertElement:
2325 Code = bitc::CST_CODE_CE_INSERTELT;
2326 Record.push_back(VE.getValueID(C->getOperand(0)));
2327 Record.push_back(VE.getValueID(C->getOperand(1)));
2328 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2329 Record.push_back(VE.getValueID(C->getOperand(2)));
2330 break;
2331 case Instruction::ShuffleVector:
2332 // If the return type and argument types are the same, this is a
2333 // standard shufflevector instruction. If the types are different,
2334 // then the shuffle is widening or truncating the input vectors, and
2335 // the argument type must also be encoded.
2336 if (C->getType() == C->getOperand(0)->getType()) {
2337 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2338 } else {
2339 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2340 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2341 }
2342 Record.push_back(VE.getValueID(C->getOperand(0)));
2343 Record.push_back(VE.getValueID(C->getOperand(1)));
2344 Record.push_back(VE.getValueID(C->getOperand(2)));
2345 break;
2346 case Instruction::ICmp:
2347 case Instruction::FCmp:
2348 Code = bitc::CST_CODE_CE_CMP;
2349 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2350 Record.push_back(VE.getValueID(C->getOperand(0)));
2351 Record.push_back(VE.getValueID(C->getOperand(1)));
2352 Record.push_back(CE->getPredicate());
2353 break;
2354 }
2355 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2356 Code = bitc::CST_CODE_BLOCKADDRESS;
2357 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2358 Record.push_back(VE.getValueID(BA->getFunction()));
2359 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2360 } else {
2361#ifndef NDEBUG
2362 C->dump();
2363#endif
2364 llvm_unreachable("Unknown constant!")::llvm::llvm_unreachable_internal("Unknown constant!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2364)
;
2365 }
2366 Stream.EmitRecord(Code, Record, AbbrevToUse);
2367 Record.clear();
2368 }
2369
2370 Stream.ExitBlock();
2371}
2372
2373void ModuleBitcodeWriter::writeModuleConstants() {
2374 const ValueEnumerator::ValueList &Vals = VE.getValues();
2375
2376 // Find the first constant to emit, which is the first non-globalvalue value.
2377 // We know globalvalues have been emitted by WriteModuleInfo.
2378 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2379 if (!isa<GlobalValue>(Vals[i].first)) {
2380 writeConstants(i, Vals.size(), true);
2381 return;
2382 }
2383 }
2384}
2385
2386/// pushValueAndType - The file has to encode both the value and type id for
2387/// many values, because we need to know what type to create for forward
2388/// references. However, most operands are not forward references, so this type
2389/// field is not needed.
2390///
2391/// This function adds V's value ID to Vals. If the value ID is higher than the
2392/// instruction ID, then it is a forward reference, and it also includes the
2393/// type ID. The value ID that is written is encoded relative to the InstID.
2394bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2395 SmallVectorImpl<unsigned> &Vals) {
2396 unsigned ValID = VE.getValueID(V);
2397 // Make encoding relative to the InstID.
2398 Vals.push_back(InstID - ValID);
2399 if (ValID >= InstID) {
2400 Vals.push_back(VE.getTypeID(V->getType()));
2401 return true;
2402 }
2403 return false;
2404}
2405
2406void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2407 unsigned InstID) {
2408 SmallVector<unsigned, 64> Record;
2409 LLVMContext &C = CS.getInstruction()->getContext();
2410
2411 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2412 const auto &Bundle = CS.getOperandBundleAt(i);
2413 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2414
2415 for (auto &Input : Bundle.Inputs)
2416 pushValueAndType(Input, InstID, Record);
2417
2418 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
2419 Record.clear();
2420 }
2421}
2422
2423/// pushValue - Like pushValueAndType, but where the type of the value is
2424/// omitted (perhaps it was already encoded in an earlier operand).
2425void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2426 SmallVectorImpl<unsigned> &Vals) {
2427 unsigned ValID = VE.getValueID(V);
2428 Vals.push_back(InstID - ValID);
2429}
2430
2431void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2432 SmallVectorImpl<uint64_t> &Vals) {
2433 unsigned ValID = VE.getValueID(V);
2434 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2435 emitSignedInt64(Vals, diff);
2436}
2437
2438/// WriteInstruction - Emit an instruction to the specified stream.
2439void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2440 unsigned InstID,
2441 SmallVectorImpl<unsigned> &Vals) {
2442 unsigned Code = 0;
2443 unsigned AbbrevToUse = 0;
2444 VE.setInstructionID(&I);
2445 switch (I.getOpcode()) {
2446 default:
2447 if (Instruction::isCast(I.getOpcode())) {
2448 Code = bitc::FUNC_CODE_INST_CAST;
2449 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2450 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2451 Vals.push_back(VE.getTypeID(I.getType()));
2452 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2453 } else {
2454 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2454, __PRETTY_FUNCTION__))
;
2455 Code = bitc::FUNC_CODE_INST_BINOP;
2456 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2457 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2458 pushValue(I.getOperand(1), InstID, Vals);
2459 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2460 uint64_t Flags = getOptimizationFlags(&I);
2461 if (Flags != 0) {
2462 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2463 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2464 Vals.push_back(Flags);
2465 }
2466 }
2467 break;
2468
2469 case Instruction::GetElementPtr: {
2470 Code = bitc::FUNC_CODE_INST_GEP;
2471 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2472 auto &GEPInst = cast<GetElementPtrInst>(I);
2473 Vals.push_back(GEPInst.isInBounds());
2474 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2475 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2476 pushValueAndType(I.getOperand(i), InstID, Vals);
2477 break;
2478 }
2479 case Instruction::ExtractValue: {
2480 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
2481 pushValueAndType(I.getOperand(0), InstID, Vals);
2482 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2483 Vals.append(EVI->idx_begin(), EVI->idx_end());
2484 break;
2485 }
2486 case Instruction::InsertValue: {
2487 Code = bitc::FUNC_CODE_INST_INSERTVAL;
2488 pushValueAndType(I.getOperand(0), InstID, Vals);
2489 pushValueAndType(I.getOperand(1), InstID, Vals);
2490 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2491 Vals.append(IVI->idx_begin(), IVI->idx_end());
2492 break;
2493 }
2494 case Instruction::Select:
2495 Code = bitc::FUNC_CODE_INST_VSELECT;
2496 pushValueAndType(I.getOperand(1), InstID, Vals);
2497 pushValue(I.getOperand(2), InstID, Vals);
2498 pushValueAndType(I.getOperand(0), InstID, Vals);
2499 break;
2500 case Instruction::ExtractElement:
2501 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
2502 pushValueAndType(I.getOperand(0), InstID, Vals);
2503 pushValueAndType(I.getOperand(1), InstID, Vals);
2504 break;
2505 case Instruction::InsertElement:
2506 Code = bitc::FUNC_CODE_INST_INSERTELT;
2507 pushValueAndType(I.getOperand(0), InstID, Vals);
2508 pushValue(I.getOperand(1), InstID, Vals);
2509 pushValueAndType(I.getOperand(2), InstID, Vals);
2510 break;
2511 case Instruction::ShuffleVector:
2512 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
2513 pushValueAndType(I.getOperand(0), InstID, Vals);
2514 pushValue(I.getOperand(1), InstID, Vals);
2515 pushValue(I.getOperand(2), InstID, Vals);
2516 break;
2517 case Instruction::ICmp:
2518 case Instruction::FCmp: {
2519 // compare returning Int1Ty or vector of Int1Ty
2520 Code = bitc::FUNC_CODE_INST_CMP2;
2521 pushValueAndType(I.getOperand(0), InstID, Vals);
2522 pushValue(I.getOperand(1), InstID, Vals);
2523 Vals.push_back(cast<CmpInst>(I).getPredicate());
2524 uint64_t Flags = getOptimizationFlags(&I);
2525 if (Flags != 0)
2526 Vals.push_back(Flags);
2527 break;
2528 }
2529
2530 case Instruction::Ret:
2531 {
2532 Code = bitc::FUNC_CODE_INST_RET;
2533 unsigned NumOperands = I.getNumOperands();
2534 if (NumOperands == 0)
2535 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2536 else if (NumOperands == 1) {
2537 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2538 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2539 } else {
2540 for (unsigned i = 0, e = NumOperands; i != e; ++i)
2541 pushValueAndType(I.getOperand(i), InstID, Vals);
2542 }
2543 }
2544 break;
2545 case Instruction::Br:
2546 {
2547 Code = bitc::FUNC_CODE_INST_BR;
2548 const BranchInst &II = cast<BranchInst>(I);
2549 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2550 if (II.isConditional()) {
2551 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2552 pushValue(II.getCondition(), InstID, Vals);
2553 }
2554 }
2555 break;
2556 case Instruction::Switch:
2557 {
2558 Code = bitc::FUNC_CODE_INST_SWITCH;
2559 const SwitchInst &SI = cast<SwitchInst>(I);
2560 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2561 pushValue(SI.getCondition(), InstID, Vals);
2562 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2563 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2564 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2565 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2566 }
2567 }
2568 break;
2569 case Instruction::IndirectBr:
2570 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
2571 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2572 // Encode the address operand as relative, but not the basic blocks.
2573 pushValue(I.getOperand(0), InstID, Vals);
2574 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2575 Vals.push_back(VE.getValueID(I.getOperand(i)));
2576 break;
2577
2578 case Instruction::Invoke: {
2579 const InvokeInst *II = cast<InvokeInst>(&I);
2580 const Value *Callee = II->getCalledValue();
2581 FunctionType *FTy = II->getFunctionType();
2582
2583 if (II->hasOperandBundles())
2584 writeOperandBundles(II, InstID);
2585
2586 Code = bitc::FUNC_CODE_INST_INVOKE;
2587
2588 Vals.push_back(VE.getAttributeID(II->getAttributes()));
2589 Vals.push_back(II->getCallingConv() | 1 << 13);
2590 Vals.push_back(VE.getValueID(II->getNormalDest()));
2591 Vals.push_back(VE.getValueID(II->getUnwindDest()));
2592 Vals.push_back(VE.getTypeID(FTy));
2593 pushValueAndType(Callee, InstID, Vals);
2594
2595 // Emit value #'s for the fixed parameters.
2596 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2597 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2598
2599 // Emit type/value pairs for varargs params.
2600 if (FTy->isVarArg()) {
2601 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
2602 i != e; ++i)
2603 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2604 }
2605 break;
2606 }
2607 case Instruction::Resume:
2608 Code = bitc::FUNC_CODE_INST_RESUME;
2609 pushValueAndType(I.getOperand(0), InstID, Vals);
2610 break;
2611 case Instruction::CleanupRet: {
2612 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2613 const auto &CRI = cast<CleanupReturnInst>(I);
2614 pushValue(CRI.getCleanupPad(), InstID, Vals);
2615 if (CRI.hasUnwindDest())
2616 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2617 break;
2618 }
2619 case Instruction::CatchRet: {
2620 Code = bitc::FUNC_CODE_INST_CATCHRET;
2621 const auto &CRI = cast<CatchReturnInst>(I);
2622 pushValue(CRI.getCatchPad(), InstID, Vals);
2623 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2624 break;
2625 }
2626 case Instruction::CleanupPad:
2627 case Instruction::CatchPad: {
2628 const auto &FuncletPad = cast<FuncletPadInst>(I);
2629 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2630 : bitc::FUNC_CODE_INST_CLEANUPPAD;
2631 pushValue(FuncletPad.getParentPad(), InstID, Vals);
2632
2633 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2634 Vals.push_back(NumArgOperands);
2635 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2636 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2637 break;
2638 }
2639 case Instruction::CatchSwitch: {
2640 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2641 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2642
2643 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2644
2645 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2646 Vals.push_back(NumHandlers);
2647 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2648 Vals.push_back(VE.getValueID(CatchPadBB));
2649
2650 if (CatchSwitch.hasUnwindDest())
2651 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
2652 break;
2653 }
2654 case Instruction::Unreachable:
2655 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
2656 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
2657 break;
2658
2659 case Instruction::PHI: {
2660 const PHINode &PN = cast<PHINode>(I);
2661 Code = bitc::FUNC_CODE_INST_PHI;
2662 // With the newer instruction encoding, forward references could give
2663 // negative valued IDs. This is most common for PHIs, so we use
2664 // signed VBRs.
2665 SmallVector<uint64_t, 128> Vals64;
2666 Vals64.push_back(VE.getTypeID(PN.getType()));
2667 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2668 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
2669 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
2670 }
2671 // Emit a Vals64 vector and exit.
2672 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
2673 Vals64.clear();
2674 return;
2675 }
2676
2677 case Instruction::LandingPad: {
2678 const LandingPadInst &LP = cast<LandingPadInst>(I);
2679 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2680 Vals.push_back(VE.getTypeID(LP.getType()));
2681 Vals.push_back(LP.isCleanup());
2682 Vals.push_back(LP.getNumClauses());
2683 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2684 if (LP.isCatch(I))
2685 Vals.push_back(LandingPadInst::Catch);
2686 else
2687 Vals.push_back(LandingPadInst::Filter);
2688 pushValueAndType(LP.getClause(I), InstID, Vals);
2689 }
2690 break;
2691 }
2692
2693 case Instruction::Alloca: {
2694 Code = bitc::FUNC_CODE_INST_ALLOCA;
2695 const AllocaInst &AI = cast<AllocaInst>(I);
2696 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
2697 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2698 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
2699 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2700 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2701, __PRETTY_FUNCTION__))
2701 "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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2701, __PRETTY_FUNCTION__))
;
2702 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2702, __PRETTY_FUNCTION__))
;
2703 AlignRecord |= AI.isUsedWithInAlloca() << 5;
2704 AlignRecord |= 1 << 6;
2705 AlignRecord |= AI.isSwiftError() << 7;
2706 Vals.push_back(AlignRecord);
2707 break;
2708 }
2709
2710 case Instruction::Load:
2711 if (cast<LoadInst>(I).isAtomic()) {
2712 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
2713 pushValueAndType(I.getOperand(0), InstID, Vals);
2714 } else {
2715 Code = bitc::FUNC_CODE_INST_LOAD;
2716 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
2717 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2718 }
2719 Vals.push_back(VE.getTypeID(I.getType()));
2720 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2721 Vals.push_back(cast<LoadInst>(I).isVolatile());
2722 if (cast<LoadInst>(I).isAtomic()) {
2723 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2724 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
2725 }
2726 break;
2727 case Instruction::Store:
2728 if (cast<StoreInst>(I).isAtomic())
2729 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2730 else
2731 Code = bitc::FUNC_CODE_INST_STORE;
2732 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2733 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
2734 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2735 Vals.push_back(cast<StoreInst>(I).isVolatile());
2736 if (cast<StoreInst>(I).isAtomic()) {
2737 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2738 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
2739 }
2740 break;
2741 case Instruction::AtomicCmpXchg:
2742 Code = bitc::FUNC_CODE_INST_CMPXCHG;
2743 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2744 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2745 pushValue(I.getOperand(2), InstID, Vals); // newval.
2746 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
2747 Vals.push_back(
2748 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2749 Vals.push_back(
2750 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2751 Vals.push_back(
2752 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
2753 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
2754 break;
2755 case Instruction::AtomicRMW:
2756 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
2757 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2758 pushValue(I.getOperand(1), InstID, Vals); // val.
2759 Vals.push_back(
2760 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
2761 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
2762 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2763 Vals.push_back(
2764 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
2765 break;
2766 case Instruction::Fence:
2767 Code = bitc::FUNC_CODE_INST_FENCE;
2768 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2769 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
2770 break;
2771 case Instruction::Call: {
2772 const CallInst &CI = cast<CallInst>(I);
2773 FunctionType *FTy = CI.getFunctionType();
2774
2775 if (CI.hasOperandBundles())
2776 writeOperandBundles(&CI, InstID);
2777
2778 Code = bitc::FUNC_CODE_INST_CALL;
2779
2780 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
2781
2782 unsigned Flags = getOptimizationFlags(&I);
2783 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2784 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2785 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2786 1 << bitc::CALL_EXPLICIT_TYPE |
2787 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2788 unsigned(Flags != 0) << bitc::CALL_FMF);
2789 if (Flags != 0)
2790 Vals.push_back(Flags);
2791
2792 Vals.push_back(VE.getTypeID(FTy));
2793 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
2794
2795 // Emit value #'s for the fixed parameters.
2796 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2797 // Check for labels (can happen with asm labels).
2798 if (FTy->getParamType(i)->isLabelTy())
2799 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2800 else
2801 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
2802 }
2803
2804 // Emit type/value pairs for varargs params.
2805 if (FTy->isVarArg()) {
2806 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
2807 i != e; ++i)
2808 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
2809 }
2810 break;
2811 }
2812 case Instruction::VAArg:
2813 Code = bitc::FUNC_CODE_INST_VAARG;
2814 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
2815 pushValue(I.getOperand(0), InstID, Vals); // valist.
2816 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2817 break;
2818 }
2819
2820 Stream.EmitRecord(Code, Vals, AbbrevToUse);
2821 Vals.clear();
2822}
2823
2824/// Emit names for globals/functions etc. \p IsModuleLevel is true when
2825/// we are writing the module-level VST, where we are including a function
2826/// bitcode index and need to backpatch the VST forward declaration record.
2827void ModuleBitcodeWriter::writeValueSymbolTable(
2828 const ValueSymbolTable &VST, bool IsModuleLevel,
2829 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
2830 if (VST.empty()) {
1
Assuming the condition is false
2
Taking false branch
2831 // writeValueSymbolTableForwardDecl should have returned early as
2832 // well. Ensure this handling remains in sync by asserting that
2833 // the placeholder offset is not set.
2834 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder())((!IsModuleLevel || !hasVSTOffsetPlaceholder()) ? static_cast
<void> (0) : __assert_fail ("!IsModuleLevel || !hasVSTOffsetPlaceholder()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2834, __PRETTY_FUNCTION__))
;
2835 return;
2836 }
2837
2838 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
3
Assuming 'IsModuleLevel' is 0
2839 // Get the offset of the VST we are writing, and backpatch it into
2840 // the VST forward declaration record.
2841 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2842 // The BitcodeStartBit was the stream offset of the identification block.
2843 VSTOffset -= bitcodeStartBit();
2844 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2844, __PRETTY_FUNCTION__))
;
2845 // Note that we add 1 here because the offset is relative to one word
2846 // before the start of the identification block, which was historically
2847 // always the start of the regular bitcode header.
2848 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
2849 }
2850
2851 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2852
2853 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2854 // records, which are not used in the per-function VSTs.
2855 unsigned FnEntry8BitAbbrev;
4
'FnEntry8BitAbbrev' declared without an initial value
2856 unsigned FnEntry7BitAbbrev;
2857 unsigned FnEntry6BitAbbrev;
2858 unsigned GUIDEntryAbbrev;
2859 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
2860 // 8-bit fixed-width VST_CODE_FNENTRY function strings.
2861 auto Abbv = std::make_shared<BitCodeAbbrev>();
2862 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2865 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2866 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2867 FnEntry8BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2868
2869 // 7-bit fixed width VST_CODE_FNENTRY function strings.
2870 Abbv = std::make_shared<BitCodeAbbrev>();
2871 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2872 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2873 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2874 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2875 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2876 FnEntry7BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2877
2878 // 6-bit char6 VST_CODE_FNENTRY function strings.
2879 Abbv = std::make_shared<BitCodeAbbrev>();
2880 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2881 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2882 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2883 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2884 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
2885 FnEntry6BitAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2886
2887 // FIXME: Change the name of this record as it is now used by
2888 // the per-module index as well.
2889 Abbv = std::make_shared<BitCodeAbbrev>();
2890 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2891 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2892 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2893 GUIDEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2894 }
2895
2896 // FIXME: Set up the abbrev, we know how many values there are!
2897 // FIXME: We know if the type names can use 7-bit ascii.
2898 SmallVector<uint64_t, 64> NameVals;
2899
2900 for (const ValueName &Name : VST) {
2901 // Figure out the encoding to use for the name.
2902 StringEncoding Bits =
2903 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
2904
2905 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
2906 NameVals.push_back(VE.getValueID(Name.getValue()));
2907
2908 Function *F = dyn_cast<Function>(Name.getValue());
2909 if (!F) {
5
Taking true branch
12
Taking true branch
19
Taking true branch
24
Assuming 'F' is non-null
25
Taking false branch
2910 // If value is an alias, need to get the aliased base object to
2911 // see if it is a function.
2912 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2913 if (GA && GA->getBaseObject())
2914 F = dyn_cast<Function>(GA->getBaseObject());
2915 }
2916
2917 // VST_CODE_ENTRY: [valueid, namechar x N]
2918 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2919 // VST_CODE_BBENTRY: [bbid, namechar x N]
2920 unsigned Code;
2921 if (isa<BasicBlock>(Name.getValue())) {
6
Taking false branch
13
Taking false branch
20
Taking true branch
26
Taking false branch
2922 Code = bitc::VST_CODE_BBENTRY;
2923 if (Bits == SE_Char6)
21
Assuming 'Bits' is not equal to SE_Char6
22
Taking false branch
2924 AbbrevToUse = VST_BBENTRY_6_ABBREV;
2925 } else if (F && !F->isDeclaration()) {
27
Assuming the condition is true
28
Taking true branch
2926 // Must be the module-level VST, where we pass in the Index and
2927 // have a VSTOffsetPlaceholder. The function-level VST should not
2928 // contain any Function symbols.
2929 assert(FunctionToBitcodeIndex)((FunctionToBitcodeIndex) ? static_cast<void> (0) : __assert_fail
("FunctionToBitcodeIndex", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2929, __PRETTY_FUNCTION__))
;
2930 assert(hasVSTOffsetPlaceholder())((hasVSTOffsetPlaceholder()) ? static_cast<void> (0) : __assert_fail
("hasVSTOffsetPlaceholder()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2930, __PRETTY_FUNCTION__))
;
2931
2932 // Save the word offset of the function (from the start of the
2933 // actual bitcode written to the stream).
2934 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
2935 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2935, __PRETTY_FUNCTION__))
;
2936 // Note that we add 1 here because the offset is relative to one word
2937 // before the start of the identification block, which was historically
2938 // always the start of the regular bitcode header.
2939 NameVals.push_back(BitcodeIndex / 32 + 1);
2940
2941 Code = bitc::VST_CODE_FNENTRY;
2942 AbbrevToUse = FnEntry8BitAbbrev;
29
Assigned value is garbage or undefined
2943 if (Bits == SE_Char6)
2944 AbbrevToUse = FnEntry6BitAbbrev;
2945 else if (Bits == SE_Fixed7)
2946 AbbrevToUse = FnEntry7BitAbbrev;
2947 } else {
2948 Code = bitc::VST_CODE_ENTRY;
2949 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
2950 AbbrevToUse = VST_ENTRY_6_ABBREV;
2951 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
2952 AbbrevToUse = VST_ENTRY_7_ABBREV;
2953 }
2954
2955 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'
2956 NameVals.push_back((unsigned char)P);
2957
2958 // Emit the finished record.
2959 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
2960 NameVals.clear();
2961 }
2962 // Emit any GUID valueIDs created for indirect call edges into the
2963 // module-level VST.
2964 if (IsModuleLevel && hasVSTOffsetPlaceholder())
2965 for (const auto &GI : valueIds()) {
2966 NameVals.push_back(GI.second);
2967 NameVals.push_back(GI.first);
2968 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals,
2969 GUIDEntryAbbrev);
2970 NameVals.clear();
2971 }
2972 Stream.ExitBlock();
2973}
2974
2975/// Emit function names and summary offsets for the combined index
2976/// used by ThinLTO.
2977void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2978 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2978, __PRETTY_FUNCTION__))
;
2979 // Get the offset of the VST we are writing, and backpatch it into
2980 // the VST forward declaration record.
2981 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2982 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 2982, __PRETTY_FUNCTION__))
;
2983 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
2984
2985 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2986
2987 auto Abbv = std::make_shared<BitCodeAbbrev>();
2988 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
2991 unsigned EntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2992
2993 SmallVector<uint64_t, 64> NameVals;
2994 for (const auto &GVI : valueIds()) {
2995 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2996 NameVals.push_back(GVI.second);
2997 NameVals.push_back(GVI.first);
2998
2999 // Emit the finished record.
3000 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
3001 NameVals.clear();
3002 }
3003 Stream.ExitBlock();
3004}
3005
3006void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3007 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3007, __PRETTY_FUNCTION__))
;
3008 unsigned Code;
3009 if (isa<BasicBlock>(Order.V))
3010 Code = bitc::USELIST_CODE_BB;
3011 else
3012 Code = bitc::USELIST_CODE_DEFAULT;
3013
3014 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3015 Record.push_back(VE.getValueID(Order.V));
3016 Stream.EmitRecord(Code, Record);
3017}
3018
3019void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3020 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3021, __PRETTY_FUNCTION__))
3021 "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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3021, __PRETTY_FUNCTION__))
;
3022
3023 auto hasMore = [&]() {
3024 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3025 };
3026 if (!hasMore())
3027 // Nothing to do.
3028 return;
3029
3030 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3031 while (hasMore()) {
3032 writeUseList(std::move(VE.UseListOrders.back()));
3033 VE.UseListOrders.pop_back();
3034 }
3035 Stream.ExitBlock();
3036}
3037
3038/// Emit a function body to the module stream.
3039void ModuleBitcodeWriter::writeFunction(
3040 const Function &F,
3041 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3042 // Save the bitcode index of the start of this function block for recording
3043 // in the VST.
3044 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3045
3046 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3047 VE.incorporateFunction(F);
3048
3049 SmallVector<unsigned, 64> Vals;
3050
3051 // Emit the number of basic blocks, so the reader can create them ahead of
3052 // time.
3053 Vals.push_back(VE.getBasicBlocks().size());
3054 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3055 Vals.clear();
3056
3057 // If there are function-local constants, emit them now.
3058 unsigned CstStart, CstEnd;
3059 VE.getFunctionConstantRange(CstStart, CstEnd);
3060 writeConstants(CstStart, CstEnd, false);
3061
3062 // If there is function-local metadata, emit it now.
3063 writeFunctionMetadata(F);
3064
3065 // Keep a running idea of what the instruction ID is.
3066 unsigned InstID = CstEnd;
3067
3068 bool NeedsMetadataAttachment = F.hasMetadata();
3069
3070 DILocation *LastDL = nullptr;
3071 // Finally, emit all the instructions, in order.
3072 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3073 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3074 I != E; ++I) {
3075 writeInstruction(*I, InstID, Vals);
3076
3077 if (!I->getType()->isVoidTy())
3078 ++InstID;
3079
3080 // If the instruction has metadata, write a metadata attachment later.
3081 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
3082
3083 // If the instruction has a debug location, emit it.
3084 DILocation *DL = I->getDebugLoc();
3085 if (!DL)
3086 continue;
3087
3088 if (DL == LastDL) {
3089 // Just repeat the same debug loc as last time.
3090 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3091 continue;
3092 }
3093
3094 Vals.push_back(DL->getLine());
3095 Vals.push_back(DL->getColumn());
3096 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3097 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3098 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3099 Vals.clear();
3100
3101 LastDL = DL;
3102 }
3103
3104 // Emit names for all the instructions etc.
3105 if (auto *Symtab = F.getValueSymbolTable())
3106 writeValueSymbolTable(*Symtab);
3107
3108 if (NeedsMetadataAttachment)
3109 writeFunctionMetadataAttachment(F);
3110 if (VE.shouldPreserveUseListOrder())
3111 writeUseListBlock(&F);
3112 VE.purgeFunction();
3113 Stream.ExitBlock();
3114}
3115
3116// Emit blockinfo, which defines the standard abbreviations etc.
3117void ModuleBitcodeWriter::writeBlockInfo() {
3118 // We only want to emit block info records for blocks that have multiple
3119 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3120 // Other blocks can define their abbrevs inline.
3121 Stream.EnterBlockInfoBlock();
3122
3123 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3124 auto Abbv = std::make_shared<BitCodeAbbrev>();
3125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3129 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3130 VST_ENTRY_8_ABBREV)
3131 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3131)
;
3132 }
3133
3134 { // 7-bit fixed width VST_CODE_ENTRY strings.
3135 auto Abbv = std::make_shared<BitCodeAbbrev>();
3136 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3137 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3140 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3141 VST_ENTRY_7_ABBREV)
3142 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3142)
;
3143 }
3144 { // 6-bit char6 VST_CODE_ENTRY strings.
3145 auto Abbv = std::make_shared<BitCodeAbbrev>();
3146 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3150 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3151 VST_ENTRY_6_ABBREV)
3152 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3152)
;
3153 }
3154 { // 6-bit char6 VST_CODE_BBENTRY strings.
3155 auto Abbv = std::make_shared<BitCodeAbbrev>();
3156 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3160 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3161 VST_BBENTRY_6_ABBREV)
3162 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3162)
;
3163 }
3164
3165
3166
3167 { // SETTYPE abbrev for CONSTANTS_BLOCK.
3168 auto Abbv = std::make_shared<BitCodeAbbrev>();
3169 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
3171 VE.computeBitsRequiredForTypeIndicies()));
3172 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3173 CONSTANTS_SETTYPE_ABBREV)
3174 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3174)
;
3175 }
3176
3177 { // INTEGER abbrev for CONSTANTS_BLOCK.
3178 auto Abbv = std::make_shared<BitCodeAbbrev>();
3179 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3181 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3182 CONSTANTS_INTEGER_ABBREV)
3183 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3183)
;
3184 }
3185
3186 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3187 auto Abbv = std::make_shared<BitCodeAbbrev>();
3188 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3191 VE.computeBitsRequiredForTypeIndicies()));
3192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3193
3194 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3195 CONSTANTS_CE_CAST_Abbrev)
3196 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3196)
;
3197 }
3198 { // NULL abbrev for CONSTANTS_BLOCK.
3199 auto Abbv = std::make_shared<BitCodeAbbrev>();
3200 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
3201 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3202 CONSTANTS_NULL_Abbrev)
3203 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3203)
;
3204 }
3205
3206 // FIXME: This should only use space for first class types!
3207
3208 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3209 auto Abbv = std::make_shared<BitCodeAbbrev>();
3210 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
3211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3212 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3213 VE.computeBitsRequiredForTypeIndicies()));
3214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3215 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3216 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3217 FUNCTION_INST_LOAD_ABBREV)
3218 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3218)
;
3219 }
3220 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3221 auto Abbv = std::make_shared<BitCodeAbbrev>();
3222 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3226 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3227 FUNCTION_INST_BINOP_ABBREV)
3228 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3228)
;
3229 }
3230 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3231 auto Abbv = std::make_shared<BitCodeAbbrev>();
3232 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
3237 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3238 FUNCTION_INST_BINOP_FLAGS_ABBREV)
3239 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3239)
;
3240 }
3241 { // INST_CAST abbrev for FUNCTION_BLOCK.
3242 auto Abbv = std::make_shared<BitCodeAbbrev>();
3243 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3246 VE.computeBitsRequiredForTypeIndicies()));
3247 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3248 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3249 FUNCTION_INST_CAST_ABBREV)
3250 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3250)
;
3251 }
3252
3253 { // INST_RET abbrev for FUNCTION_BLOCK.
3254 auto Abbv = std::make_shared<BitCodeAbbrev>();
3255 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3256 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3257 FUNCTION_INST_RET_VOID_ABBREV)
3258 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 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 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3264 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3265 FUNCTION_INST_RET_VAL_ABBREV)
3266 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3266)
;
3267 }
3268 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3269 auto Abbv = std::make_shared<BitCodeAbbrev>();
3270 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
3271 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3272 FUNCTION_INST_UNREACHABLE_ABBREV)
3273 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3273)
;
3274 }
3275 {
3276 auto Abbv = std::make_shared<BitCodeAbbrev>();
3277 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3279 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3280 Log2_32_Ceil(VE.getTypes().size() + 1)));
3281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3283 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3284 FUNCTION_INST_GEP_ABBREV)
3285 llvm_unreachable("Unexpected abbrev ordering!")::llvm::llvm_unreachable_internal("Unexpected abbrev ordering!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3285)
;
3286 }
3287
3288 Stream.ExitBlock();
3289}
3290
3291/// Write the module path strings, currently only used when generating
3292/// a combined index file.
3293void IndexBitcodeWriter::writeModStrings() {
3294 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3295
3296 // TODO: See which abbrev sizes we actually need to emit
3297
3298 // 8-bit fixed-width MST_ENTRY strings.
3299 auto Abbv = std::make_shared<BitCodeAbbrev>();
3300 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3304 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3305
3306 // 7-bit fixed width MST_ENTRY strings.
3307 Abbv = std::make_shared<BitCodeAbbrev>();
3308 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3312 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3313
3314 // 6-bit char6 MST_ENTRY strings.
3315 Abbv = std::make_shared<BitCodeAbbrev>();
3316 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3320 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3321
3322 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3323 Abbv = std::make_shared<BitCodeAbbrev>();
3324 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3330 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3331
3332 SmallVector<unsigned, 64> Vals;
3333 for (const auto &MPSE : Index.modulePaths()) {
3334 if (!doIncludeModule(MPSE.getKey()))
3335 continue;
3336 StringEncoding Bits =
3337 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3338 unsigned AbbrevToUse = Abbrev8Bit;
3339 if (Bits == SE_Char6)
3340 AbbrevToUse = Abbrev6Bit;
3341 else if (Bits == SE_Fixed7)
3342 AbbrevToUse = Abbrev7Bit;
3343
3344 Vals.push_back(MPSE.getValue().first);
3345
3346 for (const auto P : MPSE.getKey())
3347 Vals.push_back((unsigned char)P);
3348
3349 // Emit the finished record.
3350 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3351
3352 Vals.clear();
3353 // Emit an optional hash for the module now
3354 auto &Hash = MPSE.getValue().second;
3355 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3356 for (auto Val : Hash) {
3357 if (Val)
3358 AllZero = false;
3359 Vals.push_back(Val);
3360 }
3361 if (!AllZero) {
3362 // Emit the hash record.
3363 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3364 }
3365
3366 Vals.clear();
3367 }
3368 Stream.ExitBlock();
3369}
3370
3371/// Write the function type metadata related records that need to appear before
3372/// a function summary entry (whether per-module or combined).
3373static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3374 FunctionSummary *FS) {
3375 if (!FS->type_tests().empty())
3376 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3377
3378 SmallVector<uint64_t, 64> Record;
3379
3380 auto WriteVFuncIdVec = [&](uint64_t Ty,
3381 ArrayRef<FunctionSummary::VFuncId> VFs) {
3382 if (VFs.empty())
3383 return;
3384 Record.clear();
3385 for (auto &VF : VFs) {
3386 Record.push_back(VF.GUID);
3387 Record.push_back(VF.Offset);
3388 }
3389 Stream.EmitRecord(Ty, Record);
3390 };
3391
3392 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3393 FS->type_test_assume_vcalls());
3394 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3395 FS->type_checked_load_vcalls());
3396
3397 auto WriteConstVCallVec = [&](uint64_t Ty,
3398 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3399 for (auto &VC : VCs) {
3400 Record.clear();
3401 Record.push_back(VC.VFunc.GUID);
3402 Record.push_back(VC.VFunc.Offset);
3403 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3404 Stream.EmitRecord(Ty, Record);
3405 }
3406 };
3407
3408 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3409 FS->type_test_assume_const_vcalls());
3410 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3411 FS->type_checked_load_const_vcalls());
3412}
3413
3414// Helper to emit a single function summary record.
3415void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
3416 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3417 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3418 const Function &F) {
3419 NameVals.push_back(ValueID);
3420
3421 FunctionSummary *FS = cast<FunctionSummary>(Summary);
3422 writeFunctionTypeMetadataRecords(Stream, FS);
3423
3424 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3425 NameVals.push_back(FS->instCount());
3426 NameVals.push_back(FS->refs().size());
3427
3428 for (auto &RI : FS->refs())
3429 NameVals.push_back(VE.getValueID(RI.getValue()));
3430
3431 bool HasProfileData = F.getEntryCount().hasValue();
3432 for (auto &ECI : FS->calls()) {
3433 NameVals.push_back(getValueId(ECI.first));
3434 if (HasProfileData)
3435 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3436 }
3437
3438 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3439 unsigned Code =
3440 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
3441
3442 // Emit the finished record.
3443 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3444 NameVals.clear();
3445}
3446
3447// Collect the global value references in the given variable's initializer,
3448// and emit them in a summary record.
3449void ModuleBitcodeWriter::writeModuleLevelReferences(
3450 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3451 unsigned FSModRefsAbbrev) {
3452 auto Summaries =
3453 Index->findGlobalValueSummaryList(GlobalValue::getGUID(V.getName()));
3454 if (Summaries == Index->end()) {
3455 // Only declarations should not have a summary (a declaration might however
3456 // have a summary if the def was in module level asm).
3457 assert(V.isDeclaration())((V.isDeclaration()) ? static_cast<void> (0) : __assert_fail
("V.isDeclaration()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3457, __PRETTY_FUNCTION__))
;
3458 return;
3459 }
3460 auto *Summary = Summaries->second.front().get();
3461 NameVals.push_back(VE.getValueID(&V));
3462 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3463 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3464
3465 unsigned SizeBeforeRefs = NameVals.size();
3466 for (auto &RI : VS->refs())
3467 NameVals.push_back(VE.getValueID(RI.getValue()));
3468 // Sort the refs for determinism output, the vector returned by FS->refs() has
3469 // been initialized from a DenseSet.
3470 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
3471
3472 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3473 FSModRefsAbbrev);
3474 NameVals.clear();
3475}
3476
3477// Current version for the summary.
3478// This is bumped whenever we introduce changes in the way some record are
3479// interpreted, like flags for instance.
3480static const uint64_t INDEX_VERSION = 3;
3481
3482/// Emit the per-module summary section alongside the rest of
3483/// the module's bitcode.
3484void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
3485 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
3486
3487 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3488
3489 if (Index->begin() == Index->end()) {
3490 Stream.ExitBlock();
3491 return;
3492 }
3493
3494 // Abbrev for FS_PERMODULE.
3495 auto Abbv = std::make_shared<BitCodeAbbrev>();
3496 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3499 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3500 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3501 // numrefs x valueid, n x (valueid)
3502 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3503 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3504 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3505
3506 // Abbrev for FS_PERMODULE_PROFILE.
3507 Abbv = std::make_shared<BitCodeAbbrev>();
3508 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3509 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3510 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3511 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3512 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3513 // numrefs x valueid, n x (valueid, hotness)
3514 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3515 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3516 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3517
3518 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3519 Abbv = std::make_shared<BitCodeAbbrev>();
3520 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3521 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3522 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3523 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3524 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3525 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3526
3527 // Abbrev for FS_ALIAS.
3528 Abbv = std::make_shared<BitCodeAbbrev>();
3529 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3530 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3531 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3532 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3533 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3534
3535 SmallVector<uint64_t, 64> NameVals;
3536 // Iterate over the list of functions instead of the Index to
3537 // ensure the ordering is stable.
3538 for (const Function &F : M) {
3539 // Summary emission does not support anonymous functions, they have to
3540 // renamed using the anonymous function renaming pass.
3541 if (!F.hasName())
3542 report_fatal_error("Unexpected anonymous function when writing summary");
3543
3544 auto Summaries =
3545 Index->findGlobalValueSummaryList(GlobalValue::getGUID(F.getName()));
3546 if (Summaries == Index->end()) {
3547 // Only declarations should not have a summary (a declaration might
3548 // however have a summary if the def was in module level asm).
3549 assert(F.isDeclaration())((F.isDeclaration()) ? static_cast<void> (0) : __assert_fail
("F.isDeclaration()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3549, __PRETTY_FUNCTION__))
;
3550 continue;
3551 }
3552 auto *Summary = Summaries->second.front().get();
3553 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3554 FSCallsAbbrev, FSCallsProfileAbbrev, F);
3555 }
3556
3557 // Capture references from GlobalVariable initializers, which are outside
3558 // of a function scope.
3559 for (const GlobalVariable &G : M.globals())
3560 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
3561
3562 for (const GlobalAlias &A : M.aliases()) {
3563 auto *Aliasee = A.getBaseObject();
3564 if (!Aliasee->hasName())
3565 // Nameless function don't have an entry in the summary, skip it.
3566 continue;
3567 auto AliasId = VE.getValueID(&A);
3568 auto AliaseeId = VE.getValueID(Aliasee);
3569 NameVals.push_back(AliasId);
3570 auto *Summary = Index->getGlobalValueSummary(A);
3571 AliasSummary *AS = cast<AliasSummary>(Summary);
3572 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3573 NameVals.push_back(AliaseeId);
3574 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
3575 NameVals.clear();
3576 }
3577
3578 Stream.ExitBlock();
3579}
3580
3581/// Emit the combined summary section into the combined index file.
3582void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
3583 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
3584 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3585
3586 // Abbrev for FS_COMBINED.
3587 auto Abbv = std::make_shared<BitCodeAbbrev>();
3588 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
3589 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3590 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3591 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3594 // numrefs x valueid, n x (valueid)
3595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3596 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3597 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3598
3599 // Abbrev for FS_COMBINED_PROFILE.
3600 Abbv = std::make_shared<BitCodeAbbrev>();
3601 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
3602 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3603 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3604 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3605 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3606 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3607 // numrefs x valueid, n x (valueid, hotness)
3608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3610 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3611
3612 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3613 Abbv = std::make_shared<BitCodeAbbrev>();
3614 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
3615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3618 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3619 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3620 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3621
3622 // Abbrev for FS_COMBINED_ALIAS.
3623 Abbv = std::make_shared<BitCodeAbbrev>();
3624 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
3625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3626 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
3627 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3628 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3629 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3630
3631 // The aliases are emitted as a post-pass, and will point to the value
3632 // id of the aliasee. Save them in a vector for post-processing.
3633 SmallVector<AliasSummary *, 64> Aliases;
3634
3635 // Save the value id for each summary for alias emission.
3636 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3637
3638 SmallVector<uint64_t, 64> NameVals;
3639
3640 // For local linkage, we also emit the original name separately
3641 // immediately after the record.
3642 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3643 if (!GlobalValue::isLocalLinkage(S.linkage()))
3644 return;
3645 NameVals.push_back(S.getOriginalName());
3646 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3647 NameVals.clear();
3648 };
3649
3650 for (const auto &I : *this) {
3651 GlobalValueSummary *S = I.second;
3652 assert(S)((S) ? static_cast<void> (0) : __assert_fail ("S", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3652, __PRETTY_FUNCTION__))
;
3653
3654 assert(hasValueId(I.first))((hasValueId(I.first)) ? static_cast<void> (0) : __assert_fail
("hasValueId(I.first)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3654, __PRETTY_FUNCTION__))
;
3655 unsigned ValueId = getValueId(I.first);
3656 SummaryToValueIdMap[S] = ValueId;
3657
3658 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3659 // Will process aliases as a post-pass because the reader wants all
3660 // global to be loaded first.
3661 Aliases.push_back(AS);
3662 continue;
3663 }
3664
3665 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
3666 NameVals.push_back(ValueId);
3667 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3668 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3669 for (auto &RI : VS->refs()) {
3670 NameVals.push_back(getValueId(RI.getGUID()));
3671 }
3672
3673 // Emit the finished record.
3674 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3675 FSModRefsAbbrev);
3676 NameVals.clear();
3677 MaybeEmitOriginalName(*S);
3678 continue;
3679 }
3680
3681 auto *FS = cast<FunctionSummary>(S);
3682 writeFunctionTypeMetadataRecords(Stream, FS);
3683
3684 NameVals.push_back(ValueId);
3685 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3686 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3687 NameVals.push_back(FS->instCount());
3688 NameVals.push_back(FS->refs().size());
3689
3690 for (auto &RI : FS->refs()) {
3691 NameVals.push_back(getValueId(RI.getGUID()));
3692 }
3693
3694 bool HasProfileData = false;
3695 for (auto &EI : FS->calls()) {
3696 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
3697 if (HasProfileData)
3698 break;
3699 }
3700
3701 for (auto &EI : FS->calls()) {
3702 // If this GUID doesn't have a value id, it doesn't have a function
3703 // summary and we don't need to record any calls to it.
3704 if (!hasValueId(EI.first.getGUID()))
3705 continue;
3706 NameVals.push_back(getValueId(EI.first.getGUID()));
3707 if (HasProfileData)
3708 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
3709 }
3710
3711 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3712 unsigned Code =
3713 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3714
3715 // Emit the finished record.
3716 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3717 NameVals.clear();
3718 MaybeEmitOriginalName(*S);
3719 }
3720
3721 for (auto *AS : Aliases) {
3722 auto AliasValueId = SummaryToValueIdMap[AS];
3723 assert(AliasValueId)((AliasValueId) ? static_cast<void> (0) : __assert_fail
("AliasValueId", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3723, __PRETTY_FUNCTION__))
;
3724 NameVals.push_back(AliasValueId);
3725 NameVals.push_back(Index.getModuleId(AS->modulePath()));
3726 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
3727 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3728 assert(AliaseeValueId)((AliaseeValueId) ? static_cast<void> (0) : __assert_fail
("AliaseeValueId", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3728, __PRETTY_FUNCTION__))
;
3729 NameVals.push_back(AliaseeValueId);
3730
3731 // Emit the finished record.
3732 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
3733 NameVals.clear();
3734 MaybeEmitOriginalName(*AS);
3735 }
3736
3737 Stream.ExitBlock();
3738}
3739
3740/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3741/// current llvm version, and a record for the epoch number.
3742static void writeIdentificationBlock(BitstreamWriter &Stream) {
3743 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
3744
3745 // Write the "user readable" string identifying the bitcode producer
3746 auto Abbv = std::make_shared<BitCodeAbbrev>();
3747 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
3750 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3751 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
3752 "LLVM" LLVM_VERSION_STRING"5.0.0", StringAbbrev);
3753
3754 // Write the epoch version
3755 Abbv = std::make_shared<BitCodeAbbrev>();
3756 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3758 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3759 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
3760 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3761 Stream.ExitBlock();
3762}
3763
3764void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
3765 // Emit the module's hash.
3766 // MODULE_CODE_HASH: [5*i32]
3767 SHA1 Hasher;
3768 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3769 Buffer.size() - BlockStartPos));
3770 StringRef Hash = Hasher.result();
3771 uint32_t Vals[5];
3772 for (int Pos = 0; Pos < 20; Pos += 4) {
3773 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3774 }
3775
3776 // Emit the finished record.
3777 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3778}
3779
3780void ModuleBitcodeWriter::write() {
3781 writeIdentificationBlock(Stream);
3782
3783 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3784 size_t BlockStartPos = Buffer.size();
3785
3786 SmallVector<unsigned, 1> Vals;
3787 unsigned CurVersion = 1;
3788 Vals.push_back(CurVersion);
3789 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3790
3791 // Emit blockinfo, which defines the standard abbreviations etc.
3792 writeBlockInfo();
3793
3794 // Emit information about attribute groups.
3795 writeAttributeGroupTable();
3796
3797 // Emit information about parameter attributes.
3798 writeAttributeTable();
3799
3800 // Emit information describing all of the types in the module.
3801 writeTypeTable();
3802
3803 writeComdats();
3804
3805 // Emit top-level description of module, including target triple, inline asm,
3806 // descriptors for global variables, and function prototype info.
3807 writeModuleInfo();
3808
3809 // Emit constants.
3810 writeModuleConstants();
3811
3812 // Emit metadata kind names.
3813 writeModuleMetadataKinds();
3814
3815 // Emit metadata.
3816 writeModuleMetadata();
3817
3818 // Emit module-level use-lists.
3819 if (VE.shouldPreserveUseListOrder())
3820 writeUseListBlock(nullptr);
3821
3822 writeOperandBundleTags();
3823
3824 // Emit function bodies.
3825 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
3826 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
3827 if (!F->isDeclaration())
3828 writeFunction(*F, FunctionToBitcodeIndex);
3829
3830 // Need to write after the above call to WriteFunction which populates
3831 // the summary information in the index.
3832 if (Index)
3833 writePerModuleGlobalValueSummary();
3834
3835 writeValueSymbolTable(M.getValueSymbolTable(),
3836 /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
3837
3838 if (GenerateHash) {
3839 writeModuleHash(BlockStartPos);
3840 }
3841
3842 Stream.ExitBlock();
3843}
3844
3845static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3846 uint32_t &Position) {
3847 support::endian::write32le(&Buffer[Position], Value);
3848 Position += 4;
3849}
3850
3851/// If generating a bc file on darwin, we have to emit a
3852/// header and trailer to make it compatible with the system archiver. To do
3853/// this we emit the following header, and then emit a trailer that pads the
3854/// file out to be a multiple of 16 bytes.
3855///
3856/// struct bc_header {
3857/// uint32_t Magic; // 0x0B17C0DE
3858/// uint32_t Version; // Version, currently always 0.
3859/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3860/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3861/// uint32_t CPUType; // CPU specifier.
3862/// ... potentially more later ...
3863/// };
3864static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
3865 const Triple &TT) {
3866 unsigned CPUType = ~0U;
3867
3868 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
3869 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3870 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3871 // specific constants here because they are implicitly part of the Darwin ABI.
3872 enum {
3873 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3874 DARWIN_CPU_TYPE_X86 = 7,
3875 DARWIN_CPU_TYPE_ARM = 12,
3876 DARWIN_CPU_TYPE_POWERPC = 18
3877 };
3878
3879 Triple::ArchType Arch = TT.getArch();
3880 if (Arch == Triple::x86_64)
3881 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
3882 else if (Arch == Triple::x86)
3883 CPUType = DARWIN_CPU_TYPE_X86;
3884 else if (Arch == Triple::ppc)
3885 CPUType = DARWIN_CPU_TYPE_POWERPC;
3886 else if (Arch == Triple::ppc64)
3887 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
3888 else if (Arch == Triple::arm || Arch == Triple::thumb)
3889 CPUType = DARWIN_CPU_TYPE_ARM;
3890
3891 // Traditional Bitcode starts after header.
3892 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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3893, __PRETTY_FUNCTION__))
3893 "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~svn296300/lib/Bitcode/Writer/BitcodeWriter.cpp"
, 3893, __PRETTY_FUNCTION__))
;
3894 unsigned BCOffset = BWH_HeaderSize;
3895 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
3896
3897 // Write the magic and version.
3898 unsigned Position = 0;
3899 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3900 writeInt32ToBuffer(0, Buffer, Position); // Version.
3901 writeInt32ToBuffer(BCOffset, Buffer, Position);
3902 writeInt32ToBuffer(BCSize, Buffer, Position);
3903 writeInt32ToBuffer(CPUType, Buffer, Position);
3904
3905 // If the file is not a multiple of 16 bytes, insert dummy padding.
3906 while (Buffer.size() & 15)
3907 Buffer.push_back(0);
3908}
3909
3910/// Helper to write the header common to all bitcode files.
3911static void writeBitcodeHeader(BitstreamWriter &Stream) {
3912 // Emit the file header.
3913 Stream.Emit((unsigned)'B', 8);
3914 Stream.Emit((unsigned)'C', 8);
3915 Stream.Emit(0x0, 4);
3916 Stream.Emit(0xC, 4);
3917 Stream.Emit(0xE, 4);
3918 Stream.Emit(0xD, 4);
3919}
3920
3921BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3922 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3923 writeBitcodeHeader(*Stream);
3924}
3925
3926BitcodeWriter::~BitcodeWriter() = default;
3927
3928void BitcodeWriter::writeModule(const Module *M,
3929 bool ShouldPreserveUseListOrder,
3930 const ModuleSummaryIndex *Index,
3931 bool GenerateHash) {
3932 ModuleBitcodeWriter ModuleWriter(
3933 M, Buffer, *Stream, ShouldPreserveUseListOrder, Index, GenerateHash);
3934 ModuleWriter.write();
3935}
3936
3937/// WriteBitcodeToFile - Write the specified module to the specified output
3938/// stream.
3939void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
3940 bool ShouldPreserveUseListOrder,
3941 const ModuleSummaryIndex *Index,
3942 bool GenerateHash) {
3943 SmallVector<char, 0> Buffer;
3944 Buffer.reserve(256*1024);
3945
3946 // If this is darwin or another generic macho target, reserve space for the
3947 // header.
3948 Triple TT(M->getTargetTriple());
3949 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3950 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
3951
3952 BitcodeWriter Writer(Buffer);
3953 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash);
3954
3955 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
3956 emitDarwinBCHeaderAndTrailer(Buffer, TT);
3957
3958 // Write the generated bitstream to "Out".
3959 Out.write((char*)&Buffer.front(), Buffer.size());
3960}
3961
3962void IndexBitcodeWriter::write() {
3963 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3964
3965 SmallVector<unsigned, 1> Vals;
3966 unsigned CurVersion = 1;
3967 Vals.push_back(CurVersion);
3968 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
3969
3970 // If we have a VST, write the VSTOFFSET record placeholder.
3971 writeValueSymbolTableForwardDecl();
3972
3973 // Write the module paths in the combined index.
3974 writeModStrings();
3975
3976 // Write the summary combined index records.
3977 writeCombinedGlobalValueSummary();
3978
3979 // Need a special VST writer for the combined index (we don't have a
3980 // real VST and real values when this is invoked).
3981 writeCombinedValueSymbolTable();
3982
3983 Stream.ExitBlock();
3984}
3985
3986// Write the specified module summary index to the given raw output stream,
3987// where it will be written in a new bitcode block. This is used when
3988// writing the combined index file for ThinLTO. When writing a subset of the
3989// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3990void llvm::WriteIndexToFile(
3991 const ModuleSummaryIndex &Index, raw_ostream &Out,
3992 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3993 SmallVector<char, 0> Buffer;
3994 Buffer.reserve(256 * 1024);
3995
3996 BitstreamWriter Stream(Buffer);
3997 writeBitcodeHeader(Stream);
3998
3999 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
4000 IndexWriter.write();
4001
4002 Out.write((char *)&Buffer.front(), Buffer.size());
4003}