blob: c5d376c9426b8012abe7798dc91449b5cb1b49d4 [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +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
Teresa Johnsonad176792016-11-11 05:34:58 +000014#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "ValueEnumerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/Triple.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000028#include "llvm/Bitcode/BitCodes.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000029#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000030#include "llvm/Bitcode/LLVMBitCodes.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000031#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000033#include "llvm/IR/CallSite.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000034#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000037#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000038#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000040#include "llvm/IR/Function.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalIFunc.h"
43#include "llvm/IR/GlobalObject.h"
44#include "llvm/IR/GlobalValue.h"
45#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/InlineAsm.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000047#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000050#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000051#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Module.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000053#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/Operator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000055#include "llvm/IR/Type.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000056#include "llvm/IR/UseListOrder.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000057#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000059#include "llvm/MC/StringTableBuilder.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000060#include "llvm/Object/IRSymtab.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000061#include "llvm/Support/AtomicOrdering.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Endian.h"
65#include "llvm/Support/Error.h"
Torok Edwin56d06592009-07-11 20:10:48 +000066#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000067#include "llvm/Support/MathExtras.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000068#include "llvm/Support/SHA1.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000069#include "llvm/Support/TargetRegistry.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000070#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000071#include <algorithm>
72#include <cassert>
73#include <cstddef>
74#include <cstdint>
75#include <iterator>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000076#include <map>
Eugene Zelenko975293f2017-09-07 23:28:24 +000077#include <memory>
78#include <string>
79#include <utility>
80#include <vector>
81
Chris Lattnerc1d10d62007-04-22 06:24:45 +000082using namespace llvm;
83
Eugene Zelenko975293f2017-09-07 23:28:24 +000084static cl::opt<unsigned>
Mehdi Aminie98f9252016-12-28 22:30:28 +000085 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
86 cl::desc("Number of metadatas above which we emit an index "
87 "to enable lazy-loading"));
Eugene Zelenko975293f2017-09-07 23:28:24 +000088
89namespace {
90
Chris Lattner4d925982007-05-04 20:52:02 +000091/// These are manifest constants used by the bitcode writer. They do not need to
92/// be kept in sync with the reader, but need to be consistent within this file.
93enum {
Chris Lattner4d925982007-05-04 20:52:02 +000094 // VALUE_SYMTAB_BLOCK abbrev id's.
95 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000096 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +000097 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +000098 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000099
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000100 // CONSTANTS_BLOCK abbrev id's.
101 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
102 CONSTANTS_INTEGER_ABBREV,
103 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +0000104 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000105
Chris Lattnerb80751d2007-05-05 07:44:49 +0000106 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000107 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000108 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +0000109 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000110 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000111 FUNCTION_INST_RET_VOID_ABBREV,
112 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +0000113 FUNCTION_INST_UNREACHABLE_ABBREV,
114 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +0000115};
116
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000117/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000118/// file type.
119class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000120protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000121 /// The stream created and owned by the client.
122 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +0000123
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000124 StringTableBuilder &StrtabBuilder;
125
Teresa Johnson37687f32016-04-23 04:30:47 +0000126public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000127 /// Constructs a BitcodeWriterBase object that writes to the provided
128 /// \p Stream.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000129 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
130 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
Teresa Johnson37687f32016-04-23 04:30:47 +0000131
132protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000133 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000134 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +0000135};
136
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000137void BitcodeWriterBase::writeModuleVersion() {
138 // VERSION: [version#]
139 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
140}
141
Haojie Wang1dec57d2017-07-21 17:25:20 +0000142/// Base class to manage the module bitcode writing, currently subclassed for
143/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
144class ModuleBitcodeWriterBase : public BitcodeWriterBase {
145protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000146 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000147 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000148
149 /// Enumerates ids for all values in the module.
150 ValueEnumerator VE;
151
152 /// Optional per-module index to write for ThinLTO.
153 const ModuleSummaryIndex *Index;
154
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000155 /// Map that holds the correspondence between GUIDs in the summary index,
156 /// that came from indirect call profiles, and a value id generated by this
157 /// class to use in the VST and summary block records.
158 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
159
160 /// Tracks the last value id recorded in the GUIDToValueMap.
161 unsigned GlobalValueId;
162
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000163 /// Saves the offset of the VSTOffset record that must eventually be
164 /// backpatched with the offset of the actual VST.
165 uint64_t VSTOffsetPlaceholder = 0;
166
Teresa Johnson37687f32016-04-23 04:30:47 +0000167public:
Haojie Wang1dec57d2017-07-21 17:25:20 +0000168 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
Teresa Johnson37687f32016-04-23 04:30:47 +0000169 /// writing to the provided \p Buffer.
Haojie Wang1dec57d2017-07-21 17:25:20 +0000170 ModuleBitcodeWriterBase(const Module *M, StringTableBuilder &StrtabBuilder,
171 BitstreamWriter &Stream,
172 bool ShouldPreserveUseListOrder,
173 const ModuleSummaryIndex *Index)
174 : BitcodeWriterBase(Stream, StrtabBuilder), M(*M),
175 VE(*M, ShouldPreserveUseListOrder), Index(Index) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000176 // Assign ValueIds to any callee values in the index that came from
177 // indirect call profiles and were recorded as a GUID not a Value*
178 // (which would have been assigned an ID by the ValueEnumerator).
179 // The starting ValueId is just after the number of values in the
180 // ValueEnumerator, so that they can be emitted in the VST.
181 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000182 if (!Index)
183 return;
184 for (const auto &GUIDSummaryLists : *Index)
185 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000186 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000187 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
188 // For each call in the function summary, see if the call
189 // is to a GUID (which means it is for an indirect call,
190 // otherwise we would have a Value for it). If so, synthesize
191 // a value id.
192 for (auto &CallEdge : FS->calls())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000193 if (!CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000194 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000195 }
196
Haojie Wang1dec57d2017-07-21 17:25:20 +0000197protected:
198 void writePerModuleGlobalValueSummary();
199
200private:
201 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
202 GlobalValueSummary *Summary,
203 unsigned ValueID,
204 unsigned FSCallsAbbrev,
205 unsigned FSCallsProfileAbbrev,
206 const Function &F);
207 void writeModuleLevelReferences(const GlobalVariable &V,
208 SmallVector<uint64_t, 64> &NameVals,
209 unsigned FSModRefsAbbrev);
210
211 void assignValueId(GlobalValue::GUID ValGUID) {
212 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
213 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000214
Haojie Wang1dec57d2017-07-21 17:25:20 +0000215 unsigned getValueId(GlobalValue::GUID ValGUID) {
216 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
217 // Expect that any GUID value had a value Id assigned by an
218 // earlier call to assignValueId.
219 assert(VMI != GUIDToValueIdMap.end() &&
220 "GUID does not have assigned value Id");
221 return VMI->second;
222 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000223
Haojie Wang1dec57d2017-07-21 17:25:20 +0000224 // Helper to get the valueId for the type of value recorded in VI.
225 unsigned getValueId(ValueInfo VI) {
226 if (!VI.getValue())
227 return getValueId(VI.getGUID());
228 return VE.getValueID(VI.getValue());
229 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000230
Haojie Wang1dec57d2017-07-21 17:25:20 +0000231 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
232};
233
234/// Class to manage the bitcode writing for a module.
235class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
236 /// Pointer to the buffer allocated by caller for bitcode writing.
237 const SmallVectorImpl<char> &Buffer;
238
239 /// True if a module hash record should be written.
240 bool GenerateHash;
241
242 /// If non-null, when GenerateHash is true, the resulting hash is written
243 /// into ModHash.
244 ModuleHash *ModHash;
245
246 SHA1 Hasher;
247
248 /// The start bit of the identification block.
249 uint64_t BitcodeStartBit;
250
251public:
252 /// Constructs a ModuleBitcodeWriter object for the given Module,
253 /// writing to the provided \p Buffer.
254 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
255 StringTableBuilder &StrtabBuilder,
256 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
257 const ModuleSummaryIndex *Index, bool GenerateHash,
258 ModuleHash *ModHash = nullptr)
259 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
260 ShouldPreserveUseListOrder, Index),
261 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
262 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
263
Teresa Johnson37687f32016-04-23 04:30:47 +0000264 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000265 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000266
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000267private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000268 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
269
Peter Collingbournec8556152017-07-06 17:56:01 +0000270 size_t addToStrtab(StringRef Str);
271
Teresa Johnson37687f32016-04-23 04:30:47 +0000272 void writeAttributeGroupTable();
273 void writeAttributeTable();
274 void writeTypeTable();
275 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000276 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000277 void writeModuleInfo();
278 void writeValueAsMetadata(const ValueAsMetadata *MD,
279 SmallVectorImpl<uint64_t> &Record);
280 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
281 unsigned Abbrev);
282 unsigned createDILocationAbbrev();
283 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
284 unsigned &Abbrev);
285 unsigned createGenericDINodeAbbrev();
286 void writeGenericDINode(const GenericDINode *N,
287 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
288 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
289 unsigned Abbrev);
290 void writeDIEnumerator(const DIEnumerator *N,
291 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
292 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
293 unsigned Abbrev);
294 void writeDIDerivedType(const DIDerivedType *N,
295 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
296 void writeDICompositeType(const DICompositeType *N,
297 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
298 void writeDISubroutineType(const DISubroutineType *N,
299 SmallVectorImpl<uint64_t> &Record,
300 unsigned Abbrev);
301 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
302 unsigned Abbrev);
303 void writeDICompileUnit(const DICompileUnit *N,
304 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
305 void writeDISubprogram(const DISubprogram *N,
306 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
307 void writeDILexicalBlock(const DILexicalBlock *N,
308 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
309 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
310 SmallVectorImpl<uint64_t> &Record,
311 unsigned Abbrev);
312 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
313 unsigned Abbrev);
314 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
315 unsigned Abbrev);
316 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
317 unsigned Abbrev);
318 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
319 unsigned Abbrev);
320 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
321 SmallVectorImpl<uint64_t> &Record,
322 unsigned Abbrev);
323 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
324 SmallVectorImpl<uint64_t> &Record,
325 unsigned Abbrev);
326 void writeDIGlobalVariable(const DIGlobalVariable *N,
327 SmallVectorImpl<uint64_t> &Record,
328 unsigned Abbrev);
329 void writeDILocalVariable(const DILocalVariable *N,
330 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
331 void writeDIExpression(const DIExpression *N,
332 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000333 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
334 SmallVectorImpl<uint64_t> &Record,
335 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000336 void writeDIObjCProperty(const DIObjCProperty *N,
337 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
338 void writeDIImportedEntity(const DIImportedEntity *N,
339 SmallVectorImpl<uint64_t> &Record,
340 unsigned Abbrev);
341 unsigned createNamedMetadataAbbrev();
342 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
343 unsigned createMetadataStringsAbbrev();
344 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
345 SmallVectorImpl<uint64_t> &Record);
346 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000347 SmallVectorImpl<uint64_t> &Record,
348 std::vector<unsigned> *MDAbbrevs = nullptr,
349 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000350 void writeModuleMetadata();
351 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000352 void writeFunctionMetadataAttachment(const Function &F);
353 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
354 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
355 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000356 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000357 void writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000358 void writeSyncScopeNames();
Teresa Johnson37687f32016-04-23 04:30:47 +0000359 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
360 void writeModuleConstants();
361 bool pushValueAndType(const Value *V, unsigned InstID,
362 SmallVectorImpl<unsigned> &Vals);
363 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
364 void pushValue(const Value *V, unsigned InstID,
365 SmallVectorImpl<unsigned> &Vals);
366 void pushValueSigned(const Value *V, unsigned InstID,
367 SmallVectorImpl<uint64_t> &Vals);
368 void writeInstruction(const Instruction &I, unsigned InstID,
369 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000370 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
371 void writeGlobalValueSymbolTable(
372 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000373 void writeUseList(UseListOrder &&Order);
374 void writeUseListBlock(const Function *F);
375 void
376 writeFunction(const Function &F,
377 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
378 void writeBlockInfo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000379 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000380
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000381 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
382 return unsigned(SSID);
383 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000384};
385
386/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000387class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000388 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000389 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000390
Teresa Johnson84174c32016-05-10 13:48:23 +0000391 /// When writing a subset of the index for distributed backends, client
392 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000393 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000394
Teresa Johnson37687f32016-04-23 04:30:47 +0000395 /// Map that holds the correspondence between the GUID used in the combined
396 /// index and a value id generated by this class to use in references.
397 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
398
399 /// Tracks the last value id recorded in the GUIDToValueMap.
400 unsigned GlobalValueId = 0;
401
402public:
403 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000404 /// writing to the provided \p Buffer. When writing a subset of the index
405 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000406 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
407 const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000408 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000409 *ModuleToSummariesForIndex = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000410 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000411 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
412 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000413 // in writing out the call graph edges. Save the mapping from GUID
414 // to the new global value id to use when writing those edges, which
415 // are currently saved in the index in terms of GUID.
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000416 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000417 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000418 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000419 }
420
Teresa Johnson84174c32016-05-10 13:48:23 +0000421 /// The below iterator returns the GUID and associated summary.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000422 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
Teresa Johnson84174c32016-05-10 13:48:23 +0000423
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000424 /// Calls the callback for each value GUID and summary to be written to
425 /// bitcode. This hides the details of whether they are being pulled from the
426 /// entire index or just those in a provided ModuleToSummariesForIndex map.
David Blaikie358c0122017-06-02 18:25:29 +0000427 template<typename Functor>
428 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000429 if (ModuleToSummariesForIndex) {
430 for (auto &M : *ModuleToSummariesForIndex)
431 for (auto &Summary : M.second)
432 Callback(Summary);
433 } else {
434 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000435 for (auto &Summary : Summaries.second.SummaryList)
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000436 Callback({Summaries.first, Summary.get()});
Teresa Johnson84174c32016-05-10 13:48:23 +0000437 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000438 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000439
Teresa Johnson7a27b132017-06-02 01:56:02 +0000440 /// Calls the callback for each entry in the modulePaths StringMap that
441 /// should be written to the module path string table. This hides the details
442 /// of whether they are being pulled from the entire index or just those in a
443 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000444 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000445 if (ModuleToSummariesForIndex) {
446 for (const auto &M : *ModuleToSummariesForIndex) {
447 const auto &MPI = Index.modulePaths().find(M.first);
448 if (MPI == Index.modulePaths().end()) {
449 // This should only happen if the bitcode file was empty, in which
450 // case we shouldn't be importing (the ModuleToSummariesForIndex
451 // would only include the module we are writing and index for).
452 assert(ModuleToSummariesForIndex->size() == 1);
453 continue;
454 }
455 Callback(*MPI);
456 }
457 } else {
458 for (const auto &MPSE : Index.modulePaths())
459 Callback(MPSE);
460 }
461 }
462
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000463 /// Main entry point for writing a combined index to bitcode.
464 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000465
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000466private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000467 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000468 void writeCombinedGlobalValueSummary();
469
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000470 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000471 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000472 if (VMI == GUIDToValueIdMap.end())
473 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000474 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000475 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000476
Teresa Johnson37687f32016-04-23 04:30:47 +0000477 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
478};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000479
Benjamin Kramera65b6102016-05-15 15:18:11 +0000480} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000481
482static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000483 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000484 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000485 case Instruction::Trunc : return bitc::CAST_TRUNC;
486 case Instruction::ZExt : return bitc::CAST_ZEXT;
487 case Instruction::SExt : return bitc::CAST_SEXT;
488 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
489 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
490 case Instruction::UIToFP : return bitc::CAST_UITOFP;
491 case Instruction::SIToFP : return bitc::CAST_SITOFP;
492 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
493 case Instruction::FPExt : return bitc::CAST_FPEXT;
494 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
495 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
496 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000497 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000498 }
499}
500
Teresa Johnson37687f32016-04-23 04:30:47 +0000501static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000502 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000503 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000504 case Instruction::Add:
505 case Instruction::FAdd: return bitc::BINOP_ADD;
506 case Instruction::Sub:
507 case Instruction::FSub: return bitc::BINOP_SUB;
508 case Instruction::Mul:
509 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000510 case Instruction::UDiv: return bitc::BINOP_UDIV;
511 case Instruction::FDiv:
512 case Instruction::SDiv: return bitc::BINOP_SDIV;
513 case Instruction::URem: return bitc::BINOP_UREM;
514 case Instruction::FRem:
515 case Instruction::SRem: return bitc::BINOP_SREM;
516 case Instruction::Shl: return bitc::BINOP_SHL;
517 case Instruction::LShr: return bitc::BINOP_LSHR;
518 case Instruction::AShr: return bitc::BINOP_ASHR;
519 case Instruction::And: return bitc::BINOP_AND;
520 case Instruction::Or: return bitc::BINOP_OR;
521 case Instruction::Xor: return bitc::BINOP_XOR;
522 }
523}
524
Teresa Johnson37687f32016-04-23 04:30:47 +0000525static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000526 switch (Op) {
527 default: llvm_unreachable("Unknown RMW operation!");
528 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
529 case AtomicRMWInst::Add: return bitc::RMW_ADD;
530 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
531 case AtomicRMWInst::And: return bitc::RMW_AND;
532 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
533 case AtomicRMWInst::Or: return bitc::RMW_OR;
534 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
535 case AtomicRMWInst::Max: return bitc::RMW_MAX;
536 case AtomicRMWInst::Min: return bitc::RMW_MIN;
537 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
538 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
539 }
540}
541
Teresa Johnson37687f32016-04-23 04:30:47 +0000542static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000543 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000544 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
545 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
546 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
547 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
548 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
549 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
550 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000551 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000552 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000553}
554
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000555static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
556 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000557 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000558
Chris Lattnere14cb882007-05-04 19:11:41 +0000559 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000560 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
561 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
562 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000563 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000564 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000565
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000566 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000567 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000568}
569
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000570static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
571 switch (Kind) {
572 case Attribute::Alignment:
573 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000574 case Attribute::AllocSize:
575 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000576 case Attribute::AlwaysInline:
577 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000578 case Attribute::ArgMemOnly:
579 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000580 case Attribute::Builtin:
581 return bitc::ATTR_KIND_BUILTIN;
582 case Attribute::ByVal:
583 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000584 case Attribute::Convergent:
585 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000586 case Attribute::InAlloca:
587 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000588 case Attribute::Cold:
589 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000590 case Attribute::InaccessibleMemOnly:
591 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
592 case Attribute::InaccessibleMemOrArgMemOnly:
593 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000594 case Attribute::InlineHint:
595 return bitc::ATTR_KIND_INLINE_HINT;
596 case Attribute::InReg:
597 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000598 case Attribute::JumpTable:
599 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000600 case Attribute::MinSize:
601 return bitc::ATTR_KIND_MIN_SIZE;
602 case Attribute::Naked:
603 return bitc::ATTR_KIND_NAKED;
604 case Attribute::Nest:
605 return bitc::ATTR_KIND_NEST;
606 case Attribute::NoAlias:
607 return bitc::ATTR_KIND_NO_ALIAS;
608 case Attribute::NoBuiltin:
609 return bitc::ATTR_KIND_NO_BUILTIN;
610 case Attribute::NoCapture:
611 return bitc::ATTR_KIND_NO_CAPTURE;
612 case Attribute::NoDuplicate:
613 return bitc::ATTR_KIND_NO_DUPLICATE;
614 case Attribute::NoImplicitFloat:
615 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
616 case Attribute::NoInline:
617 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000618 case Attribute::NoRecurse:
619 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000620 case Attribute::NonLazyBind:
621 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000622 case Attribute::NonNull:
623 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000624 case Attribute::Dereferenceable:
625 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000626 case Attribute::DereferenceableOrNull:
627 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000628 case Attribute::NoRedZone:
629 return bitc::ATTR_KIND_NO_RED_ZONE;
630 case Attribute::NoReturn:
631 return bitc::ATTR_KIND_NO_RETURN;
632 case Attribute::NoUnwind:
633 return bitc::ATTR_KIND_NO_UNWIND;
634 case Attribute::OptimizeForSize:
635 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000636 case Attribute::OptimizeNone:
637 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000638 case Attribute::ReadNone:
639 return bitc::ATTR_KIND_READ_NONE;
640 case Attribute::ReadOnly:
641 return bitc::ATTR_KIND_READ_ONLY;
642 case Attribute::Returned:
643 return bitc::ATTR_KIND_RETURNED;
644 case Attribute::ReturnsTwice:
645 return bitc::ATTR_KIND_RETURNS_TWICE;
646 case Attribute::SExt:
647 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000648 case Attribute::Speculatable:
649 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000650 case Attribute::StackAlignment:
651 return bitc::ATTR_KIND_STACK_ALIGNMENT;
652 case Attribute::StackProtect:
653 return bitc::ATTR_KIND_STACK_PROTECT;
654 case Attribute::StackProtectReq:
655 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
656 case Attribute::StackProtectStrong:
657 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000658 case Attribute::SafeStack:
659 return bitc::ATTR_KIND_SAFESTACK;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +0000660 case Attribute::StrictFP:
661 return bitc::ATTR_KIND_STRICT_FP;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000662 case Attribute::StructRet:
663 return bitc::ATTR_KIND_STRUCT_RET;
664 case Attribute::SanitizeAddress:
665 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
666 case Attribute::SanitizeThread:
667 return bitc::ATTR_KIND_SANITIZE_THREAD;
668 case Attribute::SanitizeMemory:
669 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000670 case Attribute::SwiftError:
671 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000672 case Attribute::SwiftSelf:
673 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000674 case Attribute::UWTable:
675 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000676 case Attribute::WriteOnly:
677 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000678 case Attribute::ZExt:
679 return bitc::ATTR_KIND_Z_EXT;
680 case Attribute::EndAttrKinds:
681 llvm_unreachable("Can not encode end-attribute kinds marker.");
682 case Attribute::None:
683 llvm_unreachable("Can not encode none-attribute.");
684 }
685
686 llvm_unreachable("Trying to encode unknown attribute");
687}
688
Teresa Johnson37687f32016-04-23 04:30:47 +0000689void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000690 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
691 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000692 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000693
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000694 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000695
696 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000697 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
698 unsigned AttrListIndex = Pair.first;
699 AttributeSet AS = Pair.second;
700 Record.push_back(VE.getAttributeGroupID(Pair));
701 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000702
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000703 for (Attribute Attr : AS) {
704 if (Attr.isEnumAttribute()) {
705 Record.push_back(0);
706 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
707 } else if (Attr.isIntAttribute()) {
708 Record.push_back(1);
709 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
710 Record.push_back(Attr.getValueAsInt());
711 } else {
712 StringRef Kind = Attr.getKindAsString();
713 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000714
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000715 Record.push_back(Val.empty() ? 3 : 4);
716 Record.append(Kind.begin(), Kind.end());
717 Record.push_back(0);
718 if (!Val.empty()) {
719 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000720 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000721 }
722 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000723 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000724
725 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
726 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000727 }
728
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000729 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000730}
731
Teresa Johnson37687f32016-04-23 04:30:47 +0000732void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000733 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000734 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000735
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000736 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000737
738 SmallVector<uint64_t, 64> Record;
739 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000740 AttributeList AL = Attrs[i];
741 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
742 AttributeSet AS = AL.getAttributes(i);
743 if (AS.hasAttributes())
744 Record.push_back(VE.getAttributeGroupID({i, AS}));
745 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000746
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000747 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000748 Record.clear();
749 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000750
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000751 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000752}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000753
754/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000755void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000756 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000757
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000758 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000759 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000760
David Blaikie7b028102015-02-25 00:51:52 +0000761 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000762
Chris Lattnerccee7062007-05-05 06:30:12 +0000763 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000764 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000765 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000767 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000768 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000769
Chris Lattnerccee7062007-05-05 06:30:12 +0000770 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000771 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000772 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
773 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000774 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000775 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000776 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000777
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000778 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000779 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000780 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000781 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
782 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000783 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000784 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000785
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000786 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000787 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000788 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
789 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
790 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000791 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000792
793 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000794 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000795 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000799 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000800
Chris Lattnerccee7062007-05-05 06:30:12 +0000801 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000802 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000803 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000805 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000806 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000807
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000808 // Emit an entry count so the reader can reserve space.
809 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000810 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000811 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000812
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000813 // Loop over all of the types, emitting each in turn.
814 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000815 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000816 int AbbrevToUse = 0;
817 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000819 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000820 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
821 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
822 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
823 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
824 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
825 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000826 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000827 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
828 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
829 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000830 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000831 case Type::IntegerTyID:
832 // INTEGER: [width]
833 Code = bitc::TYPE_CODE_INTEGER;
834 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
835 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000836 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000837 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000838 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000839 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000840 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000841 unsigned AddressSpace = PTy->getAddressSpace();
842 TypeVals.push_back(AddressSpace);
843 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000844 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000845 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000846 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000847 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000848 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000849 Code = bitc::TYPE_CODE_FUNCTION;
850 TypeVals.push_back(FT->isVarArg());
851 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000852 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
853 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000854 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000855 break;
856 }
857 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000858 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000859 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000860 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000861 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000862 for (StructType::element_iterator I = ST->element_begin(),
863 E = ST->element_end(); I != E; ++I)
864 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000865
Chris Lattner335d3992011-08-12 18:06:37 +0000866 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000867 Code = bitc::TYPE_CODE_STRUCT_ANON;
868 AbbrevToUse = StructAnonAbbrev;
869 } else {
870 if (ST->isOpaque()) {
871 Code = bitc::TYPE_CODE_OPAQUE;
872 } else {
873 Code = bitc::TYPE_CODE_STRUCT_NAMED;
874 AbbrevToUse = StructNamedAbbrev;
875 }
876
877 // Emit the name if it is present.
878 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000879 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000880 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000881 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000882 break;
883 }
884 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000885 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000886 // ARRAY: [numelts, eltty]
887 Code = bitc::TYPE_CODE_ARRAY;
888 TypeVals.push_back(AT->getNumElements());
889 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000890 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000891 break;
892 }
893 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000894 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000895 // VECTOR [numelts, eltty]
896 Code = bitc::TYPE_CODE_VECTOR;
897 TypeVals.push_back(VT->getNumElements());
898 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
899 break;
900 }
901 }
902
903 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000904 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000905 TypeVals.clear();
906 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000907
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000908 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000909}
910
Teresa Johnson5e22e442016-02-06 16:07:35 +0000911static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
912 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000913 case GlobalValue::ExternalLinkage:
914 return 0;
915 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000916 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000917 case GlobalValue::AppendingLinkage:
918 return 2;
919 case GlobalValue::InternalLinkage:
920 return 3;
921 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000922 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000923 case GlobalValue::ExternalWeakLinkage:
924 return 7;
925 case GlobalValue::CommonLinkage:
926 return 8;
927 case GlobalValue::PrivateLinkage:
928 return 9;
929 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000930 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000931 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000932 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000933 case GlobalValue::AvailableExternallyLinkage:
934 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000935 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000936 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000937}
938
Teresa Johnson5e22e442016-02-06 16:07:35 +0000939static unsigned getEncodedLinkage(const GlobalValue &GV) {
940 return getEncodedLinkage(GV.getLinkage());
941}
942
Charles Saternos75da10d2017-08-04 16:00:58 +0000943static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
944 uint64_t RawFlags = 0;
945 RawFlags |= Flags.ReadNone;
946 RawFlags |= (Flags.ReadOnly << 1);
947 RawFlags |= (Flags.NoRecurse << 2);
948 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
949 return RawFlags;
950}
951
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000952// Decode the flags for GlobalValue in the summary
953static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
954 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000955
Mehdi Amini1380edf2017-02-03 07:41:43 +0000956 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000957 RawFlags |= (Flags.Live << 1);
Sean Fertile4595a912017-11-04 17:04:39 +0000958 RawFlags |= (Flags.DSOLocal << 2);
959
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000960 // Linkage don't need to be remapped at that time for the summary. Any future
961 // change to the getEncodedLinkage() function will need to be taken into
962 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000963 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
964
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000965 return RawFlags;
966}
967
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000968static unsigned getEncodedVisibility(const GlobalValue &GV) {
969 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000970 case GlobalValue::DefaultVisibility: return 0;
971 case GlobalValue::HiddenVisibility: return 1;
972 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000973 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000974 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000975}
976
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000977static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
978 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000979 case GlobalValue::DefaultStorageClass: return 0;
980 case GlobalValue::DLLImportStorageClass: return 1;
981 case GlobalValue::DLLExportStorageClass: return 2;
982 }
983 llvm_unreachable("Invalid DLL storage class");
984}
985
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000986static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000987 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000988 case GlobalVariable::NotThreadLocal: return 0;
989 case GlobalVariable::GeneralDynamicTLSModel: return 1;
990 case GlobalVariable::LocalDynamicTLSModel: return 2;
991 case GlobalVariable::InitialExecTLSModel: return 3;
992 case GlobalVariable::LocalExecTLSModel: return 4;
993 }
994 llvm_unreachable("Invalid TLS model");
995}
996
David Majnemerdad0a642014-06-27 18:19:56 +0000997static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
998 switch (C.getSelectionKind()) {
999 case Comdat::Any:
1000 return bitc::COMDAT_SELECTION_KIND_ANY;
1001 case Comdat::ExactMatch:
1002 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1003 case Comdat::Largest:
1004 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1005 case Comdat::NoDuplicates:
1006 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1007 case Comdat::SameSize:
1008 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1009 }
1010 llvm_unreachable("Invalid selection kind");
1011}
1012
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001013static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1014 switch (GV.getUnnamedAddr()) {
1015 case GlobalValue::UnnamedAddr::None: return 0;
1016 case GlobalValue::UnnamedAddr::Local: return 2;
1017 case GlobalValue::UnnamedAddr::Global: return 1;
1018 }
1019 llvm_unreachable("Invalid unnamed_addr");
1020}
1021
Peter Collingbournec8556152017-07-06 17:56:01 +00001022size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1023 if (GenerateHash)
1024 Hasher.update(Str);
1025 return StrtabBuilder.add(Str);
1026}
1027
Teresa Johnson37687f32016-04-23 04:30:47 +00001028void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +00001029 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +00001030 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001031 // COMDAT: [strtab offset, strtab size, selection_kind]
Peter Collingbournec8556152017-07-06 17:56:01 +00001032 Vals.push_back(addToStrtab(C->getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001033 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +00001034 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001035 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +00001036 Vals.clear();
1037 }
1038}
1039
Teresa Johnsonff642b92015-09-17 20:12:00 +00001040/// Write a record that will eventually hold the word offset of the
1041/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001042/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001043void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001044 // Write a placeholder value in for the offset of the real VST,
1045 // which is written after the function blocks so that it can include
1046 // the offset of each function. The placeholder offset will be
1047 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001048 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +00001049 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1050 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1051 // hold the real VST offset. Must use fixed instead of VBR as we don't
1052 // know how many VBR chunks to reserve ahead of time.
1053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001054 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00001055
1056 // Emit the placeholder
1057 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001058 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001059
Teresa Johnson37687f32016-04-23 04:30:47 +00001060 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001061 // patched when the real VST is written. We can simply subtract the 32-bit
1062 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001063 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001064}
1065
Teresa Johnsone1164de2016-02-10 21:55:02 +00001066enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1067
1068/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +00001069static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001070 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +00001071 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001072 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +00001073 isChar6 = BitCodeAbbrevOp::isChar6(C);
1074 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +00001075 // don't bother scanning the rest.
1076 return SE_Fixed8;
1077 }
1078 if (isChar6)
1079 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +00001080 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +00001081}
1082
Teresa Johnsonff642b92015-09-17 20:12:00 +00001083/// Emit top-level description of module, including target triple, inline asm,
1084/// descriptors for global variables, and function prototype info.
1085/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001086void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001087 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001088 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001089 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001090 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001091 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001092 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001093 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001094 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001095 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001096 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001097
Gordon Henriksend930f912008-08-17 18:44:35 +00001098 // Emit information about sections and GC, computing how many there are. Also
1099 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001100 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001101 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001102 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001103 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001104 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001105 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001106 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001107 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001108 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001109 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001110 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001111 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001112 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001113 Entry = SectionMap.size();
1114 }
1115 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001116 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001117 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001118 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1119 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001120 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001121 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001122 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001123 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001124 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001125 Entry = SectionMap.size();
1126 }
1127 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001128 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001129 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001130 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001131 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001132 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1133 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001134 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001135 }
1136 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001137 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001138
Chris Lattner4b00d922007-04-23 16:04:05 +00001139 // Emit abbrev for globals, now that we know # sections and max alignment.
1140 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001141 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001142 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001143 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001144 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001145 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001148 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1150 //| explicitType << 1
1151 //| constant
1152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1153 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1154 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001155 Abbv->Add(BitCodeAbbrevOp(0));
1156 else {
1157 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001159 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001160 }
1161 if (SectionMap.empty()) // Section.
1162 Abbv->Add(BitCodeAbbrevOp(0));
1163 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001165 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001166 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001167 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001168 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001169
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001170 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001171 // Emit the module's source file name.
1172 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001173 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001174 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1175 if (Bits == SE_Char6)
1176 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1177 else if (Bits == SE_Fixed7)
1178 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1179
1180 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1181 auto Abbv = std::make_shared<BitCodeAbbrev>();
1182 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1184 Abbv->Add(AbbrevOpToUse);
1185 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1186
1187 for (const auto P : M.getSourceFileName())
1188 Vals.push_back((unsigned char)P);
1189
1190 // Emit the finished record.
1191 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1192 Vals.clear();
1193 }
1194
1195 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001196 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001197 unsigned AbbrevToUse = 0;
1198
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001199 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001200 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001201 // unnamed_addr, externally_initialized, dllstorageclass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001202 // comdat, attributes, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001203 Vals.push_back(addToStrtab(GV.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001204 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001205 Vals.push_back(VE.getTypeID(GV.getValueType()));
1206 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001207 Vals.push_back(GV.isDeclaration() ? 0 :
1208 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001209 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001210 Vals.push_back(Log2_32(GV.getAlignment())+1);
1211 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1212 if (GV.isThreadLocal() ||
1213 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001214 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1215 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001216 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001217 GV.hasComdat() ||
Sean Fertilec70d28b2017-10-26 15:00:26 +00001218 GV.hasAttributes() ||
1219 GV.isDSOLocal()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001220 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001221 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001222 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001223 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001224 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001225 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001226
1227 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1228 Vals.push_back(VE.getAttributeListID(AL));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001229
1230 Vals.push_back(GV.isDSOLocal());
Chris Lattner4b00d922007-04-23 16:04:05 +00001231 } else {
1232 AbbrevToUse = SimpleGVarAbbrev;
1233 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001234
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001235 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001236 Vals.clear();
1237 }
1238
1239 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001240 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001241 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1242 // linkage, paramattrs, alignment, section, visibility, gc,
1243 // unnamed_addr, prologuedata, dllstorageclass, comdat,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001244 // prefixdata, personalityfn, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001245 Vals.push_back(addToStrtab(F.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001246 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001247 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001248 Vals.push_back(F.getCallingConv());
1249 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001250 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001251 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001252 Vals.push_back(Log2_32(F.getAlignment())+1);
1253 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001254 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001255 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001256 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001257 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1258 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001259 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001260 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001261 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1262 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001263 Vals.push_back(
1264 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001265
Sean Fertilec70d28b2017-10-26 15:00:26 +00001266 Vals.push_back(F.isDSOLocal());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001267 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001268 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001269 Vals.clear();
1270 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001271
Chris Lattner44c17072007-04-26 02:46:40 +00001272 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001273 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001274 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001275 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1276 // DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001277 Vals.push_back(addToStrtab(A.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001278 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001279 Vals.push_back(VE.getTypeID(A.getValueType()));
1280 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001281 Vals.push_back(VE.getValueID(A.getAliasee()));
1282 Vals.push_back(getEncodedLinkage(A));
1283 Vals.push_back(getEncodedVisibility(A));
1284 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001285 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001286 Vals.push_back(getEncodedUnnamedAddr(A));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001287 Vals.push_back(A.isDSOLocal());
1288
Chris Lattner44c17072007-04-26 02:46:40 +00001289 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001290 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001291 Vals.clear();
1292 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001293
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001294 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001295 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001296 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1297 // val#, linkage, visibility]
Peter Collingbournec8556152017-07-06 17:56:01 +00001298 Vals.push_back(addToStrtab(I.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001299 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001300 Vals.push_back(VE.getTypeID(I.getValueType()));
1301 Vals.push_back(I.getType()->getAddressSpace());
1302 Vals.push_back(VE.getValueID(I.getResolver()));
1303 Vals.push_back(getEncodedLinkage(I));
1304 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001305 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001306 Vals.clear();
1307 }
1308
Teresa Johnson37687f32016-04-23 04:30:47 +00001309 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001310}
1311
Teresa Johnson37687f32016-04-23 04:30:47 +00001312static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001313 uint64_t Flags = 0;
1314
Sanjay Patelc00017d2014-10-15 17:45:13 +00001315 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001316 if (OBO->hasNoSignedWrap())
1317 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1318 if (OBO->hasNoUnsignedWrap())
1319 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001320 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001321 if (PEO->isExact())
1322 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001323 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001324 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001325 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001326 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001327 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001328 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001329 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001330 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001331 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001332 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001333 Flags |= FastMathFlags::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001334 if (FPMO->hasAllowContract())
1335 Flags |= FastMathFlags::AllowContract;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001336 }
1337
1338 return Flags;
1339}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001340
Teresa Johnson37687f32016-04-23 04:30:47 +00001341void ModuleBitcodeWriter::writeValueAsMetadata(
1342 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001343 // Mimic an MDNode with a value as one operand.
1344 Value *V = MD->getValue();
1345 Record.push_back(VE.getTypeID(V->getType()));
1346 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001347 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001348 Record.clear();
1349}
1350
Teresa Johnson37687f32016-04-23 04:30:47 +00001351void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1352 SmallVectorImpl<uint64_t> &Record,
1353 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001354 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001355 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001356 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1357 "Unexpected function-local metadata");
1358 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001359 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001360 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1361 : bitc::METADATA_NODE,
1362 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001363 Record.clear();
1364}
Devang Patele059ba6e2009-07-23 01:07:34 +00001365
Teresa Johnson37687f32016-04-23 04:30:47 +00001366unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001367 // Assume the column is usually under 128, and always output the inlined-at
1368 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001369 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001370 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001376 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001377}
1378
Teresa Johnson37687f32016-04-23 04:30:47 +00001379void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1380 SmallVectorImpl<uint64_t> &Record,
1381 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001382 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001383 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001384
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001385 Record.push_back(N->isDistinct());
1386 Record.push_back(N->getLine());
1387 Record.push_back(N->getColumn());
1388 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001389 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001390
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001391 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001392 Record.clear();
1393}
1394
Teresa Johnson37687f32016-04-23 04:30:47 +00001395unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001396 // Assume the column is usually under 128, and always output the inlined-at
1397 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001398 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001399 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1402 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1403 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1404 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001406 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001407}
1408
Teresa Johnson37687f32016-04-23 04:30:47 +00001409void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1410 SmallVectorImpl<uint64_t> &Record,
1411 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001412 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001413 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001414
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001415 Record.push_back(N->isDistinct());
1416 Record.push_back(N->getTag());
1417 Record.push_back(0); // Per-tag version field; unused for now.
1418
1419 for (auto &I : N->operands())
1420 Record.push_back(VE.getMetadataOrNullID(I));
1421
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001422 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001423 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001424}
1425
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001426static uint64_t rotateSign(int64_t I) {
1427 uint64_t U = I;
1428 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001429}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001430
Teresa Johnson37687f32016-04-23 04:30:47 +00001431void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1432 SmallVectorImpl<uint64_t> &Record,
1433 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001434 Record.push_back(N->isDistinct());
1435 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001436 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001437
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001438 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001439 Record.clear();
1440}
1441
Teresa Johnson37687f32016-04-23 04:30:47 +00001442void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1443 SmallVectorImpl<uint64_t> &Record,
1444 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001445 Record.push_back(N->isDistinct());
1446 Record.push_back(rotateSign(N->getValue()));
1447 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1448
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001449 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001450 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001451}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001452
Teresa Johnson37687f32016-04-23 04:30:47 +00001453void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1454 SmallVectorImpl<uint64_t> &Record,
1455 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001456 Record.push_back(N->isDistinct());
1457 Record.push_back(N->getTag());
1458 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1459 Record.push_back(N->getSizeInBits());
1460 Record.push_back(N->getAlignInBits());
1461 Record.push_back(N->getEncoding());
1462
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001463 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001464 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001465}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001466
Teresa Johnson37687f32016-04-23 04:30:47 +00001467void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1468 SmallVectorImpl<uint64_t> &Record,
1469 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001470 Record.push_back(N->isDistinct());
1471 Record.push_back(N->getTag());
1472 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1473 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1474 Record.push_back(N->getLine());
1475 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001476 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001477 Record.push_back(N->getSizeInBits());
1478 Record.push_back(N->getAlignInBits());
1479 Record.push_back(N->getOffsetInBits());
1480 Record.push_back(N->getFlags());
1481 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1482
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001483 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1484 // that there is no DWARF address space associated with DIDerivedType.
1485 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1486 Record.push_back(*DWARFAddressSpace + 1);
1487 else
1488 Record.push_back(0);
1489
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001490 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001491 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001492}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001493
Teresa Johnson37687f32016-04-23 04:30:47 +00001494void ModuleBitcodeWriter::writeDICompositeType(
1495 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1496 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001497 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001498 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001499 Record.push_back(N->getTag());
1500 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1501 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1502 Record.push_back(N->getLine());
1503 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1504 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1505 Record.push_back(N->getSizeInBits());
1506 Record.push_back(N->getAlignInBits());
1507 Record.push_back(N->getOffsetInBits());
1508 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001509 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001510 Record.push_back(N->getRuntimeLang());
1511 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001512 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001513 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1514
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001515 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001516 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001517}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001518
Teresa Johnson37687f32016-04-23 04:30:47 +00001519void ModuleBitcodeWriter::writeDISubroutineType(
1520 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1521 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001522 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001523 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001524 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001525 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001526 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001527
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001528 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001529 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001530}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001531
Teresa Johnson37687f32016-04-23 04:30:47 +00001532void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1533 SmallVectorImpl<uint64_t> &Record,
1534 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001535 Record.push_back(N->isDistinct());
1536 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1537 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001538 Record.push_back(N->getChecksumKind());
1539 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001540
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001541 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001542 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001543}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001544
Teresa Johnson37687f32016-04-23 04:30:47 +00001545void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1546 SmallVectorImpl<uint64_t> &Record,
1547 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001548 assert(N->isDistinct() && "Expected distinct compile units");
1549 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001550 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001551 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001552 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1553 Record.push_back(N->isOptimized());
1554 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1555 Record.push_back(N->getRuntimeVersion());
1556 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1557 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001558 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1559 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001560 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001561 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1562 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001563 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001564 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001565 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001566 Record.push_back(N->getDebugInfoForProfiling());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001567 Record.push_back(N->getGnuPubnames());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001568
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001569 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001570 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001571}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001572
Teresa Johnson37687f32016-04-23 04:30:47 +00001573void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1574 SmallVectorImpl<uint64_t> &Record,
1575 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001576 uint64_t HasUnitFlag = 1 << 1;
1577 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001578 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1579 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1580 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1581 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1582 Record.push_back(N->getLine());
1583 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1584 Record.push_back(N->isLocalToUnit());
1585 Record.push_back(N->isDefinition());
1586 Record.push_back(N->getScopeLine());
1587 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1588 Record.push_back(N->getVirtuality());
1589 Record.push_back(N->getVirtualIndex());
1590 Record.push_back(N->getFlags());
1591 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001592 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001593 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001594 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001595 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001596 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001597 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001598
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001599 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001600 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001601}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001602
Teresa Johnson37687f32016-04-23 04:30:47 +00001603void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1604 SmallVectorImpl<uint64_t> &Record,
1605 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001606 Record.push_back(N->isDistinct());
1607 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1608 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1609 Record.push_back(N->getLine());
1610 Record.push_back(N->getColumn());
1611
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001612 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001613 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001614}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001615
Teresa Johnson37687f32016-04-23 04:30:47 +00001616void ModuleBitcodeWriter::writeDILexicalBlockFile(
1617 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1618 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001619 Record.push_back(N->isDistinct());
1620 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1621 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1622 Record.push_back(N->getDiscriminator());
1623
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001624 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001625 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001626}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001627
Teresa Johnson37687f32016-04-23 04:30:47 +00001628void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1629 SmallVectorImpl<uint64_t> &Record,
1630 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001631 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001632 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001633 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001634
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001635 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001636 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001637}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001638
Teresa Johnson37687f32016-04-23 04:30:47 +00001639void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1640 SmallVectorImpl<uint64_t> &Record,
1641 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001642 Record.push_back(N->isDistinct());
1643 Record.push_back(N->getMacinfoType());
1644 Record.push_back(N->getLine());
1645 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1646 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1647
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001648 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001649 Record.clear();
1650}
1651
Teresa Johnson37687f32016-04-23 04:30:47 +00001652void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1653 SmallVectorImpl<uint64_t> &Record,
1654 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001655 Record.push_back(N->isDistinct());
1656 Record.push_back(N->getMacinfoType());
1657 Record.push_back(N->getLine());
1658 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1659 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1660
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001661 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001662 Record.clear();
1663}
1664
Teresa Johnson37687f32016-04-23 04:30:47 +00001665void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1666 SmallVectorImpl<uint64_t> &Record,
1667 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001668 Record.push_back(N->isDistinct());
1669 for (auto &I : N->operands())
1670 Record.push_back(VE.getMetadataOrNullID(I));
1671
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001672 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001673 Record.clear();
1674}
1675
Teresa Johnson37687f32016-04-23 04:30:47 +00001676void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1677 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1678 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001679 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001680 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1681 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1682
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001683 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001684 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001685}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001686
Teresa Johnson37687f32016-04-23 04:30:47 +00001687void ModuleBitcodeWriter::writeDITemplateValueParameter(
1688 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1689 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001690 Record.push_back(N->isDistinct());
1691 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001692 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1693 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1694 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1695
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001696 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001697 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001698}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001699
Teresa Johnson37687f32016-04-23 04:30:47 +00001700void ModuleBitcodeWriter::writeDIGlobalVariable(
1701 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1702 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001703 const uint64_t Version = 1 << 1;
1704 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001705 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1706 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1707 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1708 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1709 Record.push_back(N->getLine());
1710 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1711 Record.push_back(N->isLocalToUnit());
1712 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001713 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001714 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001715 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001716
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001717 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001718 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001719}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001720
Teresa Johnson37687f32016-04-23 04:30:47 +00001721void ModuleBitcodeWriter::writeDILocalVariable(
1722 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1723 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001724 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001725 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001726 // 1) Record has no artificial tag (Record[1]),
1727 // has no obsolete inlinedAt field (Record[9]).
1728 // In this case Record size will be 8, HasAlignment flag is false.
1729 // 2) Record has artificial tag (Record[1]),
1730 // has no obsolete inlignedAt field (Record[9]).
1731 // In this case Record size will be 9, HasAlignment flag is false.
1732 // 3) Record has both artificial tag (Record[1]) and
1733 // obsolete inlignedAt field (Record[9]).
1734 // In this case Record size will be 10, HasAlignment flag is false.
1735 // 4) Record has neither artificial tag, nor inlignedAt field, but
1736 // HasAlignment flag is true and Record[8] contains alignment value.
1737 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001738 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001739 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1740 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1741 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1742 Record.push_back(N->getLine());
1743 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1744 Record.push_back(N->getArg());
1745 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001746 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001747
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001748 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001749 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001750}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001751
Teresa Johnson37687f32016-04-23 04:30:47 +00001752void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1753 SmallVectorImpl<uint64_t> &Record,
1754 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001755 Record.reserve(N->getElements().size() + 1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001756 const uint64_t Version = 3 << 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001757 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001758 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001759
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001760 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001761 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001762}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001763
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001764void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1765 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1766 unsigned Abbrev) {
1767 Record.push_back(N->isDistinct());
1768 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1769 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
Charles Saternos75da10d2017-08-04 16:00:58 +00001770
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001771 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1772 Record.clear();
1773}
1774
Teresa Johnson37687f32016-04-23 04:30:47 +00001775void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1776 SmallVectorImpl<uint64_t> &Record,
1777 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001778 Record.push_back(N->isDistinct());
1779 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1780 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1781 Record.push_back(N->getLine());
1782 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1783 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1784 Record.push_back(N->getAttributes());
1785 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1786
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001787 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001788 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001789}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001790
Teresa Johnson37687f32016-04-23 04:30:47 +00001791void ModuleBitcodeWriter::writeDIImportedEntity(
1792 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1793 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001794 Record.push_back(N->isDistinct());
1795 Record.push_back(N->getTag());
1796 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1797 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1798 Record.push_back(N->getLine());
1799 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Adrian Prantld63bfd22017-07-19 00:09:54 +00001800 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001801
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001802 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001803 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001804}
1805
Teresa Johnson37687f32016-04-23 04:30:47 +00001806unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001807 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001808 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1810 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001811 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001812}
1813
Teresa Johnson37687f32016-04-23 04:30:47 +00001814void ModuleBitcodeWriter::writeNamedMetadata(
1815 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001816 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001817 return;
1818
Teresa Johnson37687f32016-04-23 04:30:47 +00001819 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001820 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001821 // Write name.
1822 StringRef Str = NMD.getName();
1823 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001824 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001825 Record.clear();
1826
1827 // Write named metadata operands.
1828 for (const MDNode *N : NMD.operands())
1829 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001830 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001831 Record.clear();
1832 }
1833}
1834
Teresa Johnson37687f32016-04-23 04:30:47 +00001835unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001836 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001837 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1838 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001841 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001842}
1843
1844/// Write out a record for MDString.
1845///
1846/// All the metadata strings in a metadata block are emitted in a single
1847/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001848void ModuleBitcodeWriter::writeMetadataStrings(
1849 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001850 if (Strings.empty())
1851 return;
1852
1853 // Start the record with the number of strings.
1854 Record.push_back(bitc::METADATA_STRINGS);
1855 Record.push_back(Strings.size());
1856
1857 // Emit the sizes of the strings in the blob.
1858 SmallString<256> Blob;
1859 {
1860 BitstreamWriter W(Blob);
1861 for (const Metadata *MD : Strings)
1862 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1863 W.FlushToWord();
1864 }
1865
1866 // Add the offset to the strings to the record.
1867 Record.push_back(Blob.size());
1868
1869 // Add the strings to the blob.
1870 for (const Metadata *MD : Strings)
1871 Blob.append(cast<MDString>(MD)->getString());
1872
1873 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001874 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001875 Record.clear();
1876}
1877
Mehdi Aminie98f9252016-12-28 22:30:28 +00001878// Generates an enum to use as an index in the Abbrev array of Metadata record.
1879enum MetadataAbbrev : unsigned {
1880#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1881#include "llvm/IR/Metadata.def"
1882 LastPlusOne
1883};
1884
Teresa Johnson37687f32016-04-23 04:30:47 +00001885void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001886 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1887 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001888 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001889 return;
1890
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001891 // Initialize MDNode abbreviations.
1892#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1893#include "llvm/IR/Metadata.def"
1894
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001895 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001896 if (IndexPos)
1897 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001898 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001899 assert(N->isResolved() && "Expected forward references to be resolved");
1900
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001901 switch (N->getMetadataID()) {
1902 default:
1903 llvm_unreachable("Invalid MDNode subclass");
1904#define HANDLE_MDNODE_LEAF(CLASS) \
1905 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001906 if (MDAbbrevs) \
1907 write##CLASS(cast<CLASS>(N), Record, \
1908 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1909 else \
1910 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001911 continue;
1912#include "llvm/IR/Metadata.def"
1913 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001914 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001915 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001916 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001917}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
Teresa Johnson37687f32016-04-23 04:30:47 +00001919void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001920 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001921 return;
1922
Mehdi Aminie98f9252016-12-28 22:30:28 +00001923 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001924 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001925
1926 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1927 // block and load any metadata.
1928 std::vector<unsigned> MDAbbrevs;
1929
1930 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1931 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1932 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1933 createGenericDINodeAbbrev();
1934
David Blaikie7ad9dc12017-01-04 22:36:33 +00001935 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001936 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001937 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1938 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001939 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001940
David Blaikie7ad9dc12017-01-04 22:36:33 +00001941 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001942 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1943 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1944 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001945 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001946
1947 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001948 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00001949
1950 // We only emit an index for the metadata record if we have more than a given
1951 // (naive) threshold of metadatas, otherwise it is not worth it.
1952 if (VE.getNonMDStrings().size() > IndexThreshold) {
1953 // Write a placeholder value in for the offset of the metadata index,
1954 // which is written after the records, so that it can include
1955 // the offset of each entry. The placeholder offset will be
1956 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00001957 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00001958 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1959 }
1960
1961 // Compute and save the bit offset to the current position, which will be
1962 // patched when we emit the index later. We can simply subtract the 64-bit
1963 // fixed size from the current bit number to get the location to backpatch.
1964 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1965
1966 // This index will contain the bitpos for each individual record.
1967 std::vector<uint64_t> IndexPos;
1968 IndexPos.reserve(VE.getNonMDStrings().size());
1969
1970 // Write all the records
1971 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1972
1973 if (VE.getNonMDStrings().size() > IndexThreshold) {
1974 // Now that we have emitted all the records we will emit the index. But
1975 // first
1976 // backpatch the forward reference so that the reader can skip the records
1977 // efficiently.
1978 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1979 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1980
1981 // Delta encode the index.
1982 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1983 for (auto &Elt : IndexPos) {
1984 auto EltDelta = Elt - PreviousValue;
1985 PreviousValue = Elt;
1986 Elt = EltDelta;
1987 }
1988 // Emit the index record.
1989 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1990 IndexPos.clear();
1991 }
1992
1993 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00001994 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00001995
1996 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1997 SmallVector<uint64_t, 4> Record;
1998 Record.push_back(VE.getValueID(&GO));
1999 pushGlobalMetadataAttachment(Record, GO);
2000 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2001 };
2002 for (const Function &F : M)
2003 if (F.isDeclaration() && F.hasMetadata())
2004 AddDeclAttachedMetadata(F);
2005 // FIXME: Only store metadata for declarations here, and move data for global
2006 // variable definitions to a separate block (PR28134).
2007 for (const GlobalVariable &GV : M.globals())
2008 if (GV.hasMetadata())
2009 AddDeclAttachedMetadata(GV);
2010
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002011 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002012}
2013
Teresa Johnson37687f32016-04-23 04:30:47 +00002014void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00002015 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002016 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002017
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002018 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002019 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00002020 writeMetadataStrings(VE.getMDStrings(), Record);
2021 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002022 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00002023}
2024
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002025void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2026 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2027 // [n x [id, mdnode]]
2028 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2029 GO.getAllMetadata(MDs);
2030 for (const auto &I : MDs) {
2031 Record.push_back(I.first);
2032 Record.push_back(VE.getMetadataID(I.second));
2033 }
2034}
2035
2036void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002037 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002038
Devang Patelaf206b82009-09-18 19:26:43 +00002039 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002040
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002041 if (F.hasMetadata()) {
2042 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002043 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002044 Record.clear();
2045 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002046
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002047 // Write metadata attachments
2048 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2049 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002050 for (const BasicBlock &BB : F)
2051 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00002052 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002053 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002054
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002055 // If no metadata, ignore instruction.
2056 if (MDs.empty()) continue;
2057
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002058 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002059
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002060 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2061 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002062 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00002063 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002064 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002065 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00002066 }
2067
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002068 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002069}
2070
Peter Collingbourne21521892016-06-21 23:42:48 +00002071void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00002072 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002073
Devang Patelaf206b82009-09-18 19:26:43 +00002074 // Write metadata kinds
2075 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00002076 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002077 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002078
Dan Gohman43aa8f02010-07-20 21:42:28 +00002079 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00002080
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002081 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002082
Dan Gohman43aa8f02010-07-20 21:42:28 +00002083 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00002084 Record.push_back(MDKindID);
2085 StringRef KName = Names[MDKindID];
2086 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002087
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002088 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002089 Record.clear();
2090 }
2091
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002092 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002093}
2094
Teresa Johnson37687f32016-04-23 04:30:47 +00002095void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002096 // Write metadata kinds
2097 //
2098 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2099 //
2100 // OPERAND_BUNDLE_TAG - [strchr x N]
2101
2102 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002103 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002104
2105 if (Tags.empty())
2106 return;
2107
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002108 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002109
2110 SmallVector<uint64_t, 64> Record;
2111
2112 for (auto Tag : Tags) {
2113 Record.append(Tag.begin(), Tag.end());
2114
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002115 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002116 Record.clear();
2117 }
2118
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002119 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002120}
2121
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002122void ModuleBitcodeWriter::writeSyncScopeNames() {
2123 SmallVector<StringRef, 8> SSNs;
2124 M.getContext().getSyncScopeNames(SSNs);
2125 if (SSNs.empty())
2126 return;
2127
2128 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2129
2130 SmallVector<uint64_t, 64> Record;
2131 for (auto SSN : SSNs) {
2132 Record.append(SSN.begin(), SSN.end());
2133 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2134 Record.clear();
2135 }
2136
2137 Stream.ExitBlock();
2138}
2139
Jan Wen Voungafaced02012-10-11 20:20:40 +00002140static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2141 if ((int64_t)V >= 0)
2142 Vals.push_back(V << 1);
2143 else
2144 Vals.push_back((-V << 1) | 1);
2145}
2146
Teresa Johnson37687f32016-04-23 04:30:47 +00002147void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2148 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002149 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002150
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002151 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002152
2153 unsigned AggregateAbbrev = 0;
2154 unsigned String8Abbrev = 0;
2155 unsigned CString7Abbrev = 0;
2156 unsigned CString6Abbrev = 0;
2157 // If this is a constant pool for the module, emit module-specific abbrevs.
2158 if (isGlobal) {
2159 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002160 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002161 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002164 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002165
2166 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002167 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002168 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002171 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002172 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002173 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002174 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002177 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002178 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002179 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002180 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002183 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002184 }
2185
Devang Patel8cca7b42009-08-04 05:01:35 +00002186 SmallVector<uint64_t, 64> Record;
2187
2188 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002189 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002190 for (unsigned i = FirstVal; i != LastVal; ++i) {
2191 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002192 // If we need to switch types, do so now.
2193 if (V->getType() != LastTy) {
2194 LastTy = V->getType();
2195 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002196 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2197 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002198 Record.clear();
2199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002200
Chris Lattner52523562007-04-24 00:16:04 +00002201 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002202 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002203 unsigned(IA->isAlignStack()) << 1 |
2204 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002205
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002206 // Add the asm string.
2207 const std::string &AsmStr = IA->getAsmString();
2208 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002209 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002210
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002211 // Add the constraint string.
2212 const std::string &ConstraintStr = IA->getConstraintString();
2213 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002214 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002215 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002216 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002217 continue;
2218 }
2219 const Constant *C = cast<Constant>(V);
2220 unsigned Code = -1U;
2221 unsigned AbbrevToUse = 0;
2222 if (C->isNullValue()) {
2223 Code = bitc::CST_CODE_NULL;
2224 } else if (isa<UndefValue>(C)) {
2225 Code = bitc::CST_CODE_UNDEF;
2226 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002227 if (IV->getBitWidth() <= 64) {
2228 uint64_t V = IV->getSExtValue();
2229 emitSignedInt64(Record, V);
2230 Code = bitc::CST_CODE_INTEGER;
2231 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2232 } else { // Wide integers, > 64 bits in size.
2233 // We have an arbitrary precision integer value to write whose
2234 // bit width is > 64. However, in canonical unsigned integer
2235 // format it is likely that the high bits are going to be zero.
2236 // So, we only write the number of active words.
2237 unsigned NWords = IV->getValue().getActiveWords();
2238 const uint64_t *RawWords = IV->getValue().getRawData();
2239 for (unsigned i = 0; i != NWords; ++i) {
2240 emitSignedInt64(Record, RawWords[i]);
2241 }
2242 Code = bitc::CST_CODE_WIDE_INTEGER;
2243 }
Chris Lattner52523562007-04-24 00:16:04 +00002244 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2245 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002246 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002247 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002248 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002249 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002250 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002251 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002252 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002253 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002254 Record.push_back((p[1] << 48) | (p[0] >> 16));
2255 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002256 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002257 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002258 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002259 Record.push_back(p[0]);
2260 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002261 } else {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002262 assert(0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002263 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002264 } else if (isa<ConstantDataSequential>(C) &&
2265 cast<ConstantDataSequential>(C)->isString()) {
2266 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2267 // Emit constant strings specially.
2268 unsigned NumElts = Str->getNumElements();
2269 // If this is a null-terminated string, use the denser CSTRING encoding.
2270 if (Str->isCString()) {
2271 Code = bitc::CST_CODE_CSTRING;
2272 --NumElts; // Don't encode the null, which isn't allowed by char6.
2273 } else {
2274 Code = bitc::CST_CODE_STRING;
2275 AbbrevToUse = String8Abbrev;
2276 }
2277 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2278 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2279 for (unsigned i = 0; i != NumElts; ++i) {
2280 unsigned char V = Str->getElementAsInteger(i);
2281 Record.push_back(V);
2282 isCStr7 &= (V & 128) == 0;
2283 if (isCStrChar6)
2284 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2285 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002286
Chris Lattner372dd1e2012-01-30 00:51:16 +00002287 if (isCStrChar6)
2288 AbbrevToUse = CString6Abbrev;
2289 else if (isCStr7)
2290 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002291 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002292 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002293 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002294 Type *EltTy = CDS->getType()->getElementType();
2295 if (isa<IntegerType>(EltTy)) {
2296 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2297 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002298 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002299 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2300 Record.push_back(
2301 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002302 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002303 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002304 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002305 for (const Value *Op : C->operands())
2306 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002307 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002308 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002309 switch (CE->getOpcode()) {
2310 default:
2311 if (Instruction::isCast(CE->getOpcode())) {
2312 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002313 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002314 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2315 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002316 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002317 } else {
2318 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2319 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002320 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002321 Record.push_back(VE.getValueID(C->getOperand(0)));
2322 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002323 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002324 if (Flags != 0)
2325 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002326 }
2327 break;
David Blaikieb9263572015-03-13 21:03:36 +00002328 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002329 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002330 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002331 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002332 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2333 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2334 Record.push_back((*Idx << 1) | GO->isInBounds());
2335 } else if (GO->isInBounds())
2336 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002337 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2338 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2339 Record.push_back(VE.getValueID(C->getOperand(i)));
2340 }
2341 break;
David Blaikieb9263572015-03-13 21:03:36 +00002342 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002343 case Instruction::Select:
2344 Code = bitc::CST_CODE_CE_SELECT;
2345 Record.push_back(VE.getValueID(C->getOperand(0)));
2346 Record.push_back(VE.getValueID(C->getOperand(1)));
2347 Record.push_back(VE.getValueID(C->getOperand(2)));
2348 break;
2349 case Instruction::ExtractElement:
2350 Code = bitc::CST_CODE_CE_EXTRACTELT;
2351 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2352 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002353 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002354 Record.push_back(VE.getValueID(C->getOperand(1)));
2355 break;
2356 case Instruction::InsertElement:
2357 Code = bitc::CST_CODE_CE_INSERTELT;
2358 Record.push_back(VE.getValueID(C->getOperand(0)));
2359 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002360 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002361 Record.push_back(VE.getValueID(C->getOperand(2)));
2362 break;
2363 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002364 // If the return type and argument types are the same, this is a
2365 // standard shufflevector instruction. If the types are different,
2366 // then the shuffle is widening or truncating the input vectors, and
2367 // the argument type must also be encoded.
2368 if (C->getType() == C->getOperand(0)->getType()) {
2369 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2370 } else {
2371 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2372 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2373 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002374 Record.push_back(VE.getValueID(C->getOperand(0)));
2375 Record.push_back(VE.getValueID(C->getOperand(1)));
2376 Record.push_back(VE.getValueID(C->getOperand(2)));
2377 break;
2378 case Instruction::ICmp:
2379 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002380 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002381 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2382 Record.push_back(VE.getValueID(C->getOperand(0)));
2383 Record.push_back(VE.getValueID(C->getOperand(1)));
2384 Record.push_back(CE->getPredicate());
2385 break;
2386 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002387 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002388 Code = bitc::CST_CODE_BLOCKADDRESS;
2389 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2390 Record.push_back(VE.getValueID(BA->getFunction()));
2391 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002392 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002393#ifndef NDEBUG
2394 C->dump();
2395#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002396 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002397 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002398 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002399 Record.clear();
2400 }
2401
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002402 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002403}
2404
Teresa Johnson37687f32016-04-23 04:30:47 +00002405void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002406 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002407
Chris Lattner52523562007-04-24 00:16:04 +00002408 // Find the first constant to emit, which is the first non-globalvalue value.
2409 // We know globalvalues have been emitted by WriteModuleInfo.
2410 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2411 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002412 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002413 return;
2414 }
2415 }
2416}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002417
Teresa Johnson37687f32016-04-23 04:30:47 +00002418/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002419/// many values, because we need to know what type to create for forward
2420/// references. However, most operands are not forward references, so this type
2421/// field is not needed.
2422///
2423/// This function adds V's value ID to Vals. If the value ID is higher than the
2424/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002425/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002426bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2427 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002428 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002429 // Make encoding relative to the InstID.
2430 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002431 if (ValID >= InstID) {
2432 Vals.push_back(VE.getTypeID(V->getType()));
2433 return true;
2434 }
2435 return false;
2436}
2437
Teresa Johnson37687f32016-04-23 04:30:47 +00002438void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2439 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002440 SmallVector<unsigned, 64> Record;
2441 LLVMContext &C = CS.getInstruction()->getContext();
2442
2443 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002444 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002445 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002446
2447 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002448 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002449
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002450 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002451 Record.clear();
2452 }
2453}
2454
Teresa Johnson37687f32016-04-23 04:30:47 +00002455/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002456/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002457void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2458 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002459 unsigned ValID = VE.getValueID(V);
2460 Vals.push_back(InstID - ValID);
2461}
2462
Teresa Johnson37687f32016-04-23 04:30:47 +00002463void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2464 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002465 unsigned ValID = VE.getValueID(V);
2466 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2467 emitSignedInt64(Vals, diff);
2468}
2469
Chris Lattnere6e364c2007-04-26 05:53:54 +00002470/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002471void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2472 unsigned InstID,
2473 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002474 unsigned Code = 0;
2475 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002476 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002477 switch (I.getOpcode()) {
2478 default:
2479 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002480 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002481 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002482 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002483 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002484 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002485 } else {
2486 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002487 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002488 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002489 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002490 pushValue(I.getOperand(1), InstID, Vals);
2491 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2492 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002493 if (Flags != 0) {
2494 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2495 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2496 Vals.push_back(Flags);
2497 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002498 }
2499 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002500
David Blaikieb5b5efd2015-02-25 01:08:52 +00002501 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002502 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002503 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2504 auto &GEPInst = cast<GetElementPtrInst>(I);
2505 Vals.push_back(GEPInst.isInBounds());
2506 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002507 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002508 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002509 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002510 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002511 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002512 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002513 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002514 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002515 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002516 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002517 }
2518 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002519 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002520 pushValueAndType(I.getOperand(0), InstID, Vals);
2521 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002522 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002523 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002524 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002525 }
Chris Lattner0a603252007-05-01 02:13:26 +00002526 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002527 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002528 pushValueAndType(I.getOperand(1), InstID, Vals);
2529 pushValue(I.getOperand(2), InstID, Vals);
2530 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002531 break;
2532 case Instruction::ExtractElement:
2533 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002534 pushValueAndType(I.getOperand(0), InstID, Vals);
2535 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002536 break;
2537 case Instruction::InsertElement:
2538 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002539 pushValueAndType(I.getOperand(0), InstID, Vals);
2540 pushValue(I.getOperand(1), InstID, Vals);
2541 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002542 break;
2543 case Instruction::ShuffleVector:
2544 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002545 pushValueAndType(I.getOperand(0), InstID, Vals);
2546 pushValue(I.getOperand(1), InstID, Vals);
2547 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002548 break;
2549 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002550 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002551 // compare returning Int1Ty or vector of Int1Ty
2552 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002553 pushValueAndType(I.getOperand(0), InstID, Vals);
2554 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002555 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002556 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002557 if (Flags != 0)
2558 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002559 break;
James Molloy88eb5352015-07-10 12:52:00 +00002560 }
Chris Lattner0a603252007-05-01 02:13:26 +00002561
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002562 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002563 {
2564 Code = bitc::FUNC_CODE_INST_RET;
2565 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002566 if (NumOperands == 0)
2567 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2568 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002569 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002570 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2571 } else {
2572 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002573 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002574 }
2575 }
Chris Lattner0a603252007-05-01 02:13:26 +00002576 break;
2577 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002578 {
2579 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002580 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002581 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2582 if (II.isConditional()) {
2583 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002584 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002585 }
Chris Lattner0a603252007-05-01 02:13:26 +00002586 }
2587 break;
2588 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002589 {
2590 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002591 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002592 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002593 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002594 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002595 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002596 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2597 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002598 }
2599 }
Chris Lattner0a603252007-05-01 02:13:26 +00002600 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002601 case Instruction::IndirectBr:
2602 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002603 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002604 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002605 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002606 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002607 Vals.push_back(VE.getValueID(I.getOperand(i)));
2608 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002609
Chris Lattnerb811e952007-05-01 07:03:37 +00002610 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002611 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002612 const Value *Callee = II->getCalledValue();
2613 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002614
2615 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002616 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002617
Chris Lattner0a603252007-05-01 02:13:26 +00002618 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002619
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002620 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002621 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002622 Vals.push_back(VE.getValueID(II->getNormalDest()));
2623 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002624 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002625 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Chris Lattner0a603252007-05-01 02:13:26 +00002627 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002628 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002629 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002630
2631 // Emit type/value pairs for varargs params.
2632 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002633 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002634 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002635 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002636 }
2637 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002638 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002639 case Instruction::Resume:
2640 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002641 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002642 break;
David Majnemer654e1302015-07-31 17:58:14 +00002643 case Instruction::CleanupRet: {
2644 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2645 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002646 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002647 if (CRI.hasUnwindDest())
2648 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2649 break;
2650 }
2651 case Instruction::CatchRet: {
2652 Code = bitc::FUNC_CODE_INST_CATCHRET;
2653 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002654 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002655 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2656 break;
2657 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002658 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002659 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002660 const auto &FuncletPad = cast<FuncletPadInst>(I);
2661 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2662 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002663 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002664
2665 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002666 Vals.push_back(NumArgOperands);
2667 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002668 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002669 break;
2670 }
2671 case Instruction::CatchSwitch: {
2672 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2673 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2674
Teresa Johnson37687f32016-04-23 04:30:47 +00002675 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002676
2677 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2678 Vals.push_back(NumHandlers);
2679 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2680 Vals.push_back(VE.getValueID(CatchPadBB));
2681
2682 if (CatchSwitch.hasUnwindDest())
2683 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002684 break;
2685 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002686 case Instruction::Unreachable:
2687 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002688 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002689 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Jay Foad372ad642011-06-20 14:18:48 +00002691 case Instruction::PHI: {
2692 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002693 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002694 // With the newer instruction encoding, forward references could give
2695 // negative valued IDs. This is most common for PHIs, so we use
2696 // signed VBRs.
2697 SmallVector<uint64_t, 128> Vals64;
2698 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002699 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002700 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002701 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002702 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002703 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002704 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002705 Vals64.clear();
2706 return;
Jay Foad372ad642011-06-20 14:18:48 +00002707 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002708
Bill Wendlingfae14752011-08-12 20:24:12 +00002709 case Instruction::LandingPad: {
2710 const LandingPadInst &LP = cast<LandingPadInst>(I);
2711 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2712 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002713 Vals.push_back(LP.isCleanup());
2714 Vals.push_back(LP.getNumClauses());
2715 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2716 if (LP.isCatch(I))
2717 Vals.push_back(LandingPadInst::Catch);
2718 else
2719 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002720 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002721 }
2722 break;
2723 }
2724
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002725 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002726 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002727 const AllocaInst &AI = cast<AllocaInst>(I);
2728 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002729 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002730 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002731 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2732 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2733 "not enough bits for maximum alignment");
2734 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2735 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002736 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002737 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002738 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002739 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002740 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002741
Chris Lattner0a603252007-05-01 02:13:26 +00002742 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002743 if (cast<LoadInst>(I).isAtomic()) {
2744 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002745 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002746 } else {
2747 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002748 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002749 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2750 }
David Blaikie85035652015-02-25 01:07:20 +00002751 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002752 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2753 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002754 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002755 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002756 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002757 }
Chris Lattner0a603252007-05-01 02:13:26 +00002758 break;
2759 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002760 if (cast<StoreInst>(I).isAtomic())
2761 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2762 else
2763 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002764 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2765 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002766 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2767 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002768 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002769 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002770 Vals.push_back(
2771 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002772 }
Chris Lattner0a603252007-05-01 02:13:26 +00002773 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002774 case Instruction::AtomicCmpXchg:
2775 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002776 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2777 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2778 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002779 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002780 Vals.push_back(
2781 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2782 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002783 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002784 Vals.push_back(
2785 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002786 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002787 break;
2788 case Instruction::AtomicRMW:
2789 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002790 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2791 pushValue(I.getOperand(1), InstID, Vals); // val.
2792 Vals.push_back(
2793 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002794 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002795 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2796 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002797 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002798 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002799 case Instruction::Fence:
2800 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002801 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002802 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002803 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002804 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002805 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002806 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002807
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002808 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002809 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002810
Chris Lattnerc44070802011-06-17 18:17:37 +00002811 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002812
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002813 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002814
Teresa Johnson37687f32016-04-23 04:30:47 +00002815 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002816 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2817 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2818 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2819 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002820 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2821 unsigned(Flags != 0) << bitc::CALL_FMF);
2822 if (Flags != 0)
2823 Vals.push_back(Flags);
2824
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002825 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002826 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002827
Chris Lattner0a603252007-05-01 02:13:26 +00002828 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002829 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2830 // Check for labels (can happen with asm labels).
2831 if (FTy->getParamType(i)->isLabelTy())
2832 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2833 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002834 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002835 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002836
Chris Lattnerb811e952007-05-01 07:03:37 +00002837 // Emit type/value pairs for varargs params.
2838 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002839 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002840 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002841 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002842 }
2843 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002844 }
Chris Lattner0a603252007-05-01 02:13:26 +00002845 case Instruction::VAArg:
2846 Code = bitc::FUNC_CODE_INST_VAARG;
2847 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002848 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002849 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2850 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002851 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002852
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002853 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002854 Vals.clear();
2855}
2856
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002857/// Write a GlobalValue VST to the module. The purpose of this data structure is
2858/// to allow clients to efficiently find the function body.
2859void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2860 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2861 // Get the offset of the VST we are writing, and backpatch it into
2862 // the VST forward declaration record.
2863 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2864 // The BitcodeStartBit was the stream offset of the identification block.
2865 VSTOffset -= bitcodeStartBit();
2866 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2867 // Note that we add 1 here because the offset is relative to one word
2868 // before the start of the identification block, which was historically
2869 // always the start of the regular bitcode header.
2870 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002871
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002872 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002873
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002874 auto Abbv = std::make_shared<BitCodeAbbrev>();
2875 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2876 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2878 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002879
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002880 for (const Function &F : M) {
2881 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002882
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002883 if (F.isDeclaration())
2884 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002885
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002886 Record[0] = VE.getValueID(&F);
2887
2888 // Save the word offset of the function (from the start of the
2889 // actual bitcode written to the stream).
2890 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2891 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2892 // Note that we add 1 here because the offset is relative to one word
2893 // before the start of the identification block, which was historically
2894 // always the start of the regular bitcode header.
2895 Record[1] = BitcodeIndex / 32 + 1;
2896
2897 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002898 }
2899
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002900 Stream.ExitBlock();
2901}
2902
2903/// Emit names for arguments, instructions and basic blocks in a function.
2904void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2905 const ValueSymbolTable &VST) {
2906 if (VST.empty())
2907 return;
2908
2909 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2910
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002911 // FIXME: Set up the abbrev, we know how many values there are!
2912 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002913 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002914
Yaron Keren001e2e42015-08-10 07:04:29 +00002915 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002916 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00002917 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002918
Chris Lattnera0987962007-05-04 21:31:13 +00002919 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002920 NameVals.push_back(VE.getValueID(Name.getValue()));
2921
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002922 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002923 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002924 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002925 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002926 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002927 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002928 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002929 } else {
2930 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002931 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002932 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002933 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002934 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002935 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002936
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002937 for (const auto P : Name.getKey())
2938 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002939
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002940 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002941 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002942 NameVals.clear();
2943 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002944
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002945 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002946}
2947
Teresa Johnson37687f32016-04-23 04:30:47 +00002948void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002949 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2950 unsigned Code;
2951 if (isa<BasicBlock>(Order.V))
2952 Code = bitc::USELIST_CODE_BB;
2953 else
2954 Code = bitc::USELIST_CODE_DEFAULT;
2955
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002956 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002957 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002958 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002959}
2960
Teresa Johnson37687f32016-04-23 04:30:47 +00002961void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002962 assert(VE.shouldPreserveUseListOrder() &&
2963 "Expected to be preserving use-list order");
2964
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002965 auto hasMore = [&]() {
2966 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2967 };
2968 if (!hasMore())
2969 // Nothing to do.
2970 return;
2971
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002972 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002973 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002974 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002975 VE.UseListOrders.pop_back();
2976 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002977 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002978}
2979
Teresa Johnson403a7872015-10-04 14:33:43 +00002980/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002981void ModuleBitcodeWriter::writeFunction(
2982 const Function &F,
2983 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002984 // Save the bitcode index of the start of this function block for recording
2985 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002986 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002987
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002988 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002989 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002990
2991 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002992
Chris Lattnere6e364c2007-04-26 05:53:54 +00002993 // Emit the number of basic blocks, so the reader can create them ahead of
2994 // time.
2995 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002996 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002997 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002998
Chris Lattnere6e364c2007-04-26 05:53:54 +00002999 // If there are function-local constants, emit them now.
3000 unsigned CstStart, CstEnd;
3001 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00003002 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003003
Victor Hernandez6c730de2010-01-14 01:50:08 +00003004 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00003005 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00003006
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003007 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003008 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003009
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003010 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003011
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003012 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00003013 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003014 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003015 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3016 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003017 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003018
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00003019 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003020 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003021
Chris Lattner07d09ed2010-04-03 02:17:50 +00003022 // If the instruction has metadata, write a metadata attachment later.
3023 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003024
Chris Lattner07d09ed2010-04-03 02:17:50 +00003025 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003026 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003027 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003028 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003029
3030 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00003031 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003032 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003033 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003034 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003035
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003036 Vals.push_back(DL->getLine());
3037 Vals.push_back(DL->getColumn());
3038 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3039 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003040 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003041 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00003042
3043 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003044 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003045
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003046 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003047 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003048 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00003049
Chris Lattner07d09ed2010-04-03 02:17:50 +00003050 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003051 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003052 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003053 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00003054 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003055 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00003056}
3057
Chris Lattner702658c2007-05-04 18:26:27 +00003058// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003059void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00003060 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00003061 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00003062 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00003063 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003064
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003065 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003066 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3069 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003071 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003072 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003073 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003074 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003075
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003076 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003077 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003078 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3080 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3081 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003082 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003083 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003084 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003085 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003086 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003087 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00003088 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3091 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003092 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003093 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003094 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00003095 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003096 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003097 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003098 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3099 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00003101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003102 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003103 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003104 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003105 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003106
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003107 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003108 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003109 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003111 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003112 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003113 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003114 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003115 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003116
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003117 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003118 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003119 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3120 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003121 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003122 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003123 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003124 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003125
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003126 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003127 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003128 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003131 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3133
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003134 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003135 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003136 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003137 }
3138 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003139 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003140 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003141 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003142 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003143 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003144 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003145
Chris Lattnerb80751d2007-05-05 07:44:49 +00003146 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003147
Chris Lattnerb80751d2007-05-05 07:44:49 +00003148 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003149 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003150 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003152 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3153 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003156 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003157 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003158 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003159 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003160 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003161 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003162 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003166 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003167 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003168 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003169 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003170 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003171 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003172 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3175 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3176 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003177 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003178 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003179 llvm_unreachable("Unexpected abbrev ordering!");
3180 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003181 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003182 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003183 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3185 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003186 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003188 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003189 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003190 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003192
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003193 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003194 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003195 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003196 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003197 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003198 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003199 }
3200 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003201 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003202 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3203 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003204 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003205 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003206 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003207 }
3208 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003209 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003210 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003211 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003212 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003213 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003214 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003215 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003216 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003217 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3220 Log2_32_Ceil(VE.getTypes().size() + 1)));
3221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003223 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003224 FUNCTION_INST_GEP_ABBREV)
3225 llvm_unreachable("Unexpected abbrev ordering!");
3226 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003227
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003228 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003229}
3230
Teresa Johnson403a7872015-10-04 14:33:43 +00003231/// Write the module path strings, currently only used when generating
3232/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003233void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003234 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003235
3236 // TODO: See which abbrev sizes we actually need to emit
3237
3238 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003239 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003240 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3241 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003244 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003245
3246 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003247 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003248 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003252 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003253
3254 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003255 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003256 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3257 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3259 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003260 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003261
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003262 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003263 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003264 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3265 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3266 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3267 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3268 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3269 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003270 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003271
3272 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003273 forEachModule(
3274 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003275 StringRef Key = MPSE.getKey();
3276 const auto &Value = MPSE.getValue();
3277 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003278 unsigned AbbrevToUse = Abbrev8Bit;
3279 if (Bits == SE_Char6)
3280 AbbrevToUse = Abbrev6Bit;
3281 else if (Bits == SE_Fixed7)
3282 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003283
David Blaikieb6b42e02017-06-02 17:24:26 +00003284 Vals.push_back(Value.first);
3285 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003286
Teresa Johnson7a27b132017-06-02 01:56:02 +00003287 // Emit the finished record.
3288 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003289
Teresa Johnson7a27b132017-06-02 01:56:02 +00003290 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003291 const auto &Hash = Value.second;
3292 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3293 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003294 // Emit the hash record.
3295 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3296 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003297
Teresa Johnson7a27b132017-06-02 01:56:02 +00003298 Vals.clear();
3299 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003300 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003301}
3302
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003303/// Write the function type metadata related records that need to appear before
3304/// a function summary entry (whether per-module or combined).
3305static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3306 FunctionSummary *FS) {
3307 if (!FS->type_tests().empty())
3308 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3309
3310 SmallVector<uint64_t, 64> Record;
3311
3312 auto WriteVFuncIdVec = [&](uint64_t Ty,
3313 ArrayRef<FunctionSummary::VFuncId> VFs) {
3314 if (VFs.empty())
3315 return;
3316 Record.clear();
3317 for (auto &VF : VFs) {
3318 Record.push_back(VF.GUID);
3319 Record.push_back(VF.Offset);
3320 }
3321 Stream.EmitRecord(Ty, Record);
3322 };
3323
3324 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3325 FS->type_test_assume_vcalls());
3326 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3327 FS->type_checked_load_vcalls());
3328
3329 auto WriteConstVCallVec = [&](uint64_t Ty,
3330 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3331 for (auto &VC : VCs) {
3332 Record.clear();
3333 Record.push_back(VC.VFunc.GUID);
3334 Record.push_back(VC.VFunc.Offset);
3335 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3336 Stream.EmitRecord(Ty, Record);
3337 }
3338 };
3339
3340 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3341 FS->type_test_assume_const_vcalls());
3342 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3343 FS->type_checked_load_const_vcalls());
3344}
3345
Teresa Johnson403a7872015-10-04 14:33:43 +00003346// Helper to emit a single function summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003347void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003348 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003349 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3350 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003351 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003352
Teresa Johnson28e457b2016-04-24 14:57:11 +00003353 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003354 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003355
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003356 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003357 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003358 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003359 NameVals.push_back(FS->refs().size());
3360
3361 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003362 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003363
3364 bool HasProfileData = F.getEntryCount().hasValue();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003365 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003366 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003367 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003368 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003369 }
3370
3371 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3372 unsigned Code =
3373 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003374
3375 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003376 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003377 NameVals.clear();
3378}
3379
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003380// Collect the global value references in the given variable's initializer,
3381// and emit them in a summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003382void ModuleBitcodeWriterBase::writeModuleLevelReferences(
Teresa Johnson37687f32016-04-23 04:30:47 +00003383 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3384 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003385 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3386 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003387 // Only declarations should not have a summary (a declaration might however
3388 // have a summary if the def was in module level asm).
3389 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003390 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003391 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003392 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003393 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003394 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003395 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003396
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003397 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003398 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003399 NameVals.push_back(VE.getValueID(RI.getValue()));
3400 // Sort the refs for determinism output, the vector returned by FS->refs() has
3401 // been initialized from a DenseSet.
3402 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003403
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003404 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3405 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003406 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003407}
Teresa Johnson403a7872015-10-04 14:33:43 +00003408
Mehdi Amini8fe69362016-04-24 03:18:11 +00003409// Current version for the summary.
3410// This is bumped whenever we introduce changes in the way some record are
3411// interpreted, like flags for instance.
Charles Saternos75da10d2017-08-04 16:00:58 +00003412static const uint64_t INDEX_VERSION = 4;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003413
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003414/// Emit the per-module summary section alongside the rest of
3415/// the module's bitcode.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003416void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003417 // By default we compile with ThinLTO if the module has a summary, but the
3418 // client can request full LTO with a module flag.
3419 bool IsThinLTO = true;
3420 if (auto *MD =
3421 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3422 IsThinLTO = MD->getZExtValue();
3423 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3424 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3425 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003426
Mehdi Amini8fe69362016-04-24 03:18:11 +00003427 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3428
Teresa Johnson620c1402016-09-20 23:07:17 +00003429 if (Index->begin() == Index->end()) {
3430 Stream.ExitBlock();
3431 return;
3432 }
3433
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003434 for (const auto &GVI : valueIds()) {
3435 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3436 ArrayRef<uint64_t>{GVI.second, GVI.first});
3437 }
3438
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003439 // Abbrev for FS_PERMODULE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003440 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003441 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003447 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003450 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003451
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003452 // Abbrev for FS_PERMODULE_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003453 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003454 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003460 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003463 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003464
3465 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003466 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003467 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003469 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003472 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003473
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003474 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003475 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003476 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3477 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003480 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003481
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003482 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003483 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003484 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003485 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003486 // Summary emission does not support anonymous functions, they have to
3487 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003488 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003489 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003490
Peter Collingbourne9667b912017-05-04 18:03:25 +00003491 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3492 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003493 // Only declarations should not have a summary (a declaration might
3494 // however have a summary if the def was in module level asm).
3495 assert(F.isDeclaration());
3496 continue;
3497 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003498 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003499 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3500 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003501 }
3502
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003503 // Capture references from GlobalVariable initializers, which are outside
3504 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003505 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003506 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003507
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003508 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003509 auto *Aliasee = A.getBaseObject();
3510 if (!Aliasee->hasName())
3511 // Nameless function don't have an entry in the summary, skip it.
3512 continue;
3513 auto AliasId = VE.getValueID(&A);
3514 auto AliaseeId = VE.getValueID(Aliasee);
3515 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003516 auto *Summary = Index->getGlobalValueSummary(A);
3517 AliasSummary *AS = cast<AliasSummary>(Summary);
3518 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003519 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003520 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003521 NameVals.clear();
3522 }
3523
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003524 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003525}
3526
Teresa Johnson26ab5772016-03-15 00:04:37 +00003527/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003528void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003529 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003530 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003531
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003532 for (const auto &GVI : valueIds()) {
3533 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3534 ArrayRef<uint64_t>{GVI.second, GVI.first});
3535 }
3536
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003537 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003538 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003539 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003540 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003541 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003542 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003543 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003544 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003545 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003546 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003547 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3548 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003549 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003550
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003551 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003552 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003553 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003554 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003555 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003556 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003557 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003558 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003559 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003560 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003561 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3562 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003563 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003564
3565 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003566 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003567 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003568 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003569 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003570 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003571 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003573 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003574
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003575 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003576 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003577 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003582 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003583
Teresa Johnson02e98332016-04-27 13:28:35 +00003584 // The aliases are emitted as a post-pass, and will point to the value
3585 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003586 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003587
Teresa Johnson02e98332016-04-27 13:28:35 +00003588 // Save the value id for each summary for alias emission.
3589 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3590
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003591 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003592
3593 // For local linkage, we also emit the original name separately
3594 // immediately after the record.
3595 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3596 if (!GlobalValue::isLocalLinkage(S.linkage()))
3597 return;
3598 NameVals.push_back(S.getOriginalName());
3599 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3600 NameVals.clear();
3601 };
3602
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003603 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003604 GlobalValueSummary *S = I.second;
3605 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003606
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003607 auto ValueId = getValueId(I.first);
3608 assert(ValueId);
3609 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003610
Teresa Johnson84174c32016-05-10 13:48:23 +00003611 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3612 // Will process aliases as a post-pass because the reader wants all
3613 // global to be loaded first.
3614 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003615 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003616 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003617
Teresa Johnson84174c32016-05-10 13:48:23 +00003618 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003619 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003620 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3621 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3622 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003623 auto RefValueId = getValueId(RI.getGUID());
3624 if (!RefValueId)
3625 continue;
3626 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003627 }
3628
Teresa Johnson403a7872015-10-04 14:33:43 +00003629 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003630 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3631 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003632 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003633 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003634 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003635 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003636
3637 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003638 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003639
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003640 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003641 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3642 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3643 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003644 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003645 // Fill in below
3646 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003647
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003648 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003649 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003650 auto RefValueId = getValueId(RI.getGUID());
3651 if (!RefValueId)
3652 continue;
3653 NameVals.push_back(*RefValueId);
3654 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003655 }
Charles Saternos75da10d2017-08-04 16:00:58 +00003656 NameVals[5] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003657
3658 bool HasProfileData = false;
3659 for (auto &EI : FS->calls()) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003660 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003661 if (HasProfileData)
3662 break;
3663 }
3664
3665 for (auto &EI : FS->calls()) {
3666 // If this GUID doesn't have a value id, it doesn't have a function
3667 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003668 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003669 auto CallValueId = getValueId(GUID);
3670 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003671 // For SamplePGO, the indirect call targets for local functions will
3672 // have its original name annotated in profile. We try to find the
3673 // corresponding PGOFuncName as the GUID.
3674 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003675 if (GUID == 0)
3676 continue;
3677 CallValueId = getValueId(GUID);
3678 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003679 continue;
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003680 // The mapping from OriginalId to GUID may return a GUID
Xinliang David Li5a57b842017-08-16 17:33:43 +00003681 // that corresponds to a static variable. Filter it out here.
3682 // This can happen when
3683 // 1) There is a call to a library function which does not have
3684 // a CallValidId;
3685 // 2) There is a static variable with the OriginalGUID identical
3686 // to the GUID of the library function in 1);
3687 // When this happens, the logic for SamplePGO kicks in and
Mandeep Singh Grang1be19e62017-09-15 20:01:43 +00003688 // the static variable in 2) will be found, which needs to be
Xinliang David Li5a57b842017-08-16 17:33:43 +00003689 // filtered out.
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003690 auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3691 if (GVSum &&
3692 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3693 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +00003694 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003695 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003696 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003697 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003698 }
3699
3700 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3701 unsigned Code =
3702 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3703
3704 // Emit the finished record.
3705 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3706 NameVals.clear();
3707 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003708 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003709
Teresa Johnson28e457b2016-04-24 14:57:11 +00003710 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003711 auto AliasValueId = SummaryToValueIdMap[AS];
3712 assert(AliasValueId);
3713 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003714 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003715 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003716 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3717 assert(AliaseeValueId);
3718 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003719
3720 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003721 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003722 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003723 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003724 }
3725
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003726 if (!Index.cfiFunctionDefs().empty()) {
3727 for (auto &S : Index.cfiFunctionDefs()) {
3728 NameVals.push_back(StrtabBuilder.add(S));
3729 NameVals.push_back(S.size());
3730 }
3731 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3732 NameVals.clear();
3733 }
3734
3735 if (!Index.cfiFunctionDecls().empty()) {
3736 for (auto &S : Index.cfiFunctionDecls()) {
3737 NameVals.push_back(StrtabBuilder.add(S));
3738 NameVals.push_back(S.size());
3739 }
3740 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3741 NameVals.clear();
3742 }
3743
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003744 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003745}
3746
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003747/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3748/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003749static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003750 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003751
3752 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003753 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003754 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3755 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3756 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003757 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003758 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003759 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003760
3761 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003762 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003763 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003765 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003766 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003767 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3768 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003769}
3770
Teresa Johnson37687f32016-04-23 04:30:47 +00003771void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003772 // Emit the module's hash.
3773 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003774 if (GenerateHash) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003775 uint32_t Vals[5];
3776 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3777 Buffer.size() - BlockStartPos));
3778 StringRef Hash = Hasher.result();
3779 for (int Pos = 0; Pos < 20; Pos += 4) {
3780 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3781 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003782
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003783 // Emit the finished record.
3784 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3785
3786 if (ModHash)
3787 // Save the written hash value.
3788 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
Haojie Wang1dec57d2017-07-21 17:25:20 +00003789 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003790}
3791
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003792void ModuleBitcodeWriter::write() {
3793 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003794
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003795 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3796 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003797
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003798 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003799
3800 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003801 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003802
Bill Wendlingdc095552013-02-10 23:09:32 +00003803 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003804 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003805
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003806 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003807 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003808
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003809 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003810 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003811
Teresa Johnson37687f32016-04-23 04:30:47 +00003812 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003813
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003814 // Emit top-level description of module, including target triple, inline asm,
3815 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003816 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003817
Devang Patele059ba6e2009-07-23 01:07:34 +00003818 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003819 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003820
Peter Collingbourne21521892016-06-21 23:42:48 +00003821 // Emit metadata kind names.
3822 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003823
Devang Patelaf206b82009-09-18 19:26:43 +00003824 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003825 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003826
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003827 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003828 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003829 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003830
Teresa Johnson37687f32016-04-23 04:30:47 +00003831 writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003832 writeSyncScopeNames();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003833
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003834 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003835 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003836 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003837 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003838 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003839
3840 // Need to write after the above call to WriteFunction which populates
3841 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003842 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003843 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003844
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003845 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003846
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003847 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003848
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003849 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003850}
3851
Teresa Johnson37687f32016-04-23 04:30:47 +00003852static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3853 uint32_t &Position) {
3854 support::endian::write32le(&Buffer[Position], Value);
3855 Position += 4;
3856}
3857
3858/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003859/// header and trailer to make it compatible with the system archiver. To do
3860/// this we emit the following header, and then emit a trailer that pads the
3861/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003862///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003863/// struct bc_header {
3864/// uint32_t Magic; // 0x0B17C0DE
3865/// uint32_t Version; // Version, currently always 0.
3866/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3867/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3868/// uint32_t CPUType; // CPU specifier.
3869/// ... potentially more later ...
3870/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003871static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003872 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003873 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003874
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003875 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003876 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3877 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3878 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003879 enum {
3880 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3881 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003882 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003883 DARWIN_CPU_TYPE_POWERPC = 18
3884 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003885
Evan Chengcffdcae2011-06-14 01:51:33 +00003886 Triple::ArchType Arch = TT.getArch();
3887 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003888 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003889 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003890 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003891 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003892 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003893 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003894 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003895 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003896 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003897
Chris Lattnera660f4b2008-07-09 05:14:23 +00003898 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003899 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003900 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003901 unsigned BCOffset = BWH_HeaderSize;
3902 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003903
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003904 // Write the magic and version.
3905 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003906 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3907 writeInt32ToBuffer(0, Buffer, Position); // Version.
3908 writeInt32ToBuffer(BCOffset, Buffer, Position);
3909 writeInt32ToBuffer(BCSize, Buffer, Position);
3910 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003911
Chris Lattnera660f4b2008-07-09 05:14:23 +00003912 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003913 while (Buffer.size() & 15)
3914 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003915}
3916
Teresa Johnson403a7872015-10-04 14:33:43 +00003917/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003918static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003919 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003920 Stream.Emit((unsigned)'B', 8);
3921 Stream.Emit((unsigned)'C', 8);
3922 Stream.Emit(0x0, 4);
3923 Stream.Emit(0xC, 4);
3924 Stream.Emit(0xE, 4);
3925 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003926}
3927
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003928BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3929 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3930 writeBitcodeHeader(*Stream);
3931}
3932
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003933BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3934
3935void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3936 Stream->EnterSubblock(Block, 3);
3937
3938 auto Abbv = std::make_shared<BitCodeAbbrev>();
3939 Abbv->Add(BitCodeAbbrevOp(Record));
3940 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3941 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3942
3943 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3944
3945 Stream->ExitBlock();
3946}
3947
Peter Collingbourne92648c22017-06-27 23:50:11 +00003948void BitcodeWriter::writeSymtab() {
3949 assert(!WroteStrtab && !WroteSymtab);
3950
3951 // If any module has module-level inline asm, we will require a registered asm
3952 // parser for the target so that we can create an accurate symbol table for
3953 // the module.
3954 for (Module *M : Mods) {
3955 if (M->getModuleInlineAsm().empty())
3956 continue;
3957
3958 std::string Err;
3959 const Triple TT(M->getTargetTriple());
3960 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
3961 if (!T || !T->hasMCAsmParser())
3962 return;
3963 }
3964
3965 WroteSymtab = true;
3966 SmallVector<char, 0> Symtab;
3967 // The irsymtab::build function may be unable to create a symbol table if the
3968 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
3969 // table is not required for correctness, but we still want to be able to
3970 // write malformed modules to bitcode files, so swallow the error.
3971 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
3972 consumeError(std::move(E));
3973 return;
3974 }
3975
3976 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
3977 {Symtab.data(), Symtab.size()});
3978}
3979
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003980void BitcodeWriter::writeStrtab() {
3981 assert(!WroteStrtab);
3982
3983 std::vector<char> Strtab;
3984 StrtabBuilder.finalizeInOrder();
3985 Strtab.resize(StrtabBuilder.getSize());
3986 StrtabBuilder.write((uint8_t *)Strtab.data());
3987
3988 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3989 {Strtab.data(), Strtab.size()});
3990
3991 WroteStrtab = true;
3992}
3993
3994void BitcodeWriter::copyStrtab(StringRef Strtab) {
3995 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3996 WroteStrtab = true;
3997}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003998
3999void BitcodeWriter::writeModule(const Module *M,
4000 bool ShouldPreserveUseListOrder,
4001 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004002 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbourne92648c22017-06-27 23:50:11 +00004003 assert(!WroteStrtab);
4004
4005 // The Mods vector is used by irsymtab::build, which requires non-const
4006 // Modules in case it needs to materialize metadata. But the bitcode writer
4007 // requires that the module is materialized, so we can cast to non-const here,
4008 // after checking that it is in fact materialized.
4009 assert(M->isMaterialized());
4010 Mods.push_back(const_cast<Module *>(M));
4011
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004012 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004013 ShouldPreserveUseListOrder, Index,
4014 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004015 ModuleWriter.write();
4016}
4017
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004018void BitcodeWriter::writeIndex(
4019 const ModuleSummaryIndex *Index,
4020 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4021 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4022 ModuleToSummariesForIndex);
4023 IndexWriter.write();
4024}
4025
Chris Lattnerc1d10d62007-04-22 06:24:45 +00004026/// WriteBitcodeToFile - Write the specified module to the specified output
4027/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00004028void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00004029 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004030 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004031 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00004032 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00004033 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004034
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004035 // If this is darwin or another generic macho target, reserve space for the
4036 // header.
4037 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00004038 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004039 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004040
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004041 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004042 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4043 ModHash);
Peter Collingbourne92648c22017-06-27 23:50:11 +00004044 Writer.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004045 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004046
Akira Hatanaka1235d282016-01-23 16:02:10 +00004047 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00004048 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004049
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004050 // Write the generated bitstream to "Out".
4051 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004052}
Teresa Johnson403a7872015-10-04 14:33:43 +00004053
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004054void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004055 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00004056
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004057 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00004058
4059 // Write the module paths in the combined index.
4060 writeModStrings();
4061
4062 // Write the summary combined index records.
4063 writeCombinedGlobalValueSummary();
4064
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004065 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00004066}
4067
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004068// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00004069// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00004070// writing the combined index file for ThinLTO. When writing a subset of the
4071// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4072void llvm::WriteIndexToFile(
4073 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00004074 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004075 SmallVector<char, 0> Buffer;
4076 Buffer.reserve(256 * 1024);
4077
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004078 BitcodeWriter Writer(Buffer);
4079 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4080 Writer.writeStrtab();
Teresa Johnson403a7872015-10-04 14:33:43 +00004081
4082 Out.write((char *)&Buffer.front(), Buffer.size());
4083}
Haojie Wang1dec57d2017-07-21 17:25:20 +00004084
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00004085namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +00004086
Haojie Wang1dec57d2017-07-21 17:25:20 +00004087/// Class to manage the bitcode writing for a thin link bitcode file.
4088class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4089 /// ModHash is for use in ThinLTO incremental build, generated while writing
4090 /// the module bitcode file.
4091 const ModuleHash *ModHash;
4092
4093public:
4094 ThinLinkBitcodeWriter(const Module *M, StringTableBuilder &StrtabBuilder,
4095 BitstreamWriter &Stream,
4096 const ModuleSummaryIndex &Index,
4097 const ModuleHash &ModHash)
4098 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4099 /*ShouldPreserveUseListOrder=*/false, &Index),
4100 ModHash(&ModHash) {}
4101
4102 void write();
4103
4104private:
4105 void writeSimplifiedModuleInfo();
4106};
Eugene Zelenko975293f2017-09-07 23:28:24 +00004107
4108} // end anonymous namespace
Haojie Wang1dec57d2017-07-21 17:25:20 +00004109
4110// This function writes a simpilified module info for thin link bitcode file.
4111// It only contains the source file name along with the name(the offset and
4112// size in strtab) and linkage for global values. For the global value info
4113// entry, in order to keep linkage at offset 5, there are three zeros used
4114// as padding.
4115void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4116 SmallVector<unsigned, 64> Vals;
4117 // Emit the module's source file name.
4118 {
4119 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4120 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4121 if (Bits == SE_Char6)
4122 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4123 else if (Bits == SE_Fixed7)
4124 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4125
4126 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4127 auto Abbv = std::make_shared<BitCodeAbbrev>();
4128 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4130 Abbv->Add(AbbrevOpToUse);
4131 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4132
4133 for (const auto P : M.getSourceFileName())
4134 Vals.push_back((unsigned char)P);
4135
4136 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4137 Vals.clear();
4138 }
4139
4140 // Emit the global variable information.
4141 for (const GlobalVariable &GV : M.globals()) {
4142 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4143 Vals.push_back(StrtabBuilder.add(GV.getName()));
4144 Vals.push_back(GV.getName().size());
4145 Vals.push_back(0);
4146 Vals.push_back(0);
4147 Vals.push_back(0);
4148 Vals.push_back(getEncodedLinkage(GV));
4149
4150 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4151 Vals.clear();
4152 }
4153
4154 // Emit the function proto information.
4155 for (const Function &F : M) {
4156 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4157 Vals.push_back(StrtabBuilder.add(F.getName()));
4158 Vals.push_back(F.getName().size());
4159 Vals.push_back(0);
4160 Vals.push_back(0);
4161 Vals.push_back(0);
4162 Vals.push_back(getEncodedLinkage(F));
4163
4164 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4165 Vals.clear();
4166 }
4167
4168 // Emit the alias information.
4169 for (const GlobalAlias &A : M.aliases()) {
4170 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4171 Vals.push_back(StrtabBuilder.add(A.getName()));
4172 Vals.push_back(A.getName().size());
4173 Vals.push_back(0);
4174 Vals.push_back(0);
4175 Vals.push_back(0);
4176 Vals.push_back(getEncodedLinkage(A));
4177
4178 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4179 Vals.clear();
4180 }
4181
4182 // Emit the ifunc information.
4183 for (const GlobalIFunc &I : M.ifuncs()) {
4184 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4185 Vals.push_back(StrtabBuilder.add(I.getName()));
4186 Vals.push_back(I.getName().size());
4187 Vals.push_back(0);
4188 Vals.push_back(0);
4189 Vals.push_back(0);
4190 Vals.push_back(getEncodedLinkage(I));
4191
4192 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4193 Vals.clear();
4194 }
4195}
4196
4197void ThinLinkBitcodeWriter::write() {
4198 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4199
4200 writeModuleVersion();
4201
4202 writeSimplifiedModuleInfo();
4203
4204 writePerModuleGlobalValueSummary();
4205
4206 // Write module hash.
4207 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4208
4209 Stream.ExitBlock();
4210}
4211
4212void BitcodeWriter::writeThinLinkBitcode(const Module *M,
4213 const ModuleSummaryIndex &Index,
4214 const ModuleHash &ModHash) {
4215 assert(!WroteStrtab);
4216
4217 // The Mods vector is used by irsymtab::build, which requires non-const
4218 // Modules in case it needs to materialize metadata. But the bitcode writer
4219 // requires that the module is materialized, so we can cast to non-const here,
4220 // after checking that it is in fact materialized.
4221 assert(M->isMaterialized());
4222 Mods.push_back(const_cast<Module *>(M));
4223
4224 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4225 ModHash);
4226 ThinLinkWriter.write();
4227}
4228
4229// Write the specified thin link bitcode file to the given raw output stream,
4230// where it will be written in a new bitcode block. This is used when
4231// writing the per-module index file for ThinLTO.
4232void llvm::WriteThinLinkBitcodeToFile(const Module *M, raw_ostream &Out,
4233 const ModuleSummaryIndex &Index,
4234 const ModuleHash &ModHash) {
4235 SmallVector<char, 0> Buffer;
4236 Buffer.reserve(256 * 1024);
4237
4238 BitcodeWriter Writer(Buffer);
4239 Writer.writeThinLinkBitcode(M, Index, ModHash);
4240 Writer.writeSymtab();
4241 Writer.writeStrtab();
4242
4243 Out.write((char *)&Buffer.front(), Buffer.size());
4244}