blob: 64d3bd90dac998b838afe278a5ad869c1fe6a84f [file] [log] [blame]
Chris Lattner87351e22007-04-29 05:31:57 +00001//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
Chris Lattnerc1d10d62007-04-22 06:24:45 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "ValueEnumerator.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000015#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Triple.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000017#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000018#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000019#include "llvm/Bitcode/ReaderWriter.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000020#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000029#include "llvm/IR/UseListOrder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000032#include "llvm/Support/MathExtras.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000033#include "llvm/Support/Program.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000034#include "llvm/Support/SHA1.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000035#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000036#include <cctype>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000037#include <map>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000038using namespace llvm;
39
Chris Lattner4d925982007-05-04 20:52:02 +000040/// These are manifest constants used by the bitcode writer. They do not need to
41/// be kept in sync with the reader, but need to be consistent within this file.
42enum {
Chris Lattner4d925982007-05-04 20:52:02 +000043 // VALUE_SYMTAB_BLOCK abbrev id's.
44 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000045 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +000046 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +000047 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000048
Chris Lattnerda5e5d22007-05-05 07:36:14 +000049 // CONSTANTS_BLOCK abbrev id's.
50 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
51 CONSTANTS_INTEGER_ABBREV,
52 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +000053 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000054
Chris Lattnerb80751d2007-05-05 07:44:49 +000055 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +000056 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000057 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +000058 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000059 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +000060 FUNCTION_INST_RET_VOID_ABBREV,
61 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +000062 FUNCTION_INST_UNREACHABLE_ABBREV,
63 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +000064};
65
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000066/// Abstract class to manage the bitcode writing, subclassed for each bitcode
67/// file type. Owns the BitstreamWriter, and includes the main entry point for
Teresa Johnson37687f32016-04-23 04:30:47 +000068/// writing.
69class BitcodeWriter {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000070protected:
Teresa Johnson37687f32016-04-23 04:30:47 +000071 /// Pointer to the buffer allocated by caller for bitcode writing.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000072 const SmallVectorImpl<char> &Buffer;
Teresa Johnson37687f32016-04-23 04:30:47 +000073
74 /// The stream created and owned by the BitodeWriter.
75 BitstreamWriter Stream;
76
77 /// Saves the offset of the VSTOffset record that must eventually be
78 /// backpatched with the offset of the actual VST.
79 uint64_t VSTOffsetPlaceholder = 0;
80
81public:
82 /// Constructs a BitcodeWriter object, and initializes a BitstreamRecord,
83 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000084 BitcodeWriter(SmallVectorImpl<char> &Buffer)
85 : Buffer(Buffer), Stream(Buffer) {}
Teresa Johnson37687f32016-04-23 04:30:47 +000086
87 virtual ~BitcodeWriter() = default;
88
89 /// Main entry point to write the bitcode file, which writes the bitcode
90 /// header and will then invoke the virtual writeBlocks() method.
91 void write();
92
93private:
94 /// Derived classes must implement this to write the corresponding blocks for
95 /// that bitcode file type.
96 virtual void writeBlocks() = 0;
97
98protected:
99 bool hasVSTOffsetPlaceholder() { return VSTOffsetPlaceholder != 0; }
Teresa Johnson37687f32016-04-23 04:30:47 +0000100 void writeValueSymbolTableForwardDecl();
101 void writeBitcodeHeader();
102};
103
104/// Class to manage the bitcode writing for a module.
105class ModuleBitcodeWriter : public BitcodeWriter {
106 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000107 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000108
109 /// Enumerates ids for all values in the module.
110 ValueEnumerator VE;
111
112 /// Optional per-module index to write for ThinLTO.
113 const ModuleSummaryIndex *Index;
114
115 /// True if a module hash record should be written.
116 bool GenerateHash;
117
118 /// The start bit of the module block, for use in generating a module hash
119 uint64_t BitcodeStartBit = 0;
120
121public:
122 /// Constructs a ModuleBitcodeWriter object for the given Module,
123 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000124 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
Teresa Johnson37687f32016-04-23 04:30:47 +0000125 bool ShouldPreserveUseListOrder,
126 const ModuleSummaryIndex *Index, bool GenerateHash)
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000127 : BitcodeWriter(Buffer), M(*M), VE(*M, ShouldPreserveUseListOrder),
Teresa Johnson37687f32016-04-23 04:30:47 +0000128 Index(Index), GenerateHash(GenerateHash) {
129 // Save the start bit of the actual bitcode, in case there is space
130 // saved at the start for the darwin header above. The reader stream
131 // will start at the bitcode, and we need the offset of the VST
132 // to line up.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000133 BitcodeStartBit = Stream.GetCurrentBitNo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000134 }
135
136private:
137 /// Main entry point for writing a module to bitcode, invoked by
138 /// BitcodeWriter::write() after it writes the header.
139 void writeBlocks() override;
140
141 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
142 /// current llvm version, and a record for the epoch number.
143 void writeIdentificationBlock();
144
145 /// Emit the current module to the bitstream.
146 void writeModule();
147
148 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
149
150 void writeStringRecord(unsigned Code, StringRef Str, unsigned AbbrevToUse);
151 void writeAttributeGroupTable();
152 void writeAttributeTable();
153 void writeTypeTable();
154 void writeComdats();
155 void writeModuleInfo();
156 void writeValueAsMetadata(const ValueAsMetadata *MD,
157 SmallVectorImpl<uint64_t> &Record);
158 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
159 unsigned Abbrev);
160 unsigned createDILocationAbbrev();
161 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
162 unsigned &Abbrev);
163 unsigned createGenericDINodeAbbrev();
164 void writeGenericDINode(const GenericDINode *N,
165 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
166 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
167 unsigned Abbrev);
168 void writeDIEnumerator(const DIEnumerator *N,
169 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
170 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
171 unsigned Abbrev);
172 void writeDIDerivedType(const DIDerivedType *N,
173 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
174 void writeDICompositeType(const DICompositeType *N,
175 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
176 void writeDISubroutineType(const DISubroutineType *N,
177 SmallVectorImpl<uint64_t> &Record,
178 unsigned Abbrev);
179 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
180 unsigned Abbrev);
181 void writeDICompileUnit(const DICompileUnit *N,
182 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
183 void writeDISubprogram(const DISubprogram *N,
184 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
185 void writeDILexicalBlock(const DILexicalBlock *N,
186 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
187 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
188 SmallVectorImpl<uint64_t> &Record,
189 unsigned Abbrev);
190 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
191 unsigned Abbrev);
192 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
193 unsigned Abbrev);
194 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
195 unsigned Abbrev);
196 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
197 unsigned Abbrev);
198 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
199 SmallVectorImpl<uint64_t> &Record,
200 unsigned Abbrev);
201 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
202 SmallVectorImpl<uint64_t> &Record,
203 unsigned Abbrev);
204 void writeDIGlobalVariable(const DIGlobalVariable *N,
205 SmallVectorImpl<uint64_t> &Record,
206 unsigned Abbrev);
207 void writeDILocalVariable(const DILocalVariable *N,
208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
209 void writeDIExpression(const DIExpression *N,
210 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
211 void writeDIObjCProperty(const DIObjCProperty *N,
212 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
213 void writeDIImportedEntity(const DIImportedEntity *N,
214 SmallVectorImpl<uint64_t> &Record,
215 unsigned Abbrev);
216 unsigned createNamedMetadataAbbrev();
217 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
218 unsigned createMetadataStringsAbbrev();
219 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
220 SmallVectorImpl<uint64_t> &Record);
221 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
222 SmallVectorImpl<uint64_t> &Record);
223 void writeModuleMetadata();
224 void writeFunctionMetadata(const Function &F);
225 void writeMetadataAttachment(const Function &F);
226 void writeModuleMetadataStore();
227 void writeOperandBundleTags();
228 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
229 void writeModuleConstants();
230 bool pushValueAndType(const Value *V, unsigned InstID,
231 SmallVectorImpl<unsigned> &Vals);
232 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
233 void pushValue(const Value *V, unsigned InstID,
234 SmallVectorImpl<unsigned> &Vals);
235 void pushValueSigned(const Value *V, unsigned InstID,
236 SmallVectorImpl<uint64_t> &Vals);
237 void writeInstruction(const Instruction &I, unsigned InstID,
238 SmallVectorImpl<unsigned> &Vals);
239 void writeValueSymbolTable(
240 const ValueSymbolTable &VST, bool IsModuleLevel = false,
241 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr);
242 void writeUseList(UseListOrder &&Order);
243 void writeUseListBlock(const Function *F);
244 void
245 writeFunction(const Function &F,
246 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
247 void writeBlockInfo();
248 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000249 GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +0000250 unsigned ValueID,
251 unsigned FSCallsAbbrev,
252 unsigned FSCallsProfileAbbrev,
253 const Function &F);
254 void writeModuleLevelReferences(const GlobalVariable &V,
255 SmallVector<uint64_t, 64> &NameVals,
256 unsigned FSModRefsAbbrev);
257 void writePerModuleGlobalValueSummary();
258 void writeModuleHash(size_t BlockStartPos);
259};
260
261/// Class to manage the bitcode writing for a combined index.
262class IndexBitcodeWriter : public BitcodeWriter {
263 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000264 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000265
Teresa Johnson84174c32016-05-10 13:48:23 +0000266 /// When writing a subset of the index for distributed backends, client
267 /// provides a map of modules to the corresponding GUIDs/summaries to write.
268 std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
269
Teresa Johnson37687f32016-04-23 04:30:47 +0000270 /// Map that holds the correspondence between the GUID used in the combined
271 /// index and a value id generated by this class to use in references.
272 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
273
274 /// Tracks the last value id recorded in the GUIDToValueMap.
275 unsigned GlobalValueId = 0;
276
277public:
278 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000279 /// writing to the provided \p Buffer. When writing a subset of the index
280 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000281 IndexBitcodeWriter(SmallVectorImpl<char> &Buffer,
Teresa Johnson84174c32016-05-10 13:48:23 +0000282 const ModuleSummaryIndex &Index,
283 std::map<std::string, GVSummaryMapTy>
284 *ModuleToSummariesForIndex = nullptr)
285 : BitcodeWriter(Buffer), Index(Index),
286 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
287 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000288 // in writing out the call graph edges. Save the mapping from GUID
289 // to the new global value id to use when writing those edges, which
290 // are currently saved in the index in terms of GUID.
Teresa Johnson84174c32016-05-10 13:48:23 +0000291 for (const auto &I : *this)
292 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Teresa Johnson37687f32016-04-23 04:30:47 +0000293 }
294
Teresa Johnson84174c32016-05-10 13:48:23 +0000295 /// The below iterator returns the GUID and associated summary.
296 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
297
298 /// Iterator over the value GUID and summaries to be written to bitcode,
299 /// hides the details of whether they are being pulled from the entire
300 /// index or just those in a provided ModuleToSummariesForIndex map.
301 class iterator
302 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
303 GVInfo> {
304 /// Enables access to parent class.
305 const IndexBitcodeWriter &Writer;
306
307 // Iterators used when writing only those summaries in a provided
308 // ModuleToSummariesForIndex map:
309
310 /// Points to the last element in outer ModuleToSummariesForIndex map.
311 std::map<std::string, GVSummaryMapTy>::iterator ModuleSummariesBack;
312 /// Iterator on outer ModuleToSummariesForIndex map.
313 std::map<std::string, GVSummaryMapTy>::iterator ModuleSummariesIter;
314 /// Iterator on an inner global variable summary map.
315 GVSummaryMapTy::iterator ModuleGVSummariesIter;
316
317 // Iterators used when writing all summaries in the index:
318
319 /// Points to the last element in the Index outer GlobalValueMap.
320 const_gvsummary_iterator IndexSummariesBack;
321 /// Iterator on outer GlobalValueMap.
322 const_gvsummary_iterator IndexSummariesIter;
323 /// Iterator on an inner GlobalValueSummaryList.
324 GlobalValueSummaryList::const_iterator IndexGVSummariesIter;
325
326 public:
327 /// Construct iterator from parent \p Writer and indicate if we are
328 /// constructing the end iterator.
329 iterator(const IndexBitcodeWriter &Writer, bool IsAtEnd) : Writer(Writer) {
330 // Set up the appropriate set of iterators given whether we are writing
331 // the full index or just a subset.
332 // Can't setup the Back or inner iterators if the corresponding map
333 // is empty. This will be handled specially in operator== as well.
334 if (Writer.ModuleToSummariesForIndex &&
335 !Writer.ModuleToSummariesForIndex->empty()) {
336 ModuleSummariesIter = Writer.ModuleToSummariesForIndex->begin();
337 for (ModuleSummariesBack = Writer.ModuleToSummariesForIndex->begin();
338 std::next(ModuleSummariesBack) !=
339 Writer.ModuleToSummariesForIndex->end();
340 ModuleSummariesBack++)
341 ;
342 ModuleGVSummariesIter = !IsAtEnd ? ModuleSummariesIter->second.begin()
343 : ModuleSummariesBack->second.end();
344 } else if (!Writer.ModuleToSummariesForIndex &&
345 Writer.Index.begin() != Writer.Index.end()) {
346 IndexSummariesIter = Writer.Index.begin();
347 for (IndexSummariesBack = Writer.Index.begin();
348 std::next(IndexSummariesBack) != Writer.Index.end();
349 IndexSummariesBack++)
350 ;
351 IndexGVSummariesIter = !IsAtEnd ? IndexSummariesIter->second.begin()
352 : IndexSummariesBack->second.end();
353 }
354 }
355
356 /// Increment the appropriate set of iterators.
357 iterator &operator++() {
358 // First the inner iterator is incremented, then if it is at the end
359 // and there are more outer iterations to go, the inner is reset to
360 // the start of the next inner list.
361 if (Writer.ModuleToSummariesForIndex) {
362 ++ModuleGVSummariesIter;
363 if (ModuleGVSummariesIter == ModuleSummariesIter->second.end() &&
364 ModuleSummariesIter != ModuleSummariesBack) {
365 ++ModuleSummariesIter;
366 ModuleGVSummariesIter = ModuleSummariesIter->second.begin();
367 }
368 } else {
369 ++IndexGVSummariesIter;
370 if (IndexGVSummariesIter == IndexSummariesIter->second.end() &&
371 IndexSummariesIter != IndexSummariesBack) {
372 ++IndexSummariesIter;
373 IndexGVSummariesIter = IndexSummariesIter->second.begin();
374 }
375 }
376 return *this;
377 }
378
379 /// Access the <GUID,GlobalValueSummary*> pair corresponding to the current
380 /// outer and inner iterator positions.
381 GVInfo operator*() {
382 if (Writer.ModuleToSummariesForIndex)
383 return std::make_pair(ModuleGVSummariesIter->first,
384 ModuleGVSummariesIter->second);
385 return std::make_pair(IndexSummariesIter->first,
386 IndexGVSummariesIter->get());
387 }
388
389 /// Checks if the iterators are equal, with special handling for empty
390 /// indexes.
391 bool operator==(const iterator &RHS) const {
392 if (Writer.ModuleToSummariesForIndex) {
393 // First ensure that both are writing the same subset.
394 if (Writer.ModuleToSummariesForIndex !=
395 RHS.Writer.ModuleToSummariesForIndex)
396 return false;
397 // Already determined above that maps are the same, so if one is
398 // empty, they both are.
399 if (Writer.ModuleToSummariesForIndex->empty())
400 return true;
401 return ModuleGVSummariesIter == RHS.ModuleGVSummariesIter;
402 }
403 // First ensure RHS also writing the full index, and that both are
404 // writing the same full index.
405 if (RHS.Writer.ModuleToSummariesForIndex ||
406 &Writer.Index != &RHS.Writer.Index)
407 return false;
408 // Already determined above that maps are the same, so if one is
409 // empty, they both are.
410 if (Writer.Index.begin() == Writer.Index.end())
411 return true;
412 return IndexGVSummariesIter == RHS.IndexGVSummariesIter;
413 }
414 };
415
416 /// Obtain the start iterator over the summaries to be written.
417 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
418 /// Obtain the end iterator over the summaries to be written.
419 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
420
Teresa Johnson37687f32016-04-23 04:30:47 +0000421private:
422 /// Main entry point for writing a combined index to bitcode, invoked by
423 /// BitcodeWriter::write() after it writes the header.
424 void writeBlocks() override;
425
426 void writeIndex();
427 void writeModStrings();
428 void writeCombinedValueSymbolTable();
429 void writeCombinedGlobalValueSummary();
430
Teresa Johnson84174c32016-05-10 13:48:23 +0000431 /// Indicates whether the provided \p ModulePath should be written into
432 /// the module string table, e.g. if full index written or if it is in
433 /// the provided subset.
434 bool doIncludeModule(StringRef ModulePath) {
435 return !ModuleToSummariesForIndex ||
436 ModuleToSummariesForIndex->count(ModulePath);
437 }
438
Teresa Johnson37687f32016-04-23 04:30:47 +0000439 bool hasValueId(GlobalValue::GUID ValGUID) {
440 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
441 return VMI != GUIDToValueIdMap.end();
442 }
443 unsigned getValueId(GlobalValue::GUID ValGUID) {
444 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
445 // If this GUID doesn't have an entry, assign one.
446 if (VMI == GUIDToValueIdMap.end()) {
447 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
448 return GlobalValueId;
449 } else {
450 return VMI->second;
451 }
452 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000453 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
454};
455
456static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000457 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000458 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000459 case Instruction::Trunc : return bitc::CAST_TRUNC;
460 case Instruction::ZExt : return bitc::CAST_ZEXT;
461 case Instruction::SExt : return bitc::CAST_SEXT;
462 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
463 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
464 case Instruction::UIToFP : return bitc::CAST_UITOFP;
465 case Instruction::SIToFP : return bitc::CAST_SITOFP;
466 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
467 case Instruction::FPExt : return bitc::CAST_FPEXT;
468 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
469 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
470 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000471 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000472 }
473}
474
Teresa Johnson37687f32016-04-23 04:30:47 +0000475static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000476 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000477 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000478 case Instruction::Add:
479 case Instruction::FAdd: return bitc::BINOP_ADD;
480 case Instruction::Sub:
481 case Instruction::FSub: return bitc::BINOP_SUB;
482 case Instruction::Mul:
483 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000484 case Instruction::UDiv: return bitc::BINOP_UDIV;
485 case Instruction::FDiv:
486 case Instruction::SDiv: return bitc::BINOP_SDIV;
487 case Instruction::URem: return bitc::BINOP_UREM;
488 case Instruction::FRem:
489 case Instruction::SRem: return bitc::BINOP_SREM;
490 case Instruction::Shl: return bitc::BINOP_SHL;
491 case Instruction::LShr: return bitc::BINOP_LSHR;
492 case Instruction::AShr: return bitc::BINOP_ASHR;
493 case Instruction::And: return bitc::BINOP_AND;
494 case Instruction::Or: return bitc::BINOP_OR;
495 case Instruction::Xor: return bitc::BINOP_XOR;
496 }
497}
498
Teresa Johnson37687f32016-04-23 04:30:47 +0000499static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000500 switch (Op) {
501 default: llvm_unreachable("Unknown RMW operation!");
502 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
503 case AtomicRMWInst::Add: return bitc::RMW_ADD;
504 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
505 case AtomicRMWInst::And: return bitc::RMW_AND;
506 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
507 case AtomicRMWInst::Or: return bitc::RMW_OR;
508 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
509 case AtomicRMWInst::Max: return bitc::RMW_MAX;
510 case AtomicRMWInst::Min: return bitc::RMW_MIN;
511 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
512 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
513 }
514}
515
Teresa Johnson37687f32016-04-23 04:30:47 +0000516static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000517 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000518 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
519 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
520 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
521 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
522 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
523 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
524 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000525 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000526 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000527}
528
Teresa Johnson37687f32016-04-23 04:30:47 +0000529static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000530 switch (SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000531 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
532 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
533 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000534 llvm_unreachable("Invalid synch scope");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000535}
536
Teresa Johnson37687f32016-04-23 04:30:47 +0000537void ModuleBitcodeWriter::writeStringRecord(unsigned Code, StringRef Str,
538 unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000539 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000540
Chris Lattnere14cb882007-05-04 19:11:41 +0000541 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000542 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
543 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
544 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000545 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000546 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000547
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000548 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000549 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000550}
551
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000552static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
553 switch (Kind) {
554 case Attribute::Alignment:
555 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000556 case Attribute::AllocSize:
557 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000558 case Attribute::AlwaysInline:
559 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000560 case Attribute::ArgMemOnly:
561 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000562 case Attribute::Builtin:
563 return bitc::ATTR_KIND_BUILTIN;
564 case Attribute::ByVal:
565 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000566 case Attribute::Convergent:
567 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000568 case Attribute::InAlloca:
569 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000570 case Attribute::Cold:
571 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000572 case Attribute::InaccessibleMemOnly:
573 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
574 case Attribute::InaccessibleMemOrArgMemOnly:
575 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000576 case Attribute::InlineHint:
577 return bitc::ATTR_KIND_INLINE_HINT;
578 case Attribute::InReg:
579 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000580 case Attribute::JumpTable:
581 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000582 case Attribute::MinSize:
583 return bitc::ATTR_KIND_MIN_SIZE;
584 case Attribute::Naked:
585 return bitc::ATTR_KIND_NAKED;
586 case Attribute::Nest:
587 return bitc::ATTR_KIND_NEST;
588 case Attribute::NoAlias:
589 return bitc::ATTR_KIND_NO_ALIAS;
590 case Attribute::NoBuiltin:
591 return bitc::ATTR_KIND_NO_BUILTIN;
592 case Attribute::NoCapture:
593 return bitc::ATTR_KIND_NO_CAPTURE;
594 case Attribute::NoDuplicate:
595 return bitc::ATTR_KIND_NO_DUPLICATE;
596 case Attribute::NoImplicitFloat:
597 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
598 case Attribute::NoInline:
599 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000600 case Attribute::NoRecurse:
601 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000602 case Attribute::NonLazyBind:
603 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000604 case Attribute::NonNull:
605 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000606 case Attribute::Dereferenceable:
607 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000608 case Attribute::DereferenceableOrNull:
609 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000610 case Attribute::NoRedZone:
611 return bitc::ATTR_KIND_NO_RED_ZONE;
612 case Attribute::NoReturn:
613 return bitc::ATTR_KIND_NO_RETURN;
614 case Attribute::NoUnwind:
615 return bitc::ATTR_KIND_NO_UNWIND;
616 case Attribute::OptimizeForSize:
617 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000618 case Attribute::OptimizeNone:
619 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000620 case Attribute::ReadNone:
621 return bitc::ATTR_KIND_READ_NONE;
622 case Attribute::ReadOnly:
623 return bitc::ATTR_KIND_READ_ONLY;
624 case Attribute::Returned:
625 return bitc::ATTR_KIND_RETURNED;
626 case Attribute::ReturnsTwice:
627 return bitc::ATTR_KIND_RETURNS_TWICE;
628 case Attribute::SExt:
629 return bitc::ATTR_KIND_S_EXT;
630 case Attribute::StackAlignment:
631 return bitc::ATTR_KIND_STACK_ALIGNMENT;
632 case Attribute::StackProtect:
633 return bitc::ATTR_KIND_STACK_PROTECT;
634 case Attribute::StackProtectReq:
635 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
636 case Attribute::StackProtectStrong:
637 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000638 case Attribute::SafeStack:
639 return bitc::ATTR_KIND_SAFESTACK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000640 case Attribute::StructRet:
641 return bitc::ATTR_KIND_STRUCT_RET;
642 case Attribute::SanitizeAddress:
643 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
644 case Attribute::SanitizeThread:
645 return bitc::ATTR_KIND_SANITIZE_THREAD;
646 case Attribute::SanitizeMemory:
647 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000648 case Attribute::SwiftError:
649 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000650 case Attribute::SwiftSelf:
651 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000652 case Attribute::UWTable:
653 return bitc::ATTR_KIND_UW_TABLE;
654 case Attribute::ZExt:
655 return bitc::ATTR_KIND_Z_EXT;
656 case Attribute::EndAttrKinds:
657 llvm_unreachable("Can not encode end-attribute kinds marker.");
658 case Attribute::None:
659 llvm_unreachable("Can not encode none-attribute.");
660 }
661
662 llvm_unreachable("Trying to encode unknown attribute");
663}
664
Teresa Johnson37687f32016-04-23 04:30:47 +0000665void ModuleBitcodeWriter::writeAttributeGroupTable() {
Bill Wendling92ed7002013-02-11 22:33:26 +0000666 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
667 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000668
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000669 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000670
671 SmallVector<uint64_t, 64> Record;
Bill Wendling92ed7002013-02-11 22:33:26 +0000672 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
673 AttributeSet AS = AttrGrps[i];
Bill Wendlingdc095552013-02-10 23:09:32 +0000674 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
675 AttributeSet A = AS.getSlotAttributes(i);
676
Bill Wendling92ed7002013-02-11 22:33:26 +0000677 Record.push_back(VE.getAttributeGroupID(A));
Bill Wendlingdc095552013-02-10 23:09:32 +0000678 Record.push_back(AS.getSlotIndex(i));
679
680 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
681 I != E; ++I) {
682 Attribute Attr = *I;
683 if (Attr.isEnumAttribute()) {
684 Record.push_back(0);
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000685 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
Hal Finkele15442c2014-07-18 06:51:55 +0000686 } else if (Attr.isIntAttribute()) {
Bill Wendlingdc095552013-02-10 23:09:32 +0000687 Record.push_back(1);
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000688 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
Bill Wendlingdc095552013-02-10 23:09:32 +0000689 Record.push_back(Attr.getValueAsInt());
690 } else {
691 StringRef Kind = Attr.getKindAsString();
692 StringRef Val = Attr.getValueAsString();
693
694 Record.push_back(Val.empty() ? 3 : 4);
695 Record.append(Kind.begin(), Kind.end());
696 Record.push_back(0);
697 if (!Val.empty()) {
698 Record.append(Val.begin(), Val.end());
699 Record.push_back(0);
700 }
701 }
702 }
703
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000704 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
Bill Wendlingdc095552013-02-10 23:09:32 +0000705 Record.clear();
706 }
707 }
708
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000709 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000710}
711
Teresa Johnson37687f32016-04-23 04:30:47 +0000712void ModuleBitcodeWriter::writeAttributeTable() {
Bill Wendlinge94d8432012-12-07 23:16:57 +0000713 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000714 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000715
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000716 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000717
718 SmallVector<uint64_t, 64> Record;
719 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Bill Wendlinge94d8432012-12-07 23:16:57 +0000720 const AttributeSet &A = Attrs[i];
Bill Wendling0dc08912013-02-12 08:13:50 +0000721 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
722 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000724 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000725 Record.clear();
726 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000727
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000728 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000729}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000730
731/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000732void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000733 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000734
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000735 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000736 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
David Blaikie7b028102015-02-25 00:51:52 +0000738 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000739
Chris Lattnerccee7062007-05-05 06:30:12 +0000740 // Abbrev for TYPE_CODE_POINTER.
741 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
742 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000744 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000745 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000746
Chris Lattnerccee7062007-05-05 06:30:12 +0000747 // Abbrev for TYPE_CODE_FUNCTION.
748 Abbv = new BitCodeAbbrev();
749 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
750 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
753
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000754 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000756 // Abbrev for TYPE_CODE_STRUCT_ANON.
Chris Lattnerccee7062007-05-05 06:30:12 +0000757 Abbv = new BitCodeAbbrev();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000758 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
762
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000763 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000764
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000765 // Abbrev for TYPE_CODE_STRUCT_NAME.
766 Abbv = new BitCodeAbbrev();
767 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000770 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000771
772 // Abbrev for TYPE_CODE_STRUCT_NAMED.
773 Abbv = new BitCodeAbbrev();
774 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
775 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
778
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000779 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000780
Chris Lattnerccee7062007-05-05 06:30:12 +0000781 // Abbrev for TYPE_CODE_ARRAY.
782 Abbv = new BitCodeAbbrev();
783 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
786
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000787 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000788
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000789 // Emit an entry count so the reader can reserve space.
790 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000791 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000792 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000793
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000794 // Loop over all of the types, emitting each in turn.
795 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000796 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000797 int AbbrevToUse = 0;
798 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000799
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000800 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000801 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
802 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
803 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
804 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
805 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
806 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000807 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000808 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
809 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
810 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000811 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000812 case Type::IntegerTyID:
813 // INTEGER: [width]
814 Code = bitc::TYPE_CODE_INTEGER;
815 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
816 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000817 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000818 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000819 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000820 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000821 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000822 unsigned AddressSpace = PTy->getAddressSpace();
823 TypeVals.push_back(AddressSpace);
824 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000825 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000826 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000827 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000828 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000829 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000830 Code = bitc::TYPE_CODE_FUNCTION;
831 TypeVals.push_back(FT->isVarArg());
832 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000833 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
834 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000835 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000836 break;
837 }
838 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000839 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000840 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000841 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000842 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000843 for (StructType::element_iterator I = ST->element_begin(),
844 E = ST->element_end(); I != E; ++I)
845 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000846
Chris Lattner335d3992011-08-12 18:06:37 +0000847 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000848 Code = bitc::TYPE_CODE_STRUCT_ANON;
849 AbbrevToUse = StructAnonAbbrev;
850 } else {
851 if (ST->isOpaque()) {
852 Code = bitc::TYPE_CODE_OPAQUE;
853 } else {
854 Code = bitc::TYPE_CODE_STRUCT_NAMED;
855 AbbrevToUse = StructNamedAbbrev;
856 }
857
858 // Emit the name if it is present.
859 if (!ST->getName().empty())
Teresa Johnson37687f32016-04-23 04:30:47 +0000860 writeStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
861 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000862 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000863 break;
864 }
865 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000866 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000867 // ARRAY: [numelts, eltty]
868 Code = bitc::TYPE_CODE_ARRAY;
869 TypeVals.push_back(AT->getNumElements());
870 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000871 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000872 break;
873 }
874 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000875 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000876 // VECTOR [numelts, eltty]
877 Code = bitc::TYPE_CODE_VECTOR;
878 TypeVals.push_back(VT->getNumElements());
879 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
880 break;
881 }
882 }
883
884 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000885 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000886 TypeVals.clear();
887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000888
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000889 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000890}
891
Teresa Johnson5e22e442016-02-06 16:07:35 +0000892static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
893 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000894 case GlobalValue::ExternalLinkage:
895 return 0;
896 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000897 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000898 case GlobalValue::AppendingLinkage:
899 return 2;
900 case GlobalValue::InternalLinkage:
901 return 3;
902 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000903 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000904 case GlobalValue::ExternalWeakLinkage:
905 return 7;
906 case GlobalValue::CommonLinkage:
907 return 8;
908 case GlobalValue::PrivateLinkage:
909 return 9;
910 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000911 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000912 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000913 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000914 case GlobalValue::AvailableExternallyLinkage:
915 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000916 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000917 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000918}
919
Teresa Johnson5e22e442016-02-06 16:07:35 +0000920static unsigned getEncodedLinkage(const GlobalValue &GV) {
921 return getEncodedLinkage(GV.getLinkage());
922}
923
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000924// Decode the flags for GlobalValue in the summary
925static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
926 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000927
928 RawFlags |= Flags.HasSection; // bool
929
930 // Linkage don't need to be remapped at that time for the summary. Any future
931 // change to the getEncodedLinkage() function will need to be taken into
932 // account here as well.
933 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
934
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000935 return RawFlags;
936}
937
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000938static unsigned getEncodedVisibility(const GlobalValue &GV) {
939 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000940 case GlobalValue::DefaultVisibility: return 0;
941 case GlobalValue::HiddenVisibility: return 1;
942 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000943 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000944 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000945}
946
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000947static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
948 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000949 case GlobalValue::DefaultStorageClass: return 0;
950 case GlobalValue::DLLImportStorageClass: return 1;
951 case GlobalValue::DLLExportStorageClass: return 2;
952 }
953 llvm_unreachable("Invalid DLL storage class");
954}
955
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000956static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000957 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000958 case GlobalVariable::NotThreadLocal: return 0;
959 case GlobalVariable::GeneralDynamicTLSModel: return 1;
960 case GlobalVariable::LocalDynamicTLSModel: return 2;
961 case GlobalVariable::InitialExecTLSModel: return 3;
962 case GlobalVariable::LocalExecTLSModel: return 4;
963 }
964 llvm_unreachable("Invalid TLS model");
965}
966
David Majnemerdad0a642014-06-27 18:19:56 +0000967static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
968 switch (C.getSelectionKind()) {
969 case Comdat::Any:
970 return bitc::COMDAT_SELECTION_KIND_ANY;
971 case Comdat::ExactMatch:
972 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
973 case Comdat::Largest:
974 return bitc::COMDAT_SELECTION_KIND_LARGEST;
975 case Comdat::NoDuplicates:
976 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
977 case Comdat::SameSize:
978 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
979 }
980 llvm_unreachable("Invalid selection kind");
981}
982
Teresa Johnson37687f32016-04-23 04:30:47 +0000983void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +0000984 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +0000985 for (const Comdat *C : VE.getComdats()) {
986 // COMDAT: [selection_kind, name]
987 Vals.push_back(getEncodedComdatSelectionKind(*C));
Rafael Espindola4e74d3b2015-01-14 18:25:45 +0000988 size_t Size = C->getName().size();
David Majnemer90a021f2016-03-13 08:01:03 +0000989 assert(isUInt<32>(Size));
Rafael Espindola4e74d3b2015-01-14 18:25:45 +0000990 Vals.push_back(Size);
David Majnemerdad0a642014-06-27 18:19:56 +0000991 for (char Chr : C->getName())
992 Vals.push_back((unsigned char)Chr);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000993 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +0000994 Vals.clear();
995 }
996}
997
Teresa Johnsonff642b92015-09-17 20:12:00 +0000998/// Write a record that will eventually hold the word offset of the
999/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001000/// after the real VST is written. Saves the bit offset to backpatch.
1001void BitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001002 // Write a placeholder value in for the offset of the real VST,
1003 // which is written after the function blocks so that it can include
1004 // the offset of each function. The placeholder offset will be
1005 // updated when the real VST is written.
1006 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1007 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1008 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1009 // hold the real VST offset. Must use fixed instead of VBR as we don't
1010 // know how many VBR chunks to reserve ahead of time.
1011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001012 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001013
1014 // Emit the placeholder
1015 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001016 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001017
Teresa Johnson37687f32016-04-23 04:30:47 +00001018 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001019 // patched when the real VST is written. We can simply subtract the 32-bit
1020 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001021 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001022}
1023
Teresa Johnsone1164de2016-02-10 21:55:02 +00001024enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1025
1026/// Determine the encoding to use for the given string name and length.
1027static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
1028 bool isChar6 = true;
1029 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
1030 if (isChar6)
1031 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1032 if ((unsigned char)*C & 128)
1033 // don't bother scanning the rest.
1034 return SE_Fixed8;
1035 }
1036 if (isChar6)
1037 return SE_Char6;
1038 else
1039 return SE_Fixed7;
1040}
1041
Teresa Johnsonff642b92015-09-17 20:12:00 +00001042/// Emit top-level description of module, including target triple, inline asm,
1043/// descriptors for global variables, and function prototype info.
1044/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001045void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001046 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001047 if (!M.getTargetTriple().empty())
1048 writeStringRecord(bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001049 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001050 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001051 if (!DL.empty())
Teresa Johnson37687f32016-04-23 04:30:47 +00001052 writeStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001053 if (!M.getModuleInlineAsm().empty())
1054 writeStringRecord(bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001055 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001056
Gordon Henriksend930f912008-08-17 18:44:35 +00001057 // Emit information about sections and GC, computing how many there are. Also
1058 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001059 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001060 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001061 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001062 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001063 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001064 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001065 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001066 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001067 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001068 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001069 if (!Entry) {
Teresa Johnson37687f32016-04-23 04:30:47 +00001070 writeStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1071 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001072 Entry = SectionMap.size();
1073 }
1074 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001075 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001076 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001077 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1078 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001079 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001080 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001081 if (!Entry) {
Teresa Johnson37687f32016-04-23 04:30:47 +00001082 writeStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1083 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001084 Entry = SectionMap.size();
1085 }
1086 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001087 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001088 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001089 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001090 if (!Entry) {
Teresa Johnson37687f32016-04-23 04:30:47 +00001091 writeStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(), 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001092 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001093 }
1094 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001095 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001096
Chris Lattner4b00d922007-04-23 16:04:05 +00001097 // Emit abbrev for globals, now that we know # sections and max alignment.
1098 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001099 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001100 // Add an abbrev for common globals with no visibility or thread localness.
1101 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1102 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001103 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001104 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1106 //| explicitType << 1
1107 //| constant
1108 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1109 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1110 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001111 Abbv->Add(BitCodeAbbrevOp(0));
1112 else {
1113 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001115 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001116 }
1117 if (SectionMap.empty()) // Section.
1118 Abbv->Add(BitCodeAbbrevOp(0));
1119 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001121 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001122 // Don't bother emitting vis + thread local.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001123 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
Chris Lattner4b00d922007-04-23 16:04:05 +00001124 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001125
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001126 // Emit the global variable information.
1127 SmallVector<unsigned, 64> Vals;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001128 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001129 unsigned AbbrevToUse = 0;
1130
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001131 // GLOBALVAR: [type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001132 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001133 // unnamed_addr, externally_initialized, dllstorageclass,
1134 // comdat]
David Blaikie1a848da2015-04-27 19:58:56 +00001135 Vals.push_back(VE.getTypeID(GV.getValueType()));
1136 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001137 Vals.push_back(GV.isDeclaration() ? 0 :
1138 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001139 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001140 Vals.push_back(Log2_32(GV.getAlignment())+1);
1141 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1142 if (GV.isThreadLocal() ||
1143 GV.getVisibility() != GlobalValue::DefaultVisibility ||
1144 GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001145 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1146 GV.hasComdat()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001147 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001148 Vals.push_back(getEncodedThreadLocalMode(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001149 Vals.push_back(GV.hasUnnamedAddr());
1150 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001151 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001152 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Chris Lattner4b00d922007-04-23 16:04:05 +00001153 } else {
1154 AbbrevToUse = SimpleGVarAbbrev;
1155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001156
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001157 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001158 Vals.clear();
1159 }
1160
1161 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001162 for (const Function &F : M) {
Chad Rosier42ee1522011-12-07 23:57:55 +00001163 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001164 // section, visibility, gc, unnamed_addr, prologuedata,
David Majnemer7fddecc2015-06-17 20:52:32 +00001165 // dllstorageclass, comdat, prefixdata, personalityfn]
David Blaikie561a1572015-04-17 16:28:26 +00001166 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001167 Vals.push_back(F.getCallingConv());
1168 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001169 Vals.push_back(getEncodedLinkage(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001170 Vals.push_back(VE.getAttributeID(F.getAttributes()));
1171 Vals.push_back(Log2_32(F.getAlignment())+1);
1172 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001173 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001174 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1175 Vals.push_back(F.hasUnnamedAddr());
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001176 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1177 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001178 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001179 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001180 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1181 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001182 Vals.push_back(
1183 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001184
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001185 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001186 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001187 Vals.clear();
1188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001189
Chris Lattner44c17072007-04-26 02:46:40 +00001190 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001191 for (const GlobalAlias &A : M.aliases()) {
Chad Rosiera966c312011-12-08 00:11:31 +00001192 // ALIAS: [alias type, aliasee val#, linkage, visibility]
David Blaikie6a51dbd2015-09-17 22:18:59 +00001193 Vals.push_back(VE.getTypeID(A.getValueType()));
1194 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001195 Vals.push_back(VE.getValueID(A.getAliasee()));
1196 Vals.push_back(getEncodedLinkage(A));
1197 Vals.push_back(getEncodedVisibility(A));
1198 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001199 Vals.push_back(getEncodedThreadLocalMode(A));
1200 Vals.push_back(A.hasUnnamedAddr());
Chris Lattner44c17072007-04-26 02:46:40 +00001201 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001202 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001203 Vals.clear();
1204 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001205
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001206 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001207 for (const GlobalIFunc &I : M.ifuncs()) {
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001208 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
1209 Vals.push_back(VE.getTypeID(I.getValueType()));
1210 Vals.push_back(I.getType()->getAddressSpace());
1211 Vals.push_back(VE.getValueID(I.getResolver()));
1212 Vals.push_back(getEncodedLinkage(I));
1213 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001214 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001215 Vals.clear();
1216 }
1217
Teresa Johnsone1164de2016-02-10 21:55:02 +00001218 // Emit the module's source file name.
1219 {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001220 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1221 M.getSourceFileName().size());
Teresa Johnsone1164de2016-02-10 21:55:02 +00001222 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1223 if (Bits == SE_Char6)
1224 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1225 else if (Bits == SE_Fixed7)
1226 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1227
1228 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1229 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1230 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1232 Abbv->Add(AbbrevOpToUse);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001233 unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsone1164de2016-02-10 21:55:02 +00001234
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001235 for (const auto P : M.getSourceFileName())
Teresa Johnsone1164de2016-02-10 21:55:02 +00001236 Vals.push_back((unsigned char)P);
1237
1238 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001239 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
Teresa Johnsone1164de2016-02-10 21:55:02 +00001240 Vals.clear();
1241 }
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001242
Teresa Johnson37687f32016-04-23 04:30:47 +00001243 // If we have a VST, write the VSTOFFSET record placeholder.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001244 if (M.getValueSymbolTable().empty())
Teresa Johnson37687f32016-04-23 04:30:47 +00001245 return;
1246 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001247}
1248
Teresa Johnson37687f32016-04-23 04:30:47 +00001249static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001250 uint64_t Flags = 0;
1251
Sanjay Patelc00017d2014-10-15 17:45:13 +00001252 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001253 if (OBO->hasNoSignedWrap())
1254 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1255 if (OBO->hasNoUnsignedWrap())
1256 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001257 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001258 if (PEO->isExact())
1259 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001260 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001261 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001262 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001263 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001264 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001265 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001266 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001267 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001268 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001269 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001270 Flags |= FastMathFlags::AllowReciprocal;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001271 }
1272
1273 return Flags;
1274}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001275
Teresa Johnson37687f32016-04-23 04:30:47 +00001276void ModuleBitcodeWriter::writeValueAsMetadata(
1277 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001278 // Mimic an MDNode with a value as one operand.
1279 Value *V = MD->getValue();
1280 Record.push_back(VE.getTypeID(V->getType()));
1281 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001282 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001283 Record.clear();
1284}
1285
Teresa Johnson37687f32016-04-23 04:30:47 +00001286void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1287 SmallVectorImpl<uint64_t> &Record,
1288 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001289 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001290 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001291 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1292 "Unexpected function-local metadata");
1293 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001294 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001295 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1296 : bitc::METADATA_NODE,
1297 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001298 Record.clear();
1299}
Devang Patele059ba6e2009-07-23 01:07:34 +00001300
Teresa Johnson37687f32016-04-23 04:30:47 +00001301unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001302 // Assume the column is usually under 128, and always output the inlined-at
1303 // location (it's never more expensive than building an array size 1).
1304 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1305 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001311 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001312}
1313
Teresa Johnson37687f32016-04-23 04:30:47 +00001314void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1315 SmallVectorImpl<uint64_t> &Record,
1316 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001317 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001318 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001319
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001320 Record.push_back(N->isDistinct());
1321 Record.push_back(N->getLine());
1322 Record.push_back(N->getColumn());
1323 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001324 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001325
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001326 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001327 Record.clear();
1328}
1329
Teresa Johnson37687f32016-04-23 04:30:47 +00001330unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001331 // Assume the column is usually under 128, and always output the inlined-at
1332 // location (it's never more expensive than building an array size 1).
1333 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1334 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001341 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001342}
1343
Teresa Johnson37687f32016-04-23 04:30:47 +00001344void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1345 SmallVectorImpl<uint64_t> &Record,
1346 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001347 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001348 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001349
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001350 Record.push_back(N->isDistinct());
1351 Record.push_back(N->getTag());
1352 Record.push_back(0); // Per-tag version field; unused for now.
1353
1354 for (auto &I : N->operands())
1355 Record.push_back(VE.getMetadataOrNullID(I));
1356
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001357 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001358 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001359}
1360
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001361static uint64_t rotateSign(int64_t I) {
1362 uint64_t U = I;
1363 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001364}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001365
Teresa Johnson37687f32016-04-23 04:30:47 +00001366void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1367 SmallVectorImpl<uint64_t> &Record,
1368 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001369 Record.push_back(N->isDistinct());
1370 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001371 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001372
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001373 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001374 Record.clear();
1375}
1376
Teresa Johnson37687f32016-04-23 04:30:47 +00001377void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1378 SmallVectorImpl<uint64_t> &Record,
1379 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001380 Record.push_back(N->isDistinct());
1381 Record.push_back(rotateSign(N->getValue()));
1382 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1383
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001384 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001385 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001386}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001387
Teresa Johnson37687f32016-04-23 04:30:47 +00001388void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1389 SmallVectorImpl<uint64_t> &Record,
1390 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001391 Record.push_back(N->isDistinct());
1392 Record.push_back(N->getTag());
1393 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1394 Record.push_back(N->getSizeInBits());
1395 Record.push_back(N->getAlignInBits());
1396 Record.push_back(N->getEncoding());
1397
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001398 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001399 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001400}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001401
Teresa Johnson37687f32016-04-23 04:30:47 +00001402void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1403 SmallVectorImpl<uint64_t> &Record,
1404 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001405 Record.push_back(N->isDistinct());
1406 Record.push_back(N->getTag());
1407 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1408 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1409 Record.push_back(N->getLine());
1410 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001411 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001412 Record.push_back(N->getSizeInBits());
1413 Record.push_back(N->getAlignInBits());
1414 Record.push_back(N->getOffsetInBits());
1415 Record.push_back(N->getFlags());
1416 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1417
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001418 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001419 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001420}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001421
Teresa Johnson37687f32016-04-23 04:30:47 +00001422void ModuleBitcodeWriter::writeDICompositeType(
1423 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1424 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001425 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001426 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001427 Record.push_back(N->getTag());
1428 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1429 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1430 Record.push_back(N->getLine());
1431 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1432 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1433 Record.push_back(N->getSizeInBits());
1434 Record.push_back(N->getAlignInBits());
1435 Record.push_back(N->getOffsetInBits());
1436 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001437 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001438 Record.push_back(N->getRuntimeLang());
1439 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001440 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001441 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1442
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001443 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001444 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001445}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001446
Teresa Johnson37687f32016-04-23 04:30:47 +00001447void ModuleBitcodeWriter::writeDISubroutineType(
1448 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1449 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001450 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001451 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001452 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001453 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001454
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001455 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001456 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001457}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001458
Teresa Johnson37687f32016-04-23 04:30:47 +00001459void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1460 SmallVectorImpl<uint64_t> &Record,
1461 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001462 Record.push_back(N->isDistinct());
1463 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1464 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1465
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001466 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001467 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001468}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001469
Teresa Johnson37687f32016-04-23 04:30:47 +00001470void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1471 SmallVectorImpl<uint64_t> &Record,
1472 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001473 assert(N->isDistinct() && "Expected distinct compile units");
1474 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001475 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001476 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001477 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1478 Record.push_back(N->isOptimized());
1479 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1480 Record.push_back(N->getRuntimeVersion());
1481 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1482 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001483 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1484 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001485 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001486 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1487 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001488 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001489 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001490
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001491 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001492 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001493}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001494
Teresa Johnson37687f32016-04-23 04:30:47 +00001495void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1496 SmallVectorImpl<uint64_t> &Record,
1497 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001498 uint64_t HasUnitFlag = 1 << 1;
1499 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001500 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1501 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1502 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1503 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1504 Record.push_back(N->getLine());
1505 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1506 Record.push_back(N->isLocalToUnit());
1507 Record.push_back(N->isDefinition());
1508 Record.push_back(N->getScopeLine());
1509 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1510 Record.push_back(N->getVirtuality());
1511 Record.push_back(N->getVirtualIndex());
1512 Record.push_back(N->getFlags());
1513 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001514 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001515 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001516 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001517 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001518
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001519 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001520 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001521}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001522
Teresa Johnson37687f32016-04-23 04:30:47 +00001523void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1524 SmallVectorImpl<uint64_t> &Record,
1525 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001526 Record.push_back(N->isDistinct());
1527 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1528 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1529 Record.push_back(N->getLine());
1530 Record.push_back(N->getColumn());
1531
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001532 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001533 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001534}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001535
Teresa Johnson37687f32016-04-23 04:30:47 +00001536void ModuleBitcodeWriter::writeDILexicalBlockFile(
1537 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1538 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001539 Record.push_back(N->isDistinct());
1540 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1541 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1542 Record.push_back(N->getDiscriminator());
1543
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001544 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001545 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001546}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001547
Teresa Johnson37687f32016-04-23 04:30:47 +00001548void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1549 SmallVectorImpl<uint64_t> &Record,
1550 unsigned Abbrev) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001551 Record.push_back(N->isDistinct());
1552 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1553 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1554 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1555 Record.push_back(N->getLine());
1556
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001557 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001558 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001559}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001560
Teresa Johnson37687f32016-04-23 04:30:47 +00001561void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1562 SmallVectorImpl<uint64_t> &Record,
1563 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001564 Record.push_back(N->isDistinct());
1565 Record.push_back(N->getMacinfoType());
1566 Record.push_back(N->getLine());
1567 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1568 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1569
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001570 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001571 Record.clear();
1572}
1573
Teresa Johnson37687f32016-04-23 04:30:47 +00001574void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1575 SmallVectorImpl<uint64_t> &Record,
1576 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001577 Record.push_back(N->isDistinct());
1578 Record.push_back(N->getMacinfoType());
1579 Record.push_back(N->getLine());
1580 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1581 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1582
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001583 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001584 Record.clear();
1585}
1586
Teresa Johnson37687f32016-04-23 04:30:47 +00001587void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1588 SmallVectorImpl<uint64_t> &Record,
1589 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001590 Record.push_back(N->isDistinct());
1591 for (auto &I : N->operands())
1592 Record.push_back(VE.getMetadataOrNullID(I));
1593
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001594 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001595 Record.clear();
1596}
1597
Teresa Johnson37687f32016-04-23 04:30:47 +00001598void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1599 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1600 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001601 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001602 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1603 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1604
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001605 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001606 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001607}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001608
Teresa Johnson37687f32016-04-23 04:30:47 +00001609void ModuleBitcodeWriter::writeDITemplateValueParameter(
1610 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1611 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001612 Record.push_back(N->isDistinct());
1613 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001614 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1615 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1616 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1617
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001618 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001619 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001620}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001621
Teresa Johnson37687f32016-04-23 04:30:47 +00001622void ModuleBitcodeWriter::writeDIGlobalVariable(
1623 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1624 unsigned Abbrev) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001625 Record.push_back(N->isDistinct());
1626 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1627 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1628 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1629 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1630 Record.push_back(N->getLine());
1631 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1632 Record.push_back(N->isLocalToUnit());
1633 Record.push_back(N->isDefinition());
Duncan P. N. Exon Smith7ad0bd52015-04-11 20:27:40 +00001634 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001635 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1636
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001637 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001638 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001639}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001640
Teresa Johnson37687f32016-04-23 04:30:47 +00001641void ModuleBitcodeWriter::writeDILocalVariable(
1642 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1643 unsigned Abbrev) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001644 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001645 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1646 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1647 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1648 Record.push_back(N->getLine());
1649 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1650 Record.push_back(N->getArg());
1651 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001652
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001653 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001654 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001655}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001656
Teresa Johnson37687f32016-04-23 04:30:47 +00001657void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1658 SmallVectorImpl<uint64_t> &Record,
1659 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001660 Record.reserve(N->getElements().size() + 1);
1661
1662 Record.push_back(N->isDistinct());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001663 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001664
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001665 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001666 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001667}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001668
Teresa Johnson37687f32016-04-23 04:30:47 +00001669void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1670 SmallVectorImpl<uint64_t> &Record,
1671 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001672 Record.push_back(N->isDistinct());
1673 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1674 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1675 Record.push_back(N->getLine());
1676 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1677 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1678 Record.push_back(N->getAttributes());
1679 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1680
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001681 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001682 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001683}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001684
Teresa Johnson37687f32016-04-23 04:30:47 +00001685void ModuleBitcodeWriter::writeDIImportedEntity(
1686 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1687 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001688 Record.push_back(N->isDistinct());
1689 Record.push_back(N->getTag());
1690 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1691 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1692 Record.push_back(N->getLine());
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1694
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001695 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001696 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001697}
1698
Teresa Johnson37687f32016-04-23 04:30:47 +00001699unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001700 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1701 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1702 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1703 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001704 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001705}
1706
Teresa Johnson37687f32016-04-23 04:30:47 +00001707void ModuleBitcodeWriter::writeNamedMetadata(
1708 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001709 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001710 return;
1711
Teresa Johnson37687f32016-04-23 04:30:47 +00001712 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001713 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001714 // Write name.
1715 StringRef Str = NMD.getName();
1716 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001717 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001718 Record.clear();
1719
1720 // Write named metadata operands.
1721 for (const MDNode *N : NMD.operands())
1722 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001723 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001724 Record.clear();
1725 }
1726}
1727
Teresa Johnson37687f32016-04-23 04:30:47 +00001728unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001729 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1730 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001734 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001735}
1736
1737/// Write out a record for MDString.
1738///
1739/// All the metadata strings in a metadata block are emitted in a single
1740/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001741void ModuleBitcodeWriter::writeMetadataStrings(
1742 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001743 if (Strings.empty())
1744 return;
1745
1746 // Start the record with the number of strings.
1747 Record.push_back(bitc::METADATA_STRINGS);
1748 Record.push_back(Strings.size());
1749
1750 // Emit the sizes of the strings in the blob.
1751 SmallString<256> Blob;
1752 {
1753 BitstreamWriter W(Blob);
1754 for (const Metadata *MD : Strings)
1755 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1756 W.FlushToWord();
1757 }
1758
1759 // Add the offset to the strings to the record.
1760 Record.push_back(Blob.size());
1761
1762 // Add the strings to the blob.
1763 for (const Metadata *MD : Strings)
1764 Blob.append(cast<MDString>(MD)->getString());
1765
1766 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001767 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001768 Record.clear();
1769}
1770
Teresa Johnson37687f32016-04-23 04:30:47 +00001771void ModuleBitcodeWriter::writeMetadataRecords(
1772 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001773 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001774 return;
1775
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001776 // Initialize MDNode abbreviations.
1777#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1778#include "llvm/IR/Metadata.def"
1779
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001780 for (const Metadata *MD : MDs) {
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001781 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001782 assert(N->isResolved() && "Expected forward references to be resolved");
1783
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001784 switch (N->getMetadataID()) {
1785 default:
1786 llvm_unreachable("Invalid MDNode subclass");
1787#define HANDLE_MDNODE_LEAF(CLASS) \
1788 case Metadata::CLASS##Kind: \
Teresa Johnson37687f32016-04-23 04:30:47 +00001789 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001790 continue;
1791#include "llvm/IR/Metadata.def"
1792 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001793 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001794 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001795 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001796}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001797
Teresa Johnson37687f32016-04-23 04:30:47 +00001798void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001799 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001800 return;
1801
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001802 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001803 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001804 writeMetadataStrings(VE.getMDStrings(), Record);
1805 writeMetadataRecords(VE.getNonMDStrings(), Record);
1806 writeNamedMetadata(Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001807 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001808}
1809
Teresa Johnson37687f32016-04-23 04:30:47 +00001810void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00001811 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001812 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001813
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001814 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001815 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001816 writeMetadataStrings(VE.getMDStrings(), Record);
1817 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001818 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00001819}
1820
Teresa Johnson37687f32016-04-23 04:30:47 +00001821void ModuleBitcodeWriter::writeMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001822 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00001823
Devang Patelaf206b82009-09-18 19:26:43 +00001824 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001825
Devang Patelaf206b82009-09-18 19:26:43 +00001826 // Write metadata attachments
Chris Lattnerbb95d5e2011-06-17 17:56:00 +00001827 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001828 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001829 F.getAllMetadata(MDs);
1830 if (!MDs.empty()) {
1831 for (const auto &I : MDs) {
1832 Record.push_back(I.first);
1833 Record.push_back(VE.getMetadataID(I.second));
1834 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001835 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001836 Record.clear();
1837 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001838
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001839 for (const BasicBlock &BB : F)
1840 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00001841 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001842 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001843
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001844 // If no metadata, ignore instruction.
1845 if (MDs.empty()) continue;
1846
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001847 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001848
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001849 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1850 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001851 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00001852 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001853 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001854 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00001855 }
1856
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001857 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001858}
1859
Teresa Johnson37687f32016-04-23 04:30:47 +00001860void ModuleBitcodeWriter::writeModuleMetadataStore() {
Devang Patelaf206b82009-09-18 19:26:43 +00001861 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001862
Devang Patelaf206b82009-09-18 19:26:43 +00001863 // Write metadata kinds
1864 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00001865 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001866 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001867
Dan Gohman43aa8f02010-07-20 21:42:28 +00001868 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00001869
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001870 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001871
Dan Gohman43aa8f02010-07-20 21:42:28 +00001872 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00001873 Record.push_back(MDKindID);
1874 StringRef KName = Names[MDKindID];
1875 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001876
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001877 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00001878 Record.clear();
1879 }
1880
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001881 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00001882}
1883
Teresa Johnson37687f32016-04-23 04:30:47 +00001884void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001885 // Write metadata kinds
1886 //
1887 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1888 //
1889 // OPERAND_BUNDLE_TAG - [strchr x N]
1890
1891 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001892 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001893
1894 if (Tags.empty())
1895 return;
1896
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001897 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001898
1899 SmallVector<uint64_t, 64> Record;
1900
1901 for (auto Tag : Tags) {
1902 Record.append(Tag.begin(), Tag.end());
1903
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001904 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001905 Record.clear();
1906 }
1907
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001908 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001909}
1910
Jan Wen Voungafaced02012-10-11 20:20:40 +00001911static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1912 if ((int64_t)V >= 0)
1913 Vals.push_back(V << 1);
1914 else
1915 Vals.push_back((-V << 1) | 1);
1916}
1917
Teresa Johnson37687f32016-04-23 04:30:47 +00001918void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
1919 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00001920 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001921
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001922 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00001923
1924 unsigned AggregateAbbrev = 0;
1925 unsigned String8Abbrev = 0;
1926 unsigned CString7Abbrev = 0;
1927 unsigned CString6Abbrev = 0;
1928 // If this is a constant pool for the module, emit module-specific abbrevs.
1929 if (isGlobal) {
1930 // Abbrev for CST_CODE_AGGREGATE.
1931 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1932 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001935 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
Devang Patel8cca7b42009-08-04 05:01:35 +00001936
1937 // Abbrev for CST_CODE_STRING.
1938 Abbv = new BitCodeAbbrev();
1939 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1940 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1941 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001942 String8Abbrev = Stream.EmitAbbrev(Abbv);
Devang Patel8cca7b42009-08-04 05:01:35 +00001943 // Abbrev for CST_CODE_CSTRING.
1944 Abbv = new BitCodeAbbrev();
1945 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001948 CString7Abbrev = Stream.EmitAbbrev(Abbv);
Devang Patel8cca7b42009-08-04 05:01:35 +00001949 // Abbrev for CST_CODE_CSTRING.
1950 Abbv = new BitCodeAbbrev();
1951 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
1952 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1953 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001954 CString6Abbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001955 }
1956
Devang Patel8cca7b42009-08-04 05:01:35 +00001957 SmallVector<uint64_t, 64> Record;
1958
1959 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00001960 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00001961 for (unsigned i = FirstVal; i != LastVal; ++i) {
1962 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00001963 // If we need to switch types, do so now.
1964 if (V->getType() != LastTy) {
1965 LastTy = V->getType();
1966 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001967 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
1968 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00001969 Record.clear();
1970 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001971
Chris Lattner52523562007-04-24 00:16:04 +00001972 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00001973 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001974 unsigned(IA->isAlignStack()) << 1 |
1975 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001976
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001977 // Add the asm string.
1978 const std::string &AsmStr = IA->getAsmString();
1979 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001980 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001982 // Add the constraint string.
1983 const std::string &ConstraintStr = IA->getConstraintString();
1984 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001985 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001986 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001987 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00001988 continue;
1989 }
1990 const Constant *C = cast<Constant>(V);
1991 unsigned Code = -1U;
1992 unsigned AbbrevToUse = 0;
1993 if (C->isNullValue()) {
1994 Code = bitc::CST_CODE_NULL;
1995 } else if (isa<UndefValue>(C)) {
1996 Code = bitc::CST_CODE_UNDEF;
1997 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00001998 if (IV->getBitWidth() <= 64) {
1999 uint64_t V = IV->getSExtValue();
2000 emitSignedInt64(Record, V);
2001 Code = bitc::CST_CODE_INTEGER;
2002 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2003 } else { // Wide integers, > 64 bits in size.
2004 // We have an arbitrary precision integer value to write whose
2005 // bit width is > 64. However, in canonical unsigned integer
2006 // format it is likely that the high bits are going to be zero.
2007 // So, we only write the number of active words.
2008 unsigned NWords = IV->getValue().getActiveWords();
2009 const uint64_t *RawWords = IV->getValue().getRawData();
2010 for (unsigned i = 0; i != NWords; ++i) {
2011 emitSignedInt64(Record, RawWords[i]);
2012 }
2013 Code = bitc::CST_CODE_WIDE_INTEGER;
2014 }
Chris Lattner52523562007-04-24 00:16:04 +00002015 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2016 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002017 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002018 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002019 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002020 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002021 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002022 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002023 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002024 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002025 Record.push_back((p[1] << 48) | (p[0] >> 16));
2026 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002027 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002028 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002029 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002030 Record.push_back(p[0]);
2031 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002032 } else {
2033 assert (0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002034 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002035 } else if (isa<ConstantDataSequential>(C) &&
2036 cast<ConstantDataSequential>(C)->isString()) {
2037 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2038 // Emit constant strings specially.
2039 unsigned NumElts = Str->getNumElements();
2040 // If this is a null-terminated string, use the denser CSTRING encoding.
2041 if (Str->isCString()) {
2042 Code = bitc::CST_CODE_CSTRING;
2043 --NumElts; // Don't encode the null, which isn't allowed by char6.
2044 } else {
2045 Code = bitc::CST_CODE_STRING;
2046 AbbrevToUse = String8Abbrev;
2047 }
2048 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2049 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2050 for (unsigned i = 0; i != NumElts; ++i) {
2051 unsigned char V = Str->getElementAsInteger(i);
2052 Record.push_back(V);
2053 isCStr7 &= (V & 128) == 0;
2054 if (isCStrChar6)
2055 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2056 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002057
Chris Lattner372dd1e2012-01-30 00:51:16 +00002058 if (isCStrChar6)
2059 AbbrevToUse = CString6Abbrev;
2060 else if (isCStr7)
2061 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002062 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002063 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002064 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002065 Type *EltTy = CDS->getType()->getElementType();
2066 if (isa<IntegerType>(EltTy)) {
2067 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2068 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002069 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002070 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2071 Record.push_back(
2072 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002073 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002074 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002075 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002076 for (const Value *Op : C->operands())
2077 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002078 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002079 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002080 switch (CE->getOpcode()) {
2081 default:
2082 if (Instruction::isCast(CE->getOpcode())) {
2083 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002084 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002085 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2086 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002087 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002088 } else {
2089 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2090 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002091 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002092 Record.push_back(VE.getValueID(C->getOperand(0)));
2093 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002094 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002095 if (Flags != 0)
2096 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002097 }
2098 break;
David Blaikieb9263572015-03-13 21:03:36 +00002099 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002100 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002101 const auto *GO = cast<GEPOperator>(C);
2102 if (GO->isInBounds())
Dan Gohman1639c392009-07-27 21:53:46 +00002103 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002104 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002105 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2106 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2107 Record.push_back(VE.getValueID(C->getOperand(i)));
2108 }
2109 break;
David Blaikieb9263572015-03-13 21:03:36 +00002110 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002111 case Instruction::Select:
2112 Code = bitc::CST_CODE_CE_SELECT;
2113 Record.push_back(VE.getValueID(C->getOperand(0)));
2114 Record.push_back(VE.getValueID(C->getOperand(1)));
2115 Record.push_back(VE.getValueID(C->getOperand(2)));
2116 break;
2117 case Instruction::ExtractElement:
2118 Code = bitc::CST_CODE_CE_EXTRACTELT;
2119 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2120 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002121 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002122 Record.push_back(VE.getValueID(C->getOperand(1)));
2123 break;
2124 case Instruction::InsertElement:
2125 Code = bitc::CST_CODE_CE_INSERTELT;
2126 Record.push_back(VE.getValueID(C->getOperand(0)));
2127 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002128 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002129 Record.push_back(VE.getValueID(C->getOperand(2)));
2130 break;
2131 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002132 // If the return type and argument types are the same, this is a
2133 // standard shufflevector instruction. If the types are different,
2134 // then the shuffle is widening or truncating the input vectors, and
2135 // the argument type must also be encoded.
2136 if (C->getType() == C->getOperand(0)->getType()) {
2137 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2138 } else {
2139 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2140 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2141 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002142 Record.push_back(VE.getValueID(C->getOperand(0)));
2143 Record.push_back(VE.getValueID(C->getOperand(1)));
2144 Record.push_back(VE.getValueID(C->getOperand(2)));
2145 break;
2146 case Instruction::ICmp:
2147 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002148 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002149 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2150 Record.push_back(VE.getValueID(C->getOperand(0)));
2151 Record.push_back(VE.getValueID(C->getOperand(1)));
2152 Record.push_back(CE->getPredicate());
2153 break;
2154 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002155 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002156 Code = bitc::CST_CODE_BLOCKADDRESS;
2157 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2158 Record.push_back(VE.getValueID(BA->getFunction()));
2159 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002160 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002161#ifndef NDEBUG
2162 C->dump();
2163#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002164 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002165 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002166 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002167 Record.clear();
2168 }
2169
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002170 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002171}
2172
Teresa Johnson37687f32016-04-23 04:30:47 +00002173void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002174 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002175
Chris Lattner52523562007-04-24 00:16:04 +00002176 // Find the first constant to emit, which is the first non-globalvalue value.
2177 // We know globalvalues have been emitted by WriteModuleInfo.
2178 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2179 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002180 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002181 return;
2182 }
2183 }
2184}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002185
Teresa Johnson37687f32016-04-23 04:30:47 +00002186/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002187/// many values, because we need to know what type to create for forward
2188/// references. However, most operands are not forward references, so this type
2189/// field is not needed.
2190///
2191/// This function adds V's value ID to Vals. If the value ID is higher than the
2192/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002193/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002194bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2195 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002196 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002197 // Make encoding relative to the InstID.
2198 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002199 if (ValID >= InstID) {
2200 Vals.push_back(VE.getTypeID(V->getType()));
2201 return true;
2202 }
2203 return false;
2204}
2205
Teresa Johnson37687f32016-04-23 04:30:47 +00002206void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2207 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002208 SmallVector<unsigned, 64> Record;
2209 LLVMContext &C = CS.getInstruction()->getContext();
2210
2211 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002212 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002213 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002214
2215 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002216 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002217
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002218 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002219 Record.clear();
2220 }
2221}
2222
Teresa Johnson37687f32016-04-23 04:30:47 +00002223/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002224/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002225void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2226 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002227 unsigned ValID = VE.getValueID(V);
2228 Vals.push_back(InstID - ValID);
2229}
2230
Teresa Johnson37687f32016-04-23 04:30:47 +00002231void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2232 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002233 unsigned ValID = VE.getValueID(V);
2234 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2235 emitSignedInt64(Vals, diff);
2236}
2237
Chris Lattnere6e364c2007-04-26 05:53:54 +00002238/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002239void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2240 unsigned InstID,
2241 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002242 unsigned Code = 0;
2243 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002244 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002245 switch (I.getOpcode()) {
2246 default:
2247 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002248 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002249 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002250 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002251 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002252 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002253 } else {
2254 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002255 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002256 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002257 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002258 pushValue(I.getOperand(1), InstID, Vals);
2259 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2260 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002261 if (Flags != 0) {
2262 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2263 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2264 Vals.push_back(Flags);
2265 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002266 }
2267 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002268
David Blaikieb5b5efd2015-02-25 01:08:52 +00002269 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002270 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002271 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2272 auto &GEPInst = cast<GetElementPtrInst>(I);
2273 Vals.push_back(GEPInst.isInBounds());
2274 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002275 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002276 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002277 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002278 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002279 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002280 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002281 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002282 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002283 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002284 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002285 }
2286 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002287 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002288 pushValueAndType(I.getOperand(0), InstID, Vals);
2289 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002290 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002291 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002292 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002293 }
Chris Lattner0a603252007-05-01 02:13:26 +00002294 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002295 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002296 pushValueAndType(I.getOperand(1), InstID, Vals);
2297 pushValue(I.getOperand(2), InstID, Vals);
2298 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002299 break;
2300 case Instruction::ExtractElement:
2301 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002302 pushValueAndType(I.getOperand(0), InstID, Vals);
2303 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002304 break;
2305 case Instruction::InsertElement:
2306 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002307 pushValueAndType(I.getOperand(0), InstID, Vals);
2308 pushValue(I.getOperand(1), InstID, Vals);
2309 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002310 break;
2311 case Instruction::ShuffleVector:
2312 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002313 pushValueAndType(I.getOperand(0), InstID, Vals);
2314 pushValue(I.getOperand(1), InstID, Vals);
2315 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002316 break;
2317 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002318 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002319 // compare returning Int1Ty or vector of Int1Ty
2320 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002321 pushValueAndType(I.getOperand(0), InstID, Vals);
2322 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002323 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002324 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002325 if (Flags != 0)
2326 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002327 break;
James Molloy88eb5352015-07-10 12:52:00 +00002328 }
Chris Lattner0a603252007-05-01 02:13:26 +00002329
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002330 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002331 {
2332 Code = bitc::FUNC_CODE_INST_RET;
2333 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002334 if (NumOperands == 0)
2335 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2336 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002337 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002338 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2339 } else {
2340 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002341 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002342 }
2343 }
Chris Lattner0a603252007-05-01 02:13:26 +00002344 break;
2345 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002346 {
2347 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002348 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002349 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2350 if (II.isConditional()) {
2351 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002352 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002353 }
Chris Lattner0a603252007-05-01 02:13:26 +00002354 }
2355 break;
2356 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002357 {
2358 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002359 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002360 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002361 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002362 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Sanjay Patel225d65f2015-11-13 16:21:23 +00002363 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2364 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2365 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002366 }
2367 }
Chris Lattner0a603252007-05-01 02:13:26 +00002368 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002369 case Instruction::IndirectBr:
2370 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002371 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002372 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002373 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002374 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002375 Vals.push_back(VE.getValueID(I.getOperand(i)));
2376 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002377
Chris Lattnerb811e952007-05-01 07:03:37 +00002378 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002379 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002380 const Value *Callee = II->getCalledValue();
2381 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002382
2383 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002384 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002385
Chris Lattner0a603252007-05-01 02:13:26 +00002386 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002387
Devang Patel4c758ea2008-09-25 21:00:45 +00002388 Vals.push_back(VE.getAttributeID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002389 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002390 Vals.push_back(VE.getValueID(II->getNormalDest()));
2391 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002392 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002393 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002394
Chris Lattner0a603252007-05-01 02:13:26 +00002395 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002396 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002397 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002398
2399 // Emit type/value pairs for varargs params.
2400 if (FTy->isVarArg()) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00002401 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002402 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002403 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002404 }
2405 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002406 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002407 case Instruction::Resume:
2408 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002409 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002410 break;
David Majnemer654e1302015-07-31 17:58:14 +00002411 case Instruction::CleanupRet: {
2412 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2413 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002414 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002415 if (CRI.hasUnwindDest())
2416 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2417 break;
2418 }
2419 case Instruction::CatchRet: {
2420 Code = bitc::FUNC_CODE_INST_CATCHRET;
2421 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002422 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002423 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2424 break;
2425 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002426 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002427 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002428 const auto &FuncletPad = cast<FuncletPadInst>(I);
2429 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2430 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002431 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002432
2433 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002434 Vals.push_back(NumArgOperands);
2435 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002436 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002437 break;
2438 }
2439 case Instruction::CatchSwitch: {
2440 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2441 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2442
Teresa Johnson37687f32016-04-23 04:30:47 +00002443 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002444
2445 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2446 Vals.push_back(NumHandlers);
2447 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2448 Vals.push_back(VE.getValueID(CatchPadBB));
2449
2450 if (CatchSwitch.hasUnwindDest())
2451 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002452 break;
2453 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002454 case Instruction::Unreachable:
2455 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002456 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002457 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002458
Jay Foad372ad642011-06-20 14:18:48 +00002459 case Instruction::PHI: {
2460 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002461 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002462 // With the newer instruction encoding, forward references could give
2463 // negative valued IDs. This is most common for PHIs, so we use
2464 // signed VBRs.
2465 SmallVector<uint64_t, 128> Vals64;
2466 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002467 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002468 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002469 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002470 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002471 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002472 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002473 Vals64.clear();
2474 return;
Jay Foad372ad642011-06-20 14:18:48 +00002475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002476
Bill Wendlingfae14752011-08-12 20:24:12 +00002477 case Instruction::LandingPad: {
2478 const LandingPadInst &LP = cast<LandingPadInst>(I);
2479 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2480 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002481 Vals.push_back(LP.isCleanup());
2482 Vals.push_back(LP.getNumClauses());
2483 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2484 if (LP.isCatch(I))
2485 Vals.push_back(LandingPadInst::Catch);
2486 else
2487 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002488 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002489 }
2490 break;
2491 }
2492
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002493 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002494 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002495 const AllocaInst &AI = cast<AllocaInst>(I);
2496 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002497 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002498 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002499 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2500 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2501 "not enough bits for maximum alignment");
2502 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2503 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002504 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002505 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002506 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002507 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002508 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002509
Chris Lattner0a603252007-05-01 02:13:26 +00002510 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002511 if (cast<LoadInst>(I).isAtomic()) {
2512 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002513 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002514 } else {
2515 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002516 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002517 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2518 }
David Blaikie85035652015-02-25 01:07:20 +00002519 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002520 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2521 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002522 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002523 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2524 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002525 }
Chris Lattner0a603252007-05-01 02:13:26 +00002526 break;
2527 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002528 if (cast<StoreInst>(I).isAtomic())
2529 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2530 else
2531 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002532 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2533 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002534 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2535 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002536 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002537 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2538 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002539 }
Chris Lattner0a603252007-05-01 02:13:26 +00002540 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002541 case Instruction::AtomicCmpXchg:
2542 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002543 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2544 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2545 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002546 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002547 Vals.push_back(
2548 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2549 Vals.push_back(
2550 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2551 Vals.push_back(
2552 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002553 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002554 break;
2555 case Instruction::AtomicRMW:
2556 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002557 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2558 pushValue(I.getOperand(1), InstID, Vals); // val.
2559 Vals.push_back(
2560 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002561 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002562 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2563 Vals.push_back(
2564 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002565 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002566 case Instruction::Fence:
2567 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002568 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2569 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002570 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002571 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002572 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002573 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002574
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002575 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002576 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002577
Chris Lattnerc44070802011-06-17 18:17:37 +00002578 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002579
Gabor Greife9afee22010-06-26 09:35:09 +00002580 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002581
Teresa Johnson37687f32016-04-23 04:30:47 +00002582 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002583 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2584 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2585 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2586 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002587 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2588 unsigned(Flags != 0) << bitc::CALL_FMF);
2589 if (Flags != 0)
2590 Vals.push_back(Flags);
2591
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002592 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002593 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002594
Chris Lattner0a603252007-05-01 02:13:26 +00002595 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002596 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2597 // Check for labels (can happen with asm labels).
2598 if (FTy->getParamType(i)->isLabelTy())
2599 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2600 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002601 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002602 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002603
Chris Lattnerb811e952007-05-01 07:03:37 +00002604 // Emit type/value pairs for varargs params.
2605 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002606 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002607 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002608 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002609 }
2610 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002611 }
Chris Lattner0a603252007-05-01 02:13:26 +00002612 case Instruction::VAArg:
2613 Code = bitc::FUNC_CODE_INST_VAARG;
2614 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002615 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002616 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2617 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002619
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002620 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002621 Vals.clear();
2622}
2623
Teresa Johnson37687f32016-04-23 04:30:47 +00002624/// Emit names for globals/functions etc. \p IsModuleLevel is true when
2625/// we are writing the module-level VST, where we are including a function
2626/// bitcode index and need to backpatch the VST forward declaration record.
2627void ModuleBitcodeWriter::writeValueSymbolTable(
2628 const ValueSymbolTable &VST, bool IsModuleLevel,
2629 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002630 if (VST.empty()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002631 // writeValueSymbolTableForwardDecl should have returned early as
Teresa Johnsonff642b92015-09-17 20:12:00 +00002632 // well. Ensure this handling remains in sync by asserting that
2633 // the placeholder offset is not set.
Teresa Johnson37687f32016-04-23 04:30:47 +00002634 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder());
Teresa Johnsonff642b92015-09-17 20:12:00 +00002635 return;
2636 }
2637
Teresa Johnson37687f32016-04-23 04:30:47 +00002638 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002639 // Get the offset of the VST we are writing, and backpatch it into
2640 // the VST forward declaration record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002641 uint64_t VSTOffset = Stream.GetCurrentBitNo();
Teresa Johnsonff642b92015-09-17 20:12:00 +00002642 // The BitcodeStartBit was the stream offset of the actual bitcode
2643 // (e.g. excluding any initial darwin header).
Teresa Johnson37687f32016-04-23 04:30:47 +00002644 VSTOffset -= bitcodeStartBit();
Teresa Johnsonff642b92015-09-17 20:12:00 +00002645 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002646 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002647 }
2648
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002649 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002650
Teresa Johnsonff642b92015-09-17 20:12:00 +00002651 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2652 // records, which are not used in the per-function VSTs.
2653 unsigned FnEntry8BitAbbrev;
2654 unsigned FnEntry7BitAbbrev;
2655 unsigned FnEntry6BitAbbrev;
Teresa Johnson37687f32016-04-23 04:30:47 +00002656 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002657 // 8-bit fixed-width VST_CODE_FNENTRY function strings.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002658 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2659 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2661 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
Teresa Johnsonff642b92015-09-17 20:12:00 +00002662 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2663 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002664 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002665
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002666 // 7-bit fixed width VST_CODE_FNENTRY function strings.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002667 Abbv = new BitCodeAbbrev();
2668 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2670 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
Teresa Johnsonff642b92015-09-17 20:12:00 +00002671 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2672 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002673 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002674
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002675 // 6-bit char6 VST_CODE_FNENTRY function strings.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002676 Abbv = new BitCodeAbbrev();
2677 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
Teresa Johnsonff642b92015-09-17 20:12:00 +00002680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002682 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002683 }
2684
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002685 // FIXME: Set up the abbrev, we know how many values there are!
2686 // FIXME: We know if the type names can use 7-bit ascii.
2687 SmallVector<unsigned, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002688
Yaron Keren001e2e42015-08-10 07:04:29 +00002689 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002690 // Figure out the encoding to use for the name.
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002691 StringEncoding Bits =
2692 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Chris Lattnera0987962007-05-04 21:31:13 +00002694 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002695 NameVals.push_back(VE.getValueID(Name.getValue()));
2696
2697 Function *F = dyn_cast<Function>(Name.getValue());
2698 if (!F) {
2699 // If value is an alias, need to get the aliased base object to
2700 // see if it is a function.
2701 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2702 if (GA && GA->getBaseObject())
2703 F = dyn_cast<Function>(GA->getBaseObject());
2704 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002706 // VST_CODE_ENTRY: [valueid, namechar x N]
2707 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2708 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002709 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002710 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002711 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002712 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002713 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002714 } else if (F && !F->isDeclaration()) {
2715 // Must be the module-level VST, where we pass in the Index and
2716 // have a VSTOffsetPlaceholder. The function-level VST should not
2717 // contain any Function symbols.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00002718 assert(FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00002719 assert(hasVSTOffsetPlaceholder());
Teresa Johnsonff642b92015-09-17 20:12:00 +00002720
2721 // Save the word offset of the function (from the start of the
2722 // actual bitcode written to the stream).
Teresa Johnson37687f32016-04-23 04:30:47 +00002723 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
Teresa Johnsonff642b92015-09-17 20:12:00 +00002724 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2725 NameVals.push_back(BitcodeIndex / 32);
2726
2727 Code = bitc::VST_CODE_FNENTRY;
2728 AbbrevToUse = FnEntry8BitAbbrev;
2729 if (Bits == SE_Char6)
2730 AbbrevToUse = FnEntry6BitAbbrev;
2731 else if (Bits == SE_Fixed7)
2732 AbbrevToUse = FnEntry7BitAbbrev;
Chris Lattner6be58c62007-05-03 22:18:21 +00002733 } else {
2734 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002735 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002736 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002737 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002738 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002739 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002740
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002741 for (const auto P : Name.getKey())
2742 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002743
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002744 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002745 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002746 NameVals.clear();
2747 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002748 Stream.ExitBlock();
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002749}
2750
Teresa Johnson403a7872015-10-04 14:33:43 +00002751/// Emit function names and summary offsets for the combined index
2752/// used by ThinLTO.
Teresa Johnson37687f32016-04-23 04:30:47 +00002753void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2754 assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002755 // Get the offset of the VST we are writing, and backpatch it into
2756 // the VST forward declaration record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002757 uint64_t VSTOffset = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002758 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002759 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002760
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002761 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00002762
Teresa Johnson403a7872015-10-04 14:33:43 +00002763 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002764 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2765 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002767 unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00002768
Teresa Johnsone1164de2016-02-10 21:55:02 +00002769 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson37687f32016-04-23 04:30:47 +00002770 for (const auto &GVI : valueIds()) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002771 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2772 NameVals.push_back(GVI.second);
2773 NameVals.push_back(GVI.first);
2774
2775 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002776 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002777 NameVals.clear();
Teresa Johnson403a7872015-10-04 14:33:43 +00002778 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002779 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002780}
2781
Teresa Johnson37687f32016-04-23 04:30:47 +00002782void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002783 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2784 unsigned Code;
2785 if (isa<BasicBlock>(Order.V))
2786 Code = bitc::USELIST_CODE_BB;
2787 else
2788 Code = bitc::USELIST_CODE_DEFAULT;
2789
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002790 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002791 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002792 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002793}
2794
Teresa Johnson37687f32016-04-23 04:30:47 +00002795void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002796 assert(VE.shouldPreserveUseListOrder() &&
2797 "Expected to be preserving use-list order");
2798
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002799 auto hasMore = [&]() {
2800 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2801 };
2802 if (!hasMore())
2803 // Nothing to do.
2804 return;
2805
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002806 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002807 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002808 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002809 VE.UseListOrders.pop_back();
2810 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002811 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002812}
2813
Teresa Johnson403a7872015-10-04 14:33:43 +00002814/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002815void ModuleBitcodeWriter::writeFunction(
2816 const Function &F,
2817 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002818 // Save the bitcode index of the start of this function block for recording
2819 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002820 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002821
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002822 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002823 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002824
2825 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Chris Lattnere6e364c2007-04-26 05:53:54 +00002827 // Emit the number of basic blocks, so the reader can create them ahead of
2828 // time.
2829 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002830 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002831 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002832
Chris Lattnere6e364c2007-04-26 05:53:54 +00002833 // If there are function-local constants, emit them now.
2834 unsigned CstStart, CstEnd;
2835 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00002836 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002837
Victor Hernandez6c730de2010-01-14 01:50:08 +00002838 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002839 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00002840
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002841 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002842 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002843
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002844 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002845
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002846 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002847 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002848 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002849 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2850 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002851 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002852
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002853 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002854 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002855
Chris Lattner07d09ed2010-04-03 02:17:50 +00002856 // If the instruction has metadata, write a metadata attachment later.
2857 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002858
Chris Lattner07d09ed2010-04-03 02:17:50 +00002859 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002860 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002861 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002862 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002863
2864 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00002865 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002866 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002867 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002868 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002869
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002870 Vals.push_back(DL->getLine());
2871 Vals.push_back(DL->getColumn());
2872 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2873 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002874 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002875 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00002876
2877 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002878 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002879
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002880 // Emit names for all the instructions etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002881 writeValueSymbolTable(F.getValueSymbolTable());
Devang Patelaf206b82009-09-18 19:26:43 +00002882
Chris Lattner07d09ed2010-04-03 02:17:50 +00002883 if (NeedsMetadataAttachment)
Teresa Johnson37687f32016-04-23 04:30:47 +00002884 writeMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002885 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00002886 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00002887 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002888 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00002889}
2890
Chris Lattner702658c2007-05-04 18:26:27 +00002891// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002892void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00002893 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00002894 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00002895 // Other blocks can define their abbrevs inline.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002896 Stream.EnterBlockInfoBlock(2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002897
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002898 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
Chris Lattner982ec1e2007-05-05 00:17:00 +00002899 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2900 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2901 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2902 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2903 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002904 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002905 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002906 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002907 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002908
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002909 { // 7-bit fixed width VST_CODE_ENTRY strings.
Chris Lattner982ec1e2007-05-05 00:17:00 +00002910 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2911 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2912 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2913 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2914 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002915 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002916 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002917 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002918 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002919 { // 6-bit char6 VST_CODE_ENTRY strings.
Chris Lattnere760d6f2007-05-05 01:26:50 +00002920 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2921 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2922 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2923 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2924 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002925 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002926 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002927 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00002928 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002929 { // 6-bit char6 VST_CODE_BBENTRY strings.
Chris Lattner982ec1e2007-05-05 00:17:00 +00002930 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2931 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2932 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2933 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00002934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002935 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002936 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002937 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002938 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002939
2940
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002941
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002942 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2943 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2944 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2945 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00002946 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002947 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002948 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002949 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002950 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002951
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002952 { // INTEGER abbrev for CONSTANTS_BLOCK.
2953 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2954 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
2955 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002956 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002957 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002958 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002959 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002960
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002961 { // CE_CAST abbrev for CONSTANTS_BLOCK.
2962 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2963 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
2964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
2965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00002966 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2968
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002969 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002970 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002971 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002972 }
2973 { // NULL abbrev for CONSTANTS_BLOCK.
2974 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2975 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002976 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002977 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002978 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002979 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002980
Chris Lattnerb80751d2007-05-05 07:44:49 +00002981 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002982
Chris Lattnerb80751d2007-05-05 07:44:49 +00002983 { // INST_LOAD abbrev for FUNCTION_BLOCK.
2984 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2985 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00002986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00002987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
2988 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00002989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
2990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002991 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002992 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002993 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00002994 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002995 { // INST_BINOP abbrev for FUNCTION_BLOCK.
2996 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2997 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
2998 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
2999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003001 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003002 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003003 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003004 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003005 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3006 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3007 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3008 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3010 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003012 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003013 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003014 llvm_unreachable("Unexpected abbrev ordering!");
3015 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003016 { // INST_CAST abbrev for FUNCTION_BLOCK.
3017 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3018 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003021 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003022 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003023 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003024 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003025 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003026 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003027
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003028 { // INST_RET abbrev for FUNCTION_BLOCK.
3029 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3030 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003031 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003032 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003033 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003034 }
3035 { // INST_RET abbrev for FUNCTION_BLOCK.
3036 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3037 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003039 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003040 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003041 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003042 }
3043 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3044 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3045 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003046 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003047 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003048 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003049 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003050 {
3051 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3052 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3055 Log2_32_Ceil(VE.getTypes().size() + 1)));
3056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003058 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003059 FUNCTION_INST_GEP_ABBREV)
3060 llvm_unreachable("Unexpected abbrev ordering!");
3061 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003062
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003063 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003064}
3065
Teresa Johnson403a7872015-10-04 14:33:43 +00003066/// Write the module path strings, currently only used when generating
3067/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003068void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003069 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003070
3071 // TODO: See which abbrev sizes we actually need to emit
3072
3073 // 8-bit fixed-width MST_ENTRY strings.
3074 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3075 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003079 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003080
3081 // 7-bit fixed width MST_ENTRY strings.
3082 Abbv = new BitCodeAbbrev();
3083 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3084 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3085 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3086 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003087 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003088
3089 // 6-bit char6 MST_ENTRY strings.
3090 Abbv = new BitCodeAbbrev();
3091 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3092 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3094 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003095 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003096
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003097 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3098 Abbv = new BitCodeAbbrev();
3099 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3102 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3103 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3104 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003105 unsigned AbbrevHash = Stream.EmitAbbrev(Abbv);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003106
3107 SmallVector<unsigned, 64> Vals;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003108 for (const auto &MPSE : Index.modulePaths()) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003109 if (!doIncludeModule(MPSE.getKey()))
3110 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00003111 StringEncoding Bits =
3112 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3113 unsigned AbbrevToUse = Abbrev8Bit;
3114 if (Bits == SE_Char6)
3115 AbbrevToUse = Abbrev6Bit;
3116 else if (Bits == SE_Fixed7)
3117 AbbrevToUse = Abbrev7Bit;
3118
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003119 Vals.push_back(MPSE.getValue().first);
Teresa Johnson403a7872015-10-04 14:33:43 +00003120
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003121 for (const auto P : MPSE.getKey())
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003122 Vals.push_back((unsigned char)P);
Teresa Johnson403a7872015-10-04 14:33:43 +00003123
3124 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003125 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003126
3127 Vals.clear();
3128 // Emit an optional hash for the module now
3129 auto &Hash = MPSE.getValue().second;
3130 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3131 for (auto Val : Hash) {
3132 if (Val)
3133 AllZero = false;
3134 Vals.push_back(Val);
3135 }
3136 if (!AllZero) {
3137 // Emit the hash record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003138 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003139 }
3140
3141 Vals.clear();
Teresa Johnson403a7872015-10-04 14:33:43 +00003142 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003143 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003144}
3145
3146// Helper to emit a single function summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003147void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003148 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003149 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3150 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003151 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003152
Teresa Johnson28e457b2016-04-24 14:57:11 +00003153 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003154 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003155 NameVals.push_back(FS->instCount());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003156 NameVals.push_back(FS->refs().size());
3157
3158 for (auto &RI : FS->refs())
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003159 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003160
3161 bool HasProfileData = F.getEntryCount().hasValue();
Teresa Johnsonaae26102016-03-25 18:59:13 +00003162 for (auto &ECI : FS->calls()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003163 NameVals.push_back(VE.getValueID(ECI.first.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003164 assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
3165 NameVals.push_back(ECI.second.CallsiteCount);
3166 if (HasProfileData)
3167 NameVals.push_back(ECI.second.ProfileCount);
3168 }
3169
3170 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3171 unsigned Code =
3172 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003173
3174 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003175 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003176 NameVals.clear();
3177}
3178
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003179// Collect the global value references in the given variable's initializer,
3180// and emit them in a summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003181void ModuleBitcodeWriter::writeModuleLevelReferences(
3182 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3183 unsigned FSModRefsAbbrev) {
Teresa Johnson13968092016-03-15 19:35:45 +00003184 // Only interested in recording variable defs in the summary.
3185 if (V.isDeclaration())
3186 return;
Teresa Johnson13968092016-03-15 19:35:45 +00003187 NameVals.push_back(VE.getValueID(&V));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003188 NameVals.push_back(getEncodedGVSummaryFlags(V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003189 auto *Summary = Index->getGlobalValueSummary(V);
3190 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003191 for (auto Ref : VS->refs())
3192 NameVals.push_back(VE.getValueID(Ref.getValue()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003193 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3194 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003195 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003196}
Teresa Johnson403a7872015-10-04 14:33:43 +00003197
Mehdi Amini8fe69362016-04-24 03:18:11 +00003198// Current version for the summary.
3199// This is bumped whenever we introduce changes in the way some record are
3200// interpreted, like flags for instance.
3201static const uint64_t INDEX_VERSION = 1;
3202
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003203/// Emit the per-module summary section alongside the rest of
3204/// the module's bitcode.
Teresa Johnson37687f32016-04-23 04:30:47 +00003205void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003206 if (M.empty())
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003207 return;
3208
Teresa Johnson37687f32016-04-23 04:30:47 +00003209 if (Index->begin() == Index->end())
Teresa Johnsonb35cc692016-04-20 14:39:45 +00003210 return;
3211
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003212 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003213
Mehdi Amini8fe69362016-04-24 03:18:11 +00003214 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3215
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003216 // Abbrev for FS_PERMODULE.
Teresa Johnson403a7872015-10-04 14:33:43 +00003217 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003218 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3223 // numrefs x valueid, n x (valueid, callsitecount)
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3225 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003226 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003227
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003228 // Abbrev for FS_PERMODULE_PROFILE.
3229 Abbv = new BitCodeAbbrev();
3230 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3235 // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003238 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003239
3240 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3241 Abbv = new BitCodeAbbrev();
3242 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003247 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003248
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003249 // Abbrev for FS_ALIAS.
3250 Abbv = new BitCodeAbbrev();
3251 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003255 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003256
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003257 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003258 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003259 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003260 for (const Function &F : M) {
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003261 if (F.isDeclaration())
3262 continue;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003263 // Summary emission does not support anonymous functions, they have to
3264 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003265 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003266 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003267
Teresa Johnson28e457b2016-04-24 14:57:11 +00003268 auto *Summary = Index->getGlobalValueSummary(F);
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003269 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3270 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003271 }
3272
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003273 // Capture references from GlobalVariable initializers, which are outside
3274 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003275 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003276 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003277
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003278 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003279 auto *Aliasee = A.getBaseObject();
3280 if (!Aliasee->hasName())
3281 // Nameless function don't have an entry in the summary, skip it.
3282 continue;
3283 auto AliasId = VE.getValueID(&A);
3284 auto AliaseeId = VE.getValueID(Aliasee);
3285 NameVals.push_back(AliasId);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003286 NameVals.push_back(getEncodedGVSummaryFlags(A));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003287 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003288 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003289 NameVals.clear();
3290 }
3291
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003292 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003293}
3294
Teresa Johnson26ab5772016-03-15 00:04:37 +00003295/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003296void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003297 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003298 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003299
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003300 // Abbrev for FS_COMBINED.
Teresa Johnson403a7872015-10-04 14:33:43 +00003301 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003302 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003306 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3307 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3308 // numrefs x valueid, n x (valueid, callsitecount)
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003311 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003312
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003313 // Abbrev for FS_COMBINED_PROFILE.
3314 Abbv = new BitCodeAbbrev();
3315 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3321 // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003324 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003325
3326 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3327 Abbv = new BitCodeAbbrev();
3328 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003330 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003331 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003334 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003335
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003336 // Abbrev for FS_COMBINED_ALIAS.
3337 Abbv = new BitCodeAbbrev();
3338 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003342 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003343 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003344
Teresa Johnson02e98332016-04-27 13:28:35 +00003345 // The aliases are emitted as a post-pass, and will point to the value
3346 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003347 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003348
Teresa Johnson02e98332016-04-27 13:28:35 +00003349 // Save the value id for each summary for alias emission.
3350 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3351
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003352 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003353
3354 // For local linkage, we also emit the original name separately
3355 // immediately after the record.
3356 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3357 if (!GlobalValue::isLocalLinkage(S.linkage()))
3358 return;
3359 NameVals.push_back(S.getOriginalName());
3360 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3361 NameVals.clear();
3362 };
3363
Teresa Johnson84174c32016-05-10 13:48:23 +00003364 for (const auto &I : *this) {
3365 GlobalValueSummary *S = I.second;
3366 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003367
Teresa Johnson84174c32016-05-10 13:48:23 +00003368 assert(hasValueId(I.first));
3369 unsigned ValueId = getValueId(I.first);
3370 SummaryToValueIdMap[S] = ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003371
Teresa Johnson84174c32016-05-10 13:48:23 +00003372 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3373 // Will process aliases as a post-pass because the reader wants all
3374 // global to be loaded first.
3375 Aliases.push_back(AS);
3376 continue;
3377 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003378
Teresa Johnson84174c32016-05-10 13:48:23 +00003379 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003380 NameVals.push_back(ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003381 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3382 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3383 for (auto &RI : VS->refs()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003384 NameVals.push_back(getValueId(RI.getGUID()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003385 }
3386
Teresa Johnson403a7872015-10-04 14:33:43 +00003387 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003388 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3389 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003390 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003391 MaybeEmitOriginalName(*S);
Teresa Johnson84174c32016-05-10 13:48:23 +00003392 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00003393 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003394
3395 auto *FS = cast<FunctionSummary>(S);
3396 NameVals.push_back(ValueId);
3397 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3398 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3399 NameVals.push_back(FS->instCount());
3400 NameVals.push_back(FS->refs().size());
3401
3402 for (auto &RI : FS->refs()) {
3403 NameVals.push_back(getValueId(RI.getGUID()));
3404 }
3405
3406 bool HasProfileData = false;
3407 for (auto &EI : FS->calls()) {
3408 HasProfileData |= EI.second.ProfileCount != 0;
3409 if (HasProfileData)
3410 break;
3411 }
3412
3413 for (auto &EI : FS->calls()) {
3414 // If this GUID doesn't have a value id, it doesn't have a function
3415 // summary and we don't need to record any calls to it.
3416 if (!hasValueId(EI.first.getGUID()))
3417 continue;
3418 NameVals.push_back(getValueId(EI.first.getGUID()));
3419 assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
3420 NameVals.push_back(EI.second.CallsiteCount);
3421 if (HasProfileData)
3422 NameVals.push_back(EI.second.ProfileCount);
3423 }
3424
3425 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3426 unsigned Code =
3427 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3428
3429 // Emit the finished record.
3430 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3431 NameVals.clear();
3432 MaybeEmitOriginalName(*S);
Teresa Johnson403a7872015-10-04 14:33:43 +00003433 }
3434
Teresa Johnson28e457b2016-04-24 14:57:11 +00003435 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003436 auto AliasValueId = SummaryToValueIdMap[AS];
3437 assert(AliasValueId);
3438 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003439 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003440 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003441 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3442 assert(AliaseeValueId);
3443 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003444
3445 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003446 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003447 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003448 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003449 }
3450
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003451 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003452}
3453
Teresa Johnson37687f32016-04-23 04:30:47 +00003454void ModuleBitcodeWriter::writeIdentificationBlock() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003455 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003456
3457 // Write the "user readable" string identifying the bitcode producer
3458 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3459 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003462 auto StringAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson37687f32016-04-23 04:30:47 +00003463 writeStringRecord(bitc::IDENTIFICATION_CODE_STRING,
3464 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003465
3466 // Write the epoch version
3467 Abbv = new BitCodeAbbrev();
3468 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003470 auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
Mehdi Amini5d303282015-10-26 18:37:00 +00003471 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003472 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3473 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003474}
3475
Teresa Johnson37687f32016-04-23 04:30:47 +00003476void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003477 // Emit the module's hash.
3478 // MODULE_CODE_HASH: [5*i32]
3479 SHA1 Hasher;
Sjoerd Meijer41beee62016-04-27 18:35:02 +00003480 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003481 Buffer.size() - BlockStartPos));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003482 auto Hash = Hasher.result();
3483 SmallVector<uint64_t, 20> Vals;
3484 auto LShift = [&](unsigned char Val, unsigned Amount)
3485 -> uint64_t { return ((uint64_t)Val) << Amount; };
3486 for (int Pos = 0; Pos < 20; Pos += 4) {
3487 uint32_t SubHash = LShift(Hash[Pos + 0], 24);
3488 SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) |
3489 (unsigned)(unsigned char)Hash[Pos + 3];
3490 Vals.push_back(SubHash);
3491 }
3492
3493 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003494 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003495}
3496
Teresa Johnson37687f32016-04-23 04:30:47 +00003497void BitcodeWriter::write() {
3498 // Emit the file header first.
3499 writeBitcodeHeader();
3500
3501 writeBlocks();
3502}
3503
3504void ModuleBitcodeWriter::writeBlocks() {
3505 writeIdentificationBlock();
3506 writeModule();
3507}
3508
3509void IndexBitcodeWriter::writeBlocks() {
3510 // Index contains only a single outer (module) block.
3511 writeIndex();
3512}
3513
3514void ModuleBitcodeWriter::writeModule() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003515 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3516 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003517
Jan Wen Voungafaced02012-10-11 20:20:40 +00003518 SmallVector<unsigned, 1> Vals;
3519 unsigned CurVersion = 1;
3520 Vals.push_back(CurVersion);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003521 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003522
3523 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003524 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003525
Bill Wendlingdc095552013-02-10 23:09:32 +00003526 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003527 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003528
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003529 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003530 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003531
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003532 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003533 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003534
Teresa Johnson37687f32016-04-23 04:30:47 +00003535 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003536
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003537 // Emit top-level description of module, including target triple, inline asm,
3538 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003539 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003540
Devang Patele059ba6e2009-07-23 01:07:34 +00003541 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003542 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003543
Devang Patel8cca7b42009-08-04 05:01:35 +00003544 // Emit metadata.
Teresa Johnson37687f32016-04-23 04:30:47 +00003545 writeModuleMetadata();
Devang Patel8cca7b42009-08-04 05:01:35 +00003546
Devang Patelaf206b82009-09-18 19:26:43 +00003547 // Emit metadata.
Teresa Johnson37687f32016-04-23 04:30:47 +00003548 writeModuleMetadataStore();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003549
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003550 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003551 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003552 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003553
Teresa Johnson37687f32016-04-23 04:30:47 +00003554 writeOperandBundleTags();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003555
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003556 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003557 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003558 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003559 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003560 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003561
3562 // Need to write after the above call to WriteFunction which populates
3563 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003564 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003565 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003566
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003567 writeValueSymbolTable(M.getValueSymbolTable(),
Teresa Johnson37687f32016-04-23 04:30:47 +00003568 /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003569
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003570 if (GenerateHash) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003571 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003572 }
3573
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003574 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003575}
3576
Teresa Johnson37687f32016-04-23 04:30:47 +00003577static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3578 uint32_t &Position) {
3579 support::endian::write32le(&Buffer[Position], Value);
3580 Position += 4;
3581}
3582
3583/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003584/// header and trailer to make it compatible with the system archiver. To do
3585/// this we emit the following header, and then emit a trailer that pads the
3586/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003587///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003588/// struct bc_header {
3589/// uint32_t Magic; // 0x0B17C0DE
3590/// uint32_t Version; // Version, currently always 0.
3591/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3592/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3593/// uint32_t CPUType; // CPU specifier.
3594/// ... potentially more later ...
3595/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003596static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003597 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003598 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003599
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003600 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003601 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3602 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3603 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003604 enum {
3605 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3606 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003607 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003608 DARWIN_CPU_TYPE_POWERPC = 18
3609 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003610
Evan Chengcffdcae2011-06-14 01:51:33 +00003611 Triple::ArchType Arch = TT.getArch();
3612 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003613 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003614 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003615 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003616 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003617 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003618 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003619 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003620 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003621 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003622
Chris Lattnera660f4b2008-07-09 05:14:23 +00003623 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003624 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003625 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003626 unsigned BCOffset = BWH_HeaderSize;
3627 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003628
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003629 // Write the magic and version.
3630 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003631 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3632 writeInt32ToBuffer(0, Buffer, Position); // Version.
3633 writeInt32ToBuffer(BCOffset, Buffer, Position);
3634 writeInt32ToBuffer(BCSize, Buffer, Position);
3635 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003636
Chris Lattnera660f4b2008-07-09 05:14:23 +00003637 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003638 while (Buffer.size() & 15)
3639 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003640}
3641
Teresa Johnson403a7872015-10-04 14:33:43 +00003642/// Helper to write the header common to all bitcode files.
Teresa Johnson37687f32016-04-23 04:30:47 +00003643void BitcodeWriter::writeBitcodeHeader() {
Teresa Johnson403a7872015-10-04 14:33:43 +00003644 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003645 Stream.Emit((unsigned)'B', 8);
3646 Stream.Emit((unsigned)'C', 8);
3647 Stream.Emit(0x0, 4);
3648 Stream.Emit(0xC, 4);
3649 Stream.Emit(0xE, 4);
3650 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003651}
3652
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003653/// WriteBitcodeToFile - Write the specified module to the specified output
3654/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00003655void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00003656 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003657 const ModuleSummaryIndex *Index,
3658 bool GenerateHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00003659 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003660 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003661
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003662 // If this is darwin or another generic macho target, reserve space for the
3663 // header.
3664 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00003665 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003666 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003667
3668 // Emit the module into the buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003669 ModuleBitcodeWriter ModuleWriter(M, Buffer, ShouldPreserveUseListOrder, Index,
3670 GenerateHash);
Teresa Johnson37687f32016-04-23 04:30:47 +00003671 ModuleWriter.write();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003672
Akira Hatanaka1235d282016-01-23 16:02:10 +00003673 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00003674 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003675
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003676 // Write the generated bitstream to "Out".
3677 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003678}
Teresa Johnson403a7872015-10-04 14:33:43 +00003679
Teresa Johnson37687f32016-04-23 04:30:47 +00003680void IndexBitcodeWriter::writeIndex() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003681 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00003682
3683 SmallVector<unsigned, 1> Vals;
3684 unsigned CurVersion = 1;
3685 Vals.push_back(CurVersion);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003686 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
Teresa Johnson37687f32016-04-23 04:30:47 +00003687
3688 // If we have a VST, write the VSTOFFSET record placeholder.
3689 writeValueSymbolTableForwardDecl();
3690
3691 // Write the module paths in the combined index.
3692 writeModStrings();
3693
3694 // Write the summary combined index records.
3695 writeCombinedGlobalValueSummary();
3696
3697 // Need a special VST writer for the combined index (we don't have a
3698 // real VST and real values when this is invoked).
3699 writeCombinedValueSymbolTable();
3700
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003701 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00003702}
3703
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003704// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00003705// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00003706// writing the combined index file for ThinLTO. When writing a subset of the
3707// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3708void llvm::WriteIndexToFile(
3709 const ModuleSummaryIndex &Index, raw_ostream &Out,
3710 std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003711 SmallVector<char, 0> Buffer;
3712 Buffer.reserve(256 * 1024);
3713
Teresa Johnson84174c32016-05-10 13:48:23 +00003714 IndexBitcodeWriter IndexWriter(Buffer, Index, ModuleToSummariesForIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00003715 IndexWriter.write();
Teresa Johnson403a7872015-10-04 14:33:43 +00003716
3717 Out.write((char *)&Buffer.front(), Buffer.size());
3718}