blob: 94f5f56ef5a0ec060d9c4b9903e4588d970cacbe [file] [log] [blame]
Chris Lattner87351e22007-04-29 05:31:57 +00001//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
Chris Lattnerc1d10d62007-04-22 06:24:45 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
Teresa Johnsonad176792016-11-11 05:34:58 +000014#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "ValueEnumerator.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/Triple.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000018#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000019#include "llvm/Bitcode/LLVMBitCodes.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000020#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000029#include "llvm/IR/UseListOrder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000031#include "llvm/MC/StringTableBuilder.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000033#include "llvm/Support/MathExtras.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000034#include "llvm/Support/Program.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000035#include "llvm/Support/SHA1.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000037#include <cctype>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000038#include <map>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000039using namespace llvm;
40
Benjamin Kramera65b6102016-05-15 15:18:11 +000041namespace {
Mehdi Aminie98f9252016-12-28 22:30:28 +000042
43cl::opt<unsigned>
44 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
45 cl::desc("Number of metadatas above which we emit an index "
46 "to enable lazy-loading"));
Chris Lattner4d925982007-05-04 20:52:02 +000047/// These are manifest constants used by the bitcode writer. They do not need to
48/// be kept in sync with the reader, but need to be consistent within this file.
49enum {
Chris Lattner4d925982007-05-04 20:52:02 +000050 // VALUE_SYMTAB_BLOCK abbrev id's.
51 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000052 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +000053 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +000054 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000055
Chris Lattnerda5e5d22007-05-05 07:36:14 +000056 // CONSTANTS_BLOCK abbrev id's.
57 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 CONSTANTS_INTEGER_ABBREV,
59 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +000060 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000061
Chris Lattnerb80751d2007-05-05 07:44:49 +000062 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +000063 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000064 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +000065 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000066 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +000067 FUNCTION_INST_RET_VOID_ABBREV,
68 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +000069 FUNCTION_INST_UNREACHABLE_ABBREV,
70 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +000071};
72
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000073/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000074/// file type.
75class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000076protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000077 /// The stream created and owned by the client.
78 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +000079
Teresa Johnson37687f32016-04-23 04:30:47 +000080public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000081 /// Constructs a BitcodeWriterBase object that writes to the provided
82 /// \p Stream.
83 BitcodeWriterBase(BitstreamWriter &Stream) : Stream(Stream) {}
Teresa Johnson37687f32016-04-23 04:30:47 +000084
85protected:
Teresa Johnson37687f32016-04-23 04:30:47 +000086 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +000087 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +000088};
89
Peter Collingbournea0f371a2017-04-17 17:51:36 +000090void BitcodeWriterBase::writeModuleVersion() {
91 // VERSION: [version#]
92 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
93}
94
Teresa Johnson37687f32016-04-23 04:30:47 +000095/// Class to manage the bitcode writing for a module.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000096class ModuleBitcodeWriter : public BitcodeWriterBase {
97 /// Pointer to the buffer allocated by caller for bitcode writing.
98 const SmallVectorImpl<char> &Buffer;
99
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000100 StringTableBuilder &StrtabBuilder;
101
Teresa Johnson37687f32016-04-23 04:30:47 +0000102 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000103 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000104
105 /// Enumerates ids for all values in the module.
106 ValueEnumerator VE;
107
108 /// Optional per-module index to write for ThinLTO.
109 const ModuleSummaryIndex *Index;
110
111 /// True if a module hash record should be written.
112 bool GenerateHash;
113
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000114 /// If non-null, when GenerateHash is true, the resulting hash is written
115 /// into ModHash. When GenerateHash is false, that specified value
116 /// is used as the hash instead of computing from the generated bitcode.
117 /// Can be used to produce the same module hash for a minimized bitcode
118 /// used just for the thin link as in the regular full bitcode that will
119 /// be used in the backend.
120 ModuleHash *ModHash;
121
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000122 /// The start bit of the identification block.
123 uint64_t BitcodeStartBit;
Teresa Johnson37687f32016-04-23 04:30:47 +0000124
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000125 /// Map that holds the correspondence between GUIDs in the summary index,
126 /// that came from indirect call profiles, and a value id generated by this
127 /// class to use in the VST and summary block records.
128 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
129
130 /// Tracks the last value id recorded in the GUIDToValueMap.
131 unsigned GlobalValueId;
132
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000133 /// Saves the offset of the VSTOffset record that must eventually be
134 /// backpatched with the offset of the actual VST.
135 uint64_t VSTOffsetPlaceholder = 0;
136
Teresa Johnson37687f32016-04-23 04:30:47 +0000137public:
138 /// Constructs a ModuleBitcodeWriter object for the given Module,
139 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000140 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000141 StringTableBuilder &StrtabBuilder,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000142 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000143 const ModuleSummaryIndex *Index, bool GenerateHash,
144 ModuleHash *ModHash = nullptr)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000145 : BitcodeWriterBase(Stream), Buffer(Buffer), StrtabBuilder(StrtabBuilder),
146 M(*M), VE(*M, ShouldPreserveUseListOrder), Index(Index),
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000147 GenerateHash(GenerateHash), ModHash(ModHash),
148 BitcodeStartBit(Stream.GetCurrentBitNo()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000149 // Assign ValueIds to any callee values in the index that came from
150 // indirect call profiles and were recorded as a GUID not a Value*
151 // (which would have been assigned an ID by the ValueEnumerator).
152 // The starting ValueId is just after the number of values in the
153 // ValueEnumerator, so that they can be emitted in the VST.
154 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000155 if (!Index)
156 return;
157 for (const auto &GUIDSummaryLists : *Index)
158 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000159 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000160 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
161 // For each call in the function summary, see if the call
162 // is to a GUID (which means it is for an indirect call,
163 // otherwise we would have a Value for it). If so, synthesize
164 // a value id.
165 for (auto &CallEdge : FS->calls())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000166 if (!CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000167 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000168 }
169
Teresa Johnson37687f32016-04-23 04:30:47 +0000170 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000171 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000172
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000173private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000174 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
175
Teresa Johnson37687f32016-04-23 04:30:47 +0000176 void writeAttributeGroupTable();
177 void writeAttributeTable();
178 void writeTypeTable();
179 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000180 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000181 void writeModuleInfo();
182 void writeValueAsMetadata(const ValueAsMetadata *MD,
183 SmallVectorImpl<uint64_t> &Record);
184 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
185 unsigned Abbrev);
186 unsigned createDILocationAbbrev();
187 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
188 unsigned &Abbrev);
189 unsigned createGenericDINodeAbbrev();
190 void writeGenericDINode(const GenericDINode *N,
191 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
192 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
193 unsigned Abbrev);
194 void writeDIEnumerator(const DIEnumerator *N,
195 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
196 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
197 unsigned Abbrev);
198 void writeDIDerivedType(const DIDerivedType *N,
199 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
200 void writeDICompositeType(const DICompositeType *N,
201 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
202 void writeDISubroutineType(const DISubroutineType *N,
203 SmallVectorImpl<uint64_t> &Record,
204 unsigned Abbrev);
205 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
206 unsigned Abbrev);
207 void writeDICompileUnit(const DICompileUnit *N,
208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
209 void writeDISubprogram(const DISubprogram *N,
210 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
211 void writeDILexicalBlock(const DILexicalBlock *N,
212 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
213 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
214 SmallVectorImpl<uint64_t> &Record,
215 unsigned Abbrev);
216 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
217 unsigned Abbrev);
218 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
219 unsigned Abbrev);
220 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
221 unsigned Abbrev);
222 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
223 unsigned Abbrev);
224 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
225 SmallVectorImpl<uint64_t> &Record,
226 unsigned Abbrev);
227 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
228 SmallVectorImpl<uint64_t> &Record,
229 unsigned Abbrev);
230 void writeDIGlobalVariable(const DIGlobalVariable *N,
231 SmallVectorImpl<uint64_t> &Record,
232 unsigned Abbrev);
233 void writeDILocalVariable(const DILocalVariable *N,
234 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
235 void writeDIExpression(const DIExpression *N,
236 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000237 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
238 SmallVectorImpl<uint64_t> &Record,
239 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000240 void writeDIObjCProperty(const DIObjCProperty *N,
241 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
242 void writeDIImportedEntity(const DIImportedEntity *N,
243 SmallVectorImpl<uint64_t> &Record,
244 unsigned Abbrev);
245 unsigned createNamedMetadataAbbrev();
246 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
247 unsigned createMetadataStringsAbbrev();
248 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
249 SmallVectorImpl<uint64_t> &Record);
250 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000251 SmallVectorImpl<uint64_t> &Record,
252 std::vector<unsigned> *MDAbbrevs = nullptr,
253 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000254 void writeModuleMetadata();
255 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000256 void writeFunctionMetadataAttachment(const Function &F);
257 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
258 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
259 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000260 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000261 void writeOperandBundleTags();
262 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
263 void writeModuleConstants();
264 bool pushValueAndType(const Value *V, unsigned InstID,
265 SmallVectorImpl<unsigned> &Vals);
266 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
267 void pushValue(const Value *V, unsigned InstID,
268 SmallVectorImpl<unsigned> &Vals);
269 void pushValueSigned(const Value *V, unsigned InstID,
270 SmallVectorImpl<uint64_t> &Vals);
271 void writeInstruction(const Instruction &I, unsigned InstID,
272 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000273 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
274 void writeGlobalValueSymbolTable(
275 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000276 void writeUseList(UseListOrder &&Order);
277 void writeUseListBlock(const Function *F);
278 void
279 writeFunction(const Function &F,
280 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
281 void writeBlockInfo();
282 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000283 GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +0000284 unsigned ValueID,
285 unsigned FSCallsAbbrev,
286 unsigned FSCallsProfileAbbrev,
287 const Function &F);
288 void writeModuleLevelReferences(const GlobalVariable &V,
289 SmallVector<uint64_t, 64> &NameVals,
290 unsigned FSModRefsAbbrev);
291 void writePerModuleGlobalValueSummary();
292 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000293
294 void assignValueId(GlobalValue::GUID ValGUID) {
295 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
296 }
297 unsigned getValueId(GlobalValue::GUID ValGUID) {
298 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000299 // Expect that any GUID value had a value Id assigned by an
300 // earlier call to assignValueId.
301 assert(VMI != GUIDToValueIdMap.end() &&
302 "GUID does not have assigned value Id");
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000303 return VMI->second;
304 }
305 // Helper to get the valueId for the type of value recorded in VI.
306 unsigned getValueId(ValueInfo VI) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000307 if (!VI.getValue())
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000308 return getValueId(VI.getGUID());
309 return VE.getValueID(VI.getValue());
310 }
311 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
Teresa Johnson37687f32016-04-23 04:30:47 +0000312};
313
314/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000315class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000316 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000317 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000318
Teresa Johnson84174c32016-05-10 13:48:23 +0000319 /// When writing a subset of the index for distributed backends, client
320 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000321 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000322
Teresa Johnson37687f32016-04-23 04:30:47 +0000323 /// Map that holds the correspondence between the GUID used in the combined
324 /// index and a value id generated by this class to use in references.
325 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
326
327 /// Tracks the last value id recorded in the GUIDToValueMap.
328 unsigned GlobalValueId = 0;
329
330public:
331 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000332 /// writing to the provided \p Buffer. When writing a subset of the index
333 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000334 IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000335 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000336 *ModuleToSummariesForIndex = nullptr)
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000337 : BitcodeWriterBase(Stream), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000338 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
339 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000340 // in writing out the call graph edges. Save the mapping from GUID
341 // to the new global value id to use when writing those edges, which
342 // are currently saved in the index in terms of GUID.
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000343 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000344 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000345 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000346 }
347
Teresa Johnson84174c32016-05-10 13:48:23 +0000348 /// The below iterator returns the GUID and associated summary.
349 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
350
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000351 /// Calls the callback for each value GUID and summary to be written to
352 /// bitcode. This hides the details of whether they are being pulled from the
353 /// entire index or just those in a provided ModuleToSummariesForIndex map.
354 void forEachSummary(std::function<void(GVInfo)> Callback) {
355 if (ModuleToSummariesForIndex) {
356 for (auto &M : *ModuleToSummariesForIndex)
357 for (auto &Summary : M.second)
358 Callback(Summary);
359 } else {
360 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000361 for (auto &Summary : Summaries.second.SummaryList)
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000362 Callback({Summaries.first, Summary.get()});
Teresa Johnson84174c32016-05-10 13:48:23 +0000363 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000364 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000365
Teresa Johnson7a27b132017-06-02 01:56:02 +0000366 /// Calls the callback for each entry in the modulePaths StringMap that
367 /// should be written to the module path string table. This hides the details
368 /// of whether they are being pulled from the entire index or just those in a
369 /// provided ModuleToSummariesForIndex map.
370 void
371 forEachModule(std::function<
372 void(const StringMapEntry<std::pair<uint64_t, ModuleHash>> &)>
373 Callback) {
374 if (ModuleToSummariesForIndex) {
375 for (const auto &M : *ModuleToSummariesForIndex) {
376 const auto &MPI = Index.modulePaths().find(M.first);
377 if (MPI == Index.modulePaths().end()) {
378 // This should only happen if the bitcode file was empty, in which
379 // case we shouldn't be importing (the ModuleToSummariesForIndex
380 // would only include the module we are writing and index for).
381 assert(ModuleToSummariesForIndex->size() == 1);
382 continue;
383 }
384 Callback(*MPI);
385 }
386 } else {
387 for (const auto &MPSE : Index.modulePaths())
388 Callback(MPSE);
389 }
390 }
391
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000392 /// Main entry point for writing a combined index to bitcode.
393 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000394
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000395private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000396 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000397 void writeCombinedGlobalValueSummary();
398
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000399 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000400 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000401 if (VMI == GUIDToValueIdMap.end())
402 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000403 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000404 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000405 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
406};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000407} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000408
409static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000410 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000411 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000412 case Instruction::Trunc : return bitc::CAST_TRUNC;
413 case Instruction::ZExt : return bitc::CAST_ZEXT;
414 case Instruction::SExt : return bitc::CAST_SEXT;
415 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
416 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
417 case Instruction::UIToFP : return bitc::CAST_UITOFP;
418 case Instruction::SIToFP : return bitc::CAST_SITOFP;
419 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
420 case Instruction::FPExt : return bitc::CAST_FPEXT;
421 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
422 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
423 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000424 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000425 }
426}
427
Teresa Johnson37687f32016-04-23 04:30:47 +0000428static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000429 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000430 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000431 case Instruction::Add:
432 case Instruction::FAdd: return bitc::BINOP_ADD;
433 case Instruction::Sub:
434 case Instruction::FSub: return bitc::BINOP_SUB;
435 case Instruction::Mul:
436 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000437 case Instruction::UDiv: return bitc::BINOP_UDIV;
438 case Instruction::FDiv:
439 case Instruction::SDiv: return bitc::BINOP_SDIV;
440 case Instruction::URem: return bitc::BINOP_UREM;
441 case Instruction::FRem:
442 case Instruction::SRem: return bitc::BINOP_SREM;
443 case Instruction::Shl: return bitc::BINOP_SHL;
444 case Instruction::LShr: return bitc::BINOP_LSHR;
445 case Instruction::AShr: return bitc::BINOP_ASHR;
446 case Instruction::And: return bitc::BINOP_AND;
447 case Instruction::Or: return bitc::BINOP_OR;
448 case Instruction::Xor: return bitc::BINOP_XOR;
449 }
450}
451
Teresa Johnson37687f32016-04-23 04:30:47 +0000452static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000453 switch (Op) {
454 default: llvm_unreachable("Unknown RMW operation!");
455 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
456 case AtomicRMWInst::Add: return bitc::RMW_ADD;
457 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
458 case AtomicRMWInst::And: return bitc::RMW_AND;
459 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
460 case AtomicRMWInst::Or: return bitc::RMW_OR;
461 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
462 case AtomicRMWInst::Max: return bitc::RMW_MAX;
463 case AtomicRMWInst::Min: return bitc::RMW_MIN;
464 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
465 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
466 }
467}
468
Teresa Johnson37687f32016-04-23 04:30:47 +0000469static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000470 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000471 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
472 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
473 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
474 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
475 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
476 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
477 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000478 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000479 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000480}
481
Teresa Johnson37687f32016-04-23 04:30:47 +0000482static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000483 switch (SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000484 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
485 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
486 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000487 llvm_unreachable("Invalid synch scope");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000488}
489
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000490static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
491 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000492 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000493
Chris Lattnere14cb882007-05-04 19:11:41 +0000494 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000495 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
496 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
497 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000498 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000499 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000500
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000501 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000502 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000503}
504
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000505static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
506 switch (Kind) {
507 case Attribute::Alignment:
508 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000509 case Attribute::AllocSize:
510 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000511 case Attribute::AlwaysInline:
512 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000513 case Attribute::ArgMemOnly:
514 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000515 case Attribute::Builtin:
516 return bitc::ATTR_KIND_BUILTIN;
517 case Attribute::ByVal:
518 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000519 case Attribute::Convergent:
520 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000521 case Attribute::InAlloca:
522 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000523 case Attribute::Cold:
524 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000525 case Attribute::InaccessibleMemOnly:
526 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
527 case Attribute::InaccessibleMemOrArgMemOnly:
528 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000529 case Attribute::InlineHint:
530 return bitc::ATTR_KIND_INLINE_HINT;
531 case Attribute::InReg:
532 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000533 case Attribute::JumpTable:
534 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000535 case Attribute::MinSize:
536 return bitc::ATTR_KIND_MIN_SIZE;
537 case Attribute::Naked:
538 return bitc::ATTR_KIND_NAKED;
539 case Attribute::Nest:
540 return bitc::ATTR_KIND_NEST;
541 case Attribute::NoAlias:
542 return bitc::ATTR_KIND_NO_ALIAS;
543 case Attribute::NoBuiltin:
544 return bitc::ATTR_KIND_NO_BUILTIN;
545 case Attribute::NoCapture:
546 return bitc::ATTR_KIND_NO_CAPTURE;
547 case Attribute::NoDuplicate:
548 return bitc::ATTR_KIND_NO_DUPLICATE;
549 case Attribute::NoImplicitFloat:
550 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
551 case Attribute::NoInline:
552 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000553 case Attribute::NoRecurse:
554 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000555 case Attribute::NonLazyBind:
556 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000557 case Attribute::NonNull:
558 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000559 case Attribute::Dereferenceable:
560 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000561 case Attribute::DereferenceableOrNull:
562 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000563 case Attribute::NoRedZone:
564 return bitc::ATTR_KIND_NO_RED_ZONE;
565 case Attribute::NoReturn:
566 return bitc::ATTR_KIND_NO_RETURN;
567 case Attribute::NoUnwind:
568 return bitc::ATTR_KIND_NO_UNWIND;
569 case Attribute::OptimizeForSize:
570 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000571 case Attribute::OptimizeNone:
572 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000573 case Attribute::ReadNone:
574 return bitc::ATTR_KIND_READ_NONE;
575 case Attribute::ReadOnly:
576 return bitc::ATTR_KIND_READ_ONLY;
577 case Attribute::Returned:
578 return bitc::ATTR_KIND_RETURNED;
579 case Attribute::ReturnsTwice:
580 return bitc::ATTR_KIND_RETURNS_TWICE;
581 case Attribute::SExt:
582 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000583 case Attribute::Speculatable:
584 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000585 case Attribute::StackAlignment:
586 return bitc::ATTR_KIND_STACK_ALIGNMENT;
587 case Attribute::StackProtect:
588 return bitc::ATTR_KIND_STACK_PROTECT;
589 case Attribute::StackProtectReq:
590 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
591 case Attribute::StackProtectStrong:
592 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000593 case Attribute::SafeStack:
594 return bitc::ATTR_KIND_SAFESTACK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000595 case Attribute::StructRet:
596 return bitc::ATTR_KIND_STRUCT_RET;
597 case Attribute::SanitizeAddress:
598 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
599 case Attribute::SanitizeThread:
600 return bitc::ATTR_KIND_SANITIZE_THREAD;
601 case Attribute::SanitizeMemory:
602 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000603 case Attribute::SwiftError:
604 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000605 case Attribute::SwiftSelf:
606 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000607 case Attribute::UWTable:
608 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000609 case Attribute::WriteOnly:
610 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000611 case Attribute::ZExt:
612 return bitc::ATTR_KIND_Z_EXT;
613 case Attribute::EndAttrKinds:
614 llvm_unreachable("Can not encode end-attribute kinds marker.");
615 case Attribute::None:
616 llvm_unreachable("Can not encode none-attribute.");
617 }
618
619 llvm_unreachable("Trying to encode unknown attribute");
620}
621
Teresa Johnson37687f32016-04-23 04:30:47 +0000622void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000623 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
624 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000625 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000626
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000627 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000628
629 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000630 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
631 unsigned AttrListIndex = Pair.first;
632 AttributeSet AS = Pair.second;
633 Record.push_back(VE.getAttributeGroupID(Pair));
634 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000635
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000636 for (Attribute Attr : AS) {
637 if (Attr.isEnumAttribute()) {
638 Record.push_back(0);
639 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
640 } else if (Attr.isIntAttribute()) {
641 Record.push_back(1);
642 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
643 Record.push_back(Attr.getValueAsInt());
644 } else {
645 StringRef Kind = Attr.getKindAsString();
646 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000647
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000648 Record.push_back(Val.empty() ? 3 : 4);
649 Record.append(Kind.begin(), Kind.end());
650 Record.push_back(0);
651 if (!Val.empty()) {
652 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000653 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000654 }
655 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000656 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000657
658 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
659 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000660 }
661
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000662 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000663}
664
Teresa Johnson37687f32016-04-23 04:30:47 +0000665void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000666 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000667 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000668
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000669 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000670
671 SmallVector<uint64_t, 64> Record;
672 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000673 AttributeList AL = Attrs[i];
674 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
675 AttributeSet AS = AL.getAttributes(i);
676 if (AS.hasAttributes())
677 Record.push_back(VE.getAttributeGroupID({i, AS}));
678 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000679
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000680 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000681 Record.clear();
682 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000683
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000684 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000685}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000686
687/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000688void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000689 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000690
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000691 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000692 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000693
David Blaikie7b028102015-02-25 00:51:52 +0000694 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000695
Chris Lattnerccee7062007-05-05 06:30:12 +0000696 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000697 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000698 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000699 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000700 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000701 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000702
Chris Lattnerccee7062007-05-05 06:30:12 +0000703 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000704 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000705 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
709
David Blaikie7ad9dc12017-01-04 22:36:33 +0000710 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000711
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000712 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000713 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000714 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
718
David Blaikie7ad9dc12017-01-04 22:36:33 +0000719 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000720
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000721 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000722 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000723 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
724 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
725 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000726 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000727
728 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000729 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000730 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
734
David Blaikie7ad9dc12017-01-04 22:36:33 +0000735 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000736
Chris Lattnerccee7062007-05-05 06:30:12 +0000737 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000738 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000739 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
740 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
742
David Blaikie7ad9dc12017-01-04 22:36:33 +0000743 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000744
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000745 // Emit an entry count so the reader can reserve space.
746 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000747 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000748 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000749
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000750 // Loop over all of the types, emitting each in turn.
751 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000752 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000753 int AbbrevToUse = 0;
754 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000756 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000757 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
758 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
759 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
760 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
761 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
762 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000763 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000764 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
765 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
766 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000767 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000768 case Type::IntegerTyID:
769 // INTEGER: [width]
770 Code = bitc::TYPE_CODE_INTEGER;
771 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
772 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000773 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000774 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000775 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000776 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000777 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000778 unsigned AddressSpace = PTy->getAddressSpace();
779 TypeVals.push_back(AddressSpace);
780 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000781 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000782 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000783 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000784 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000785 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000786 Code = bitc::TYPE_CODE_FUNCTION;
787 TypeVals.push_back(FT->isVarArg());
788 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000789 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
790 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000791 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000792 break;
793 }
794 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000795 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000796 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000797 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000798 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000799 for (StructType::element_iterator I = ST->element_begin(),
800 E = ST->element_end(); I != E; ++I)
801 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000802
Chris Lattner335d3992011-08-12 18:06:37 +0000803 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000804 Code = bitc::TYPE_CODE_STRUCT_ANON;
805 AbbrevToUse = StructAnonAbbrev;
806 } else {
807 if (ST->isOpaque()) {
808 Code = bitc::TYPE_CODE_OPAQUE;
809 } else {
810 Code = bitc::TYPE_CODE_STRUCT_NAMED;
811 AbbrevToUse = StructNamedAbbrev;
812 }
813
814 // Emit the name if it is present.
815 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000816 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000817 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000818 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000819 break;
820 }
821 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000822 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000823 // ARRAY: [numelts, eltty]
824 Code = bitc::TYPE_CODE_ARRAY;
825 TypeVals.push_back(AT->getNumElements());
826 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000827 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000828 break;
829 }
830 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000831 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000832 // VECTOR [numelts, eltty]
833 Code = bitc::TYPE_CODE_VECTOR;
834 TypeVals.push_back(VT->getNumElements());
835 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
836 break;
837 }
838 }
839
840 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000841 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000842 TypeVals.clear();
843 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000844
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000845 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000846}
847
Teresa Johnson5e22e442016-02-06 16:07:35 +0000848static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
849 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000850 case GlobalValue::ExternalLinkage:
851 return 0;
852 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000853 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000854 case GlobalValue::AppendingLinkage:
855 return 2;
856 case GlobalValue::InternalLinkage:
857 return 3;
858 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000859 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000860 case GlobalValue::ExternalWeakLinkage:
861 return 7;
862 case GlobalValue::CommonLinkage:
863 return 8;
864 case GlobalValue::PrivateLinkage:
865 return 9;
866 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000867 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000868 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000869 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000870 case GlobalValue::AvailableExternallyLinkage:
871 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000872 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000873 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000874}
875
Teresa Johnson5e22e442016-02-06 16:07:35 +0000876static unsigned getEncodedLinkage(const GlobalValue &GV) {
877 return getEncodedLinkage(GV.getLinkage());
878}
879
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000880// Decode the flags for GlobalValue in the summary
881static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
882 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000883
Mehdi Amini1380edf2017-02-03 07:41:43 +0000884 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000885 RawFlags |= (Flags.Live << 1);
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000886 // Linkage don't need to be remapped at that time for the summary. Any future
887 // change to the getEncodedLinkage() function will need to be taken into
888 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000889 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
890
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000891 return RawFlags;
892}
893
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000894static unsigned getEncodedVisibility(const GlobalValue &GV) {
895 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000896 case GlobalValue::DefaultVisibility: return 0;
897 case GlobalValue::HiddenVisibility: return 1;
898 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000899 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000900 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000901}
902
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000903static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
904 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000905 case GlobalValue::DefaultStorageClass: return 0;
906 case GlobalValue::DLLImportStorageClass: return 1;
907 case GlobalValue::DLLExportStorageClass: return 2;
908 }
909 llvm_unreachable("Invalid DLL storage class");
910}
911
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000912static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000913 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000914 case GlobalVariable::NotThreadLocal: return 0;
915 case GlobalVariable::GeneralDynamicTLSModel: return 1;
916 case GlobalVariable::LocalDynamicTLSModel: return 2;
917 case GlobalVariable::InitialExecTLSModel: return 3;
918 case GlobalVariable::LocalExecTLSModel: return 4;
919 }
920 llvm_unreachable("Invalid TLS model");
921}
922
David Majnemerdad0a642014-06-27 18:19:56 +0000923static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
924 switch (C.getSelectionKind()) {
925 case Comdat::Any:
926 return bitc::COMDAT_SELECTION_KIND_ANY;
927 case Comdat::ExactMatch:
928 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
929 case Comdat::Largest:
930 return bitc::COMDAT_SELECTION_KIND_LARGEST;
931 case Comdat::NoDuplicates:
932 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
933 case Comdat::SameSize:
934 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
935 }
936 llvm_unreachable("Invalid selection kind");
937}
938
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000939static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
940 switch (GV.getUnnamedAddr()) {
941 case GlobalValue::UnnamedAddr::None: return 0;
942 case GlobalValue::UnnamedAddr::Local: return 2;
943 case GlobalValue::UnnamedAddr::Global: return 1;
944 }
945 llvm_unreachable("Invalid unnamed_addr");
946}
947
Teresa Johnson37687f32016-04-23 04:30:47 +0000948void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +0000949 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +0000950 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000951 // COMDAT: [strtab offset, strtab size, selection_kind]
952 Vals.push_back(StrtabBuilder.add(C->getName()));
953 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +0000954 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000955 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +0000956 Vals.clear();
957 }
958}
959
Teresa Johnsonff642b92015-09-17 20:12:00 +0000960/// Write a record that will eventually hold the word offset of the
961/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +0000962/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000963void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +0000964 // Write a placeholder value in for the offset of the real VST,
965 // which is written after the function blocks so that it can include
966 // the offset of each function. The placeholder offset will be
967 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000968 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +0000969 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
970 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
971 // hold the real VST offset. Must use fixed instead of VBR as we don't
972 // know how many VBR chunks to reserve ahead of time.
973 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000974 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +0000975
976 // Emit the placeholder
977 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000978 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +0000979
Teresa Johnson37687f32016-04-23 04:30:47 +0000980 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +0000981 // patched when the real VST is written. We can simply subtract the 32-bit
982 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000983 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +0000984}
985
Teresa Johnsone1164de2016-02-10 21:55:02 +0000986enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
987
988/// Determine the encoding to use for the given string name and length.
989static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
990 bool isChar6 = true;
991 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
992 if (isChar6)
993 isChar6 = BitCodeAbbrevOp::isChar6(*C);
994 if ((unsigned char)*C & 128)
995 // don't bother scanning the rest.
996 return SE_Fixed8;
997 }
998 if (isChar6)
999 return SE_Char6;
1000 else
1001 return SE_Fixed7;
1002}
1003
Teresa Johnsonff642b92015-09-17 20:12:00 +00001004/// Emit top-level description of module, including target triple, inline asm,
1005/// descriptors for global variables, and function prototype info.
1006/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001007void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001008 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001009 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001010 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001011 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001012 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001013 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001014 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001015 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001016 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001017 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001018
Gordon Henriksend930f912008-08-17 18:44:35 +00001019 // Emit information about sections and GC, computing how many there are. Also
1020 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001021 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001022 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001023 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001024 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001025 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001026 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001027 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001028 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001029 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001030 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001031 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001032 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001033 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001034 Entry = SectionMap.size();
1035 }
1036 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001037 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001038 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001039 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1040 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001041 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001042 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001043 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001044 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001045 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001046 Entry = SectionMap.size();
1047 }
1048 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001049 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001050 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001051 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001052 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001053 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1054 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001055 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001056 }
1057 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001058 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001059
Chris Lattner4b00d922007-04-23 16:04:05 +00001060 // Emit abbrev for globals, now that we know # sections and max alignment.
1061 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001062 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001063 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001064 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001065 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001069 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1071 //| explicitType << 1
1072 //| constant
1073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1074 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1075 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001076 Abbv->Add(BitCodeAbbrevOp(0));
1077 else {
1078 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001080 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001081 }
1082 if (SectionMap.empty()) // Section.
1083 Abbv->Add(BitCodeAbbrevOp(0));
1084 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001085 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001086 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001087 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001088 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001090
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001091 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001092 // Emit the module's source file name.
1093 {
1094 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1095 M.getSourceFileName().size());
1096 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1097 if (Bits == SE_Char6)
1098 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1099 else if (Bits == SE_Fixed7)
1100 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1101
1102 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1103 auto Abbv = std::make_shared<BitCodeAbbrev>();
1104 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1105 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1106 Abbv->Add(AbbrevOpToUse);
1107 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1108
1109 for (const auto P : M.getSourceFileName())
1110 Vals.push_back((unsigned char)P);
1111
1112 // Emit the finished record.
1113 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1114 Vals.clear();
1115 }
1116
1117 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001118 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001119 unsigned AbbrevToUse = 0;
1120
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001121 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001122 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001123 // unnamed_addr, externally_initialized, dllstorageclass,
Javed Absarf3d79042017-05-11 12:28:08 +00001124 // comdat, attributes]
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001125 Vals.push_back(StrtabBuilder.add(GV.getName()));
1126 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001127 Vals.push_back(VE.getTypeID(GV.getValueType()));
1128 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001129 Vals.push_back(GV.isDeclaration() ? 0 :
1130 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001131 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001132 Vals.push_back(Log2_32(GV.getAlignment())+1);
1133 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1134 if (GV.isThreadLocal() ||
1135 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001136 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1137 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001138 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001139 GV.hasComdat() ||
1140 GV.hasAttributes()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001141 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001142 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001143 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001144 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001145 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001146 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001147
1148 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1149 Vals.push_back(VE.getAttributeListID(AL));
Chris Lattner4b00d922007-04-23 16:04:05 +00001150 } else {
1151 AbbrevToUse = SimpleGVarAbbrev;
1152 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001153
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001154 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001155 Vals.clear();
1156 }
1157
1158 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001159 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001160 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1161 // linkage, paramattrs, alignment, section, visibility, gc,
1162 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1163 // prefixdata, personalityfn]
1164 Vals.push_back(StrtabBuilder.add(F.getName()));
1165 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001166 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001167 Vals.push_back(F.getCallingConv());
1168 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001169 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001170 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001171 Vals.push_back(Log2_32(F.getAlignment())+1);
1172 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001173 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001174 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001175 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001176 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1177 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001178 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001179 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001180 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1181 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001182 Vals.push_back(
1183 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001184
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001185 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001186 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001187 Vals.clear();
1188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001189
Chris Lattner44c17072007-04-26 02:46:40 +00001190 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001191 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001192 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1193 // visibility, dllstorageclass, threadlocal, unnamed_addr]
1194 Vals.push_back(StrtabBuilder.add(A.getName()));
1195 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001196 Vals.push_back(VE.getTypeID(A.getValueType()));
1197 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001198 Vals.push_back(VE.getValueID(A.getAliasee()));
1199 Vals.push_back(getEncodedLinkage(A));
1200 Vals.push_back(getEncodedVisibility(A));
1201 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001202 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001203 Vals.push_back(getEncodedUnnamedAddr(A));
Chris Lattner44c17072007-04-26 02:46:40 +00001204 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001205 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001206 Vals.clear();
1207 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001208
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001209 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001210 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001211 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1212 // val#, linkage, visibility]
1213 Vals.push_back(StrtabBuilder.add(I.getName()));
1214 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001215 Vals.push_back(VE.getTypeID(I.getValueType()));
1216 Vals.push_back(I.getType()->getAddressSpace());
1217 Vals.push_back(VE.getValueID(I.getResolver()));
1218 Vals.push_back(getEncodedLinkage(I));
1219 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001220 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001221 Vals.clear();
1222 }
1223
Teresa Johnson37687f32016-04-23 04:30:47 +00001224 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001225}
1226
Teresa Johnson37687f32016-04-23 04:30:47 +00001227static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001228 uint64_t Flags = 0;
1229
Sanjay Patelc00017d2014-10-15 17:45:13 +00001230 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001231 if (OBO->hasNoSignedWrap())
1232 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1233 if (OBO->hasNoUnsignedWrap())
1234 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001235 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001236 if (PEO->isExact())
1237 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001238 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001239 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001240 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001241 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001242 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001243 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001244 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001245 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001246 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001247 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001248 Flags |= FastMathFlags::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001249 if (FPMO->hasAllowContract())
1250 Flags |= FastMathFlags::AllowContract;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001251 }
1252
1253 return Flags;
1254}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001255
Teresa Johnson37687f32016-04-23 04:30:47 +00001256void ModuleBitcodeWriter::writeValueAsMetadata(
1257 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001258 // Mimic an MDNode with a value as one operand.
1259 Value *V = MD->getValue();
1260 Record.push_back(VE.getTypeID(V->getType()));
1261 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001262 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001263 Record.clear();
1264}
1265
Teresa Johnson37687f32016-04-23 04:30:47 +00001266void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1267 SmallVectorImpl<uint64_t> &Record,
1268 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001269 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001270 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001271 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1272 "Unexpected function-local metadata");
1273 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001274 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001275 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1276 : bitc::METADATA_NODE,
1277 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001278 Record.clear();
1279}
Devang Patele059ba6e2009-07-23 01:07:34 +00001280
Teresa Johnson37687f32016-04-23 04:30:47 +00001281unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001282 // Assume the column is usually under 128, and always output the inlined-at
1283 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001284 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001285 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001291 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001292}
1293
Teresa Johnson37687f32016-04-23 04:30:47 +00001294void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1295 SmallVectorImpl<uint64_t> &Record,
1296 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001297 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001298 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001299
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001300 Record.push_back(N->isDistinct());
1301 Record.push_back(N->getLine());
1302 Record.push_back(N->getColumn());
1303 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001304 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001305
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001306 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001307 Record.clear();
1308}
1309
Teresa Johnson37687f32016-04-23 04:30:47 +00001310unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001311 // Assume the column is usually under 128, and always output the inlined-at
1312 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001313 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001314 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1319 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001321 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001322}
1323
Teresa Johnson37687f32016-04-23 04:30:47 +00001324void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1325 SmallVectorImpl<uint64_t> &Record,
1326 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001327 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001328 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001329
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001330 Record.push_back(N->isDistinct());
1331 Record.push_back(N->getTag());
1332 Record.push_back(0); // Per-tag version field; unused for now.
1333
1334 for (auto &I : N->operands())
1335 Record.push_back(VE.getMetadataOrNullID(I));
1336
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001337 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001338 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001339}
1340
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001341static uint64_t rotateSign(int64_t I) {
1342 uint64_t U = I;
1343 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001344}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001345
Teresa Johnson37687f32016-04-23 04:30:47 +00001346void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1347 SmallVectorImpl<uint64_t> &Record,
1348 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001349 Record.push_back(N->isDistinct());
1350 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001351 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001352
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001353 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001354 Record.clear();
1355}
1356
Teresa Johnson37687f32016-04-23 04:30:47 +00001357void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1358 SmallVectorImpl<uint64_t> &Record,
1359 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001360 Record.push_back(N->isDistinct());
1361 Record.push_back(rotateSign(N->getValue()));
1362 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1363
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001364 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001365 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001366}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001367
Teresa Johnson37687f32016-04-23 04:30:47 +00001368void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1369 SmallVectorImpl<uint64_t> &Record,
1370 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001371 Record.push_back(N->isDistinct());
1372 Record.push_back(N->getTag());
1373 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1374 Record.push_back(N->getSizeInBits());
1375 Record.push_back(N->getAlignInBits());
1376 Record.push_back(N->getEncoding());
1377
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001378 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001379 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001380}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001381
Teresa Johnson37687f32016-04-23 04:30:47 +00001382void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1383 SmallVectorImpl<uint64_t> &Record,
1384 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001385 Record.push_back(N->isDistinct());
1386 Record.push_back(N->getTag());
1387 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1388 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1389 Record.push_back(N->getLine());
1390 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001391 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001392 Record.push_back(N->getSizeInBits());
1393 Record.push_back(N->getAlignInBits());
1394 Record.push_back(N->getOffsetInBits());
1395 Record.push_back(N->getFlags());
1396 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1397
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001398 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1399 // that there is no DWARF address space associated with DIDerivedType.
1400 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1401 Record.push_back(*DWARFAddressSpace + 1);
1402 else
1403 Record.push_back(0);
1404
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001405 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001406 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001407}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001408
Teresa Johnson37687f32016-04-23 04:30:47 +00001409void ModuleBitcodeWriter::writeDICompositeType(
1410 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1411 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001412 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001413 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001414 Record.push_back(N->getTag());
1415 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1416 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1417 Record.push_back(N->getLine());
1418 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1419 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1420 Record.push_back(N->getSizeInBits());
1421 Record.push_back(N->getAlignInBits());
1422 Record.push_back(N->getOffsetInBits());
1423 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001424 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001425 Record.push_back(N->getRuntimeLang());
1426 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001427 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001428 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1429
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001430 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001431 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001432}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001433
Teresa Johnson37687f32016-04-23 04:30:47 +00001434void ModuleBitcodeWriter::writeDISubroutineType(
1435 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1436 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001437 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001438 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001439 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001440 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001441 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001442
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001443 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001444 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001445}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001446
Teresa Johnson37687f32016-04-23 04:30:47 +00001447void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1448 SmallVectorImpl<uint64_t> &Record,
1449 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001450 Record.push_back(N->isDistinct());
1451 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1452 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001453 Record.push_back(N->getChecksumKind());
1454 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001455
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001456 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001457 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001458}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001459
Teresa Johnson37687f32016-04-23 04:30:47 +00001460void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1461 SmallVectorImpl<uint64_t> &Record,
1462 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001463 assert(N->isDistinct() && "Expected distinct compile units");
1464 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001465 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001466 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001467 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1468 Record.push_back(N->isOptimized());
1469 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1470 Record.push_back(N->getRuntimeVersion());
1471 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1472 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001473 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1474 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001475 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001476 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1477 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001478 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001479 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001480 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001481 Record.push_back(N->getDebugInfoForProfiling());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001482
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001483 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001484 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001485}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001486
Teresa Johnson37687f32016-04-23 04:30:47 +00001487void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1488 SmallVectorImpl<uint64_t> &Record,
1489 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001490 uint64_t HasUnitFlag = 1 << 1;
1491 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001492 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1493 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1494 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1495 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1496 Record.push_back(N->getLine());
1497 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1498 Record.push_back(N->isLocalToUnit());
1499 Record.push_back(N->isDefinition());
1500 Record.push_back(N->getScopeLine());
1501 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1502 Record.push_back(N->getVirtuality());
1503 Record.push_back(N->getVirtualIndex());
1504 Record.push_back(N->getFlags());
1505 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001506 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001507 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001508 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001509 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001510 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001511 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001512
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001513 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001514 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001515}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001516
Teresa Johnson37687f32016-04-23 04:30:47 +00001517void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1518 SmallVectorImpl<uint64_t> &Record,
1519 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001520 Record.push_back(N->isDistinct());
1521 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1522 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1523 Record.push_back(N->getLine());
1524 Record.push_back(N->getColumn());
1525
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001526 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001527 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001528}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001529
Teresa Johnson37687f32016-04-23 04:30:47 +00001530void ModuleBitcodeWriter::writeDILexicalBlockFile(
1531 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1532 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001533 Record.push_back(N->isDistinct());
1534 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1535 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1536 Record.push_back(N->getDiscriminator());
1537
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001538 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001539 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001540}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001541
Teresa Johnson37687f32016-04-23 04:30:47 +00001542void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1543 SmallVectorImpl<uint64_t> &Record,
1544 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001545 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001546 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001547 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001548
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001549 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001550 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001551}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001552
Teresa Johnson37687f32016-04-23 04:30:47 +00001553void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1554 SmallVectorImpl<uint64_t> &Record,
1555 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001556 Record.push_back(N->isDistinct());
1557 Record.push_back(N->getMacinfoType());
1558 Record.push_back(N->getLine());
1559 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1560 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1561
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001562 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001563 Record.clear();
1564}
1565
Teresa Johnson37687f32016-04-23 04:30:47 +00001566void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1567 SmallVectorImpl<uint64_t> &Record,
1568 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001569 Record.push_back(N->isDistinct());
1570 Record.push_back(N->getMacinfoType());
1571 Record.push_back(N->getLine());
1572 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1573 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1574
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001575 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001576 Record.clear();
1577}
1578
Teresa Johnson37687f32016-04-23 04:30:47 +00001579void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1580 SmallVectorImpl<uint64_t> &Record,
1581 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001582 Record.push_back(N->isDistinct());
1583 for (auto &I : N->operands())
1584 Record.push_back(VE.getMetadataOrNullID(I));
1585
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001586 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001587 Record.clear();
1588}
1589
Teresa Johnson37687f32016-04-23 04:30:47 +00001590void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1591 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1592 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001593 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001594 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1595 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1596
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001597 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001598 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001599}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001600
Teresa Johnson37687f32016-04-23 04:30:47 +00001601void ModuleBitcodeWriter::writeDITemplateValueParameter(
1602 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1603 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001604 Record.push_back(N->isDistinct());
1605 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001606 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1607 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1608 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1609
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001610 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001611 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001612}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001613
Teresa Johnson37687f32016-04-23 04:30:47 +00001614void ModuleBitcodeWriter::writeDIGlobalVariable(
1615 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1616 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001617 const uint64_t Version = 1 << 1;
1618 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001619 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1620 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1621 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1622 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1623 Record.push_back(N->getLine());
1624 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1625 Record.push_back(N->isLocalToUnit());
1626 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001627 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001628 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001629 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001630
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001631 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001632 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001633}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001634
Teresa Johnson37687f32016-04-23 04:30:47 +00001635void ModuleBitcodeWriter::writeDILocalVariable(
1636 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1637 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001638 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001639 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001640 // 1) Record has no artificial tag (Record[1]),
1641 // has no obsolete inlinedAt field (Record[9]).
1642 // In this case Record size will be 8, HasAlignment flag is false.
1643 // 2) Record has artificial tag (Record[1]),
1644 // has no obsolete inlignedAt field (Record[9]).
1645 // In this case Record size will be 9, HasAlignment flag is false.
1646 // 3) Record has both artificial tag (Record[1]) and
1647 // obsolete inlignedAt field (Record[9]).
1648 // In this case Record size will be 10, HasAlignment flag is false.
1649 // 4) Record has neither artificial tag, nor inlignedAt field, but
1650 // HasAlignment flag is true and Record[8] contains alignment value.
1651 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001652 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001653 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1654 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1655 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1656 Record.push_back(N->getLine());
1657 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1658 Record.push_back(N->getArg());
1659 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001660 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001661
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001662 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001663 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001664}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001665
Teresa Johnson37687f32016-04-23 04:30:47 +00001666void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1667 SmallVectorImpl<uint64_t> &Record,
1668 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001669 Record.reserve(N->getElements().size() + 1);
Adrian Prantl6825fb62017-04-18 01:21:53 +00001670 const uint64_t Version = 2 << 1;
1671 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001672 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001673
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001674 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001675 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001676}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001677
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001678void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1679 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1680 unsigned Abbrev) {
1681 Record.push_back(N->isDistinct());
1682 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1683 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1684
1685 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1686 Record.clear();
1687}
1688
Teresa Johnson37687f32016-04-23 04:30:47 +00001689void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1690 SmallVectorImpl<uint64_t> &Record,
1691 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001692 Record.push_back(N->isDistinct());
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1694 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1695 Record.push_back(N->getLine());
1696 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1697 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1698 Record.push_back(N->getAttributes());
1699 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1700
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001701 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001702 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001703}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001704
Teresa Johnson37687f32016-04-23 04:30:47 +00001705void ModuleBitcodeWriter::writeDIImportedEntity(
1706 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1707 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001708 Record.push_back(N->isDistinct());
1709 Record.push_back(N->getTag());
1710 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1711 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1712 Record.push_back(N->getLine());
1713 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1714
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001715 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001716 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001717}
1718
Teresa Johnson37687f32016-04-23 04:30:47 +00001719unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001720 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001721 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001724 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001725}
1726
Teresa Johnson37687f32016-04-23 04:30:47 +00001727void ModuleBitcodeWriter::writeNamedMetadata(
1728 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001729 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001730 return;
1731
Teresa Johnson37687f32016-04-23 04:30:47 +00001732 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001733 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001734 // Write name.
1735 StringRef Str = NMD.getName();
1736 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001737 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001738 Record.clear();
1739
1740 // Write named metadata operands.
1741 for (const MDNode *N : NMD.operands())
1742 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001743 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001744 Record.clear();
1745 }
1746}
1747
Teresa Johnson37687f32016-04-23 04:30:47 +00001748unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001749 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001750 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1751 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001754 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001755}
1756
1757/// Write out a record for MDString.
1758///
1759/// All the metadata strings in a metadata block are emitted in a single
1760/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001761void ModuleBitcodeWriter::writeMetadataStrings(
1762 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001763 if (Strings.empty())
1764 return;
1765
1766 // Start the record with the number of strings.
1767 Record.push_back(bitc::METADATA_STRINGS);
1768 Record.push_back(Strings.size());
1769
1770 // Emit the sizes of the strings in the blob.
1771 SmallString<256> Blob;
1772 {
1773 BitstreamWriter W(Blob);
1774 for (const Metadata *MD : Strings)
1775 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1776 W.FlushToWord();
1777 }
1778
1779 // Add the offset to the strings to the record.
1780 Record.push_back(Blob.size());
1781
1782 // Add the strings to the blob.
1783 for (const Metadata *MD : Strings)
1784 Blob.append(cast<MDString>(MD)->getString());
1785
1786 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001787 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001788 Record.clear();
1789}
1790
Mehdi Aminie98f9252016-12-28 22:30:28 +00001791// Generates an enum to use as an index in the Abbrev array of Metadata record.
1792enum MetadataAbbrev : unsigned {
1793#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1794#include "llvm/IR/Metadata.def"
1795 LastPlusOne
1796};
1797
Teresa Johnson37687f32016-04-23 04:30:47 +00001798void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001799 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1800 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001801 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001802 return;
1803
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001804 // Initialize MDNode abbreviations.
1805#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1806#include "llvm/IR/Metadata.def"
1807
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001808 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001809 if (IndexPos)
1810 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001811 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001812 assert(N->isResolved() && "Expected forward references to be resolved");
1813
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001814 switch (N->getMetadataID()) {
1815 default:
1816 llvm_unreachable("Invalid MDNode subclass");
1817#define HANDLE_MDNODE_LEAF(CLASS) \
1818 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001819 if (MDAbbrevs) \
1820 write##CLASS(cast<CLASS>(N), Record, \
1821 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1822 else \
1823 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001824 continue;
1825#include "llvm/IR/Metadata.def"
1826 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001827 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001828 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001829 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001830}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001831
Teresa Johnson37687f32016-04-23 04:30:47 +00001832void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001833 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001834 return;
1835
Mehdi Aminie98f9252016-12-28 22:30:28 +00001836 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001837 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001838
1839 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1840 // block and load any metadata.
1841 std::vector<unsigned> MDAbbrevs;
1842
1843 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1844 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1845 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1846 createGenericDINodeAbbrev();
1847
David Blaikie7ad9dc12017-01-04 22:36:33 +00001848 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001849 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001850 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1851 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001852 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001853
David Blaikie7ad9dc12017-01-04 22:36:33 +00001854 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001855 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1856 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001858 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001859
1860 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001861 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00001862
1863 // We only emit an index for the metadata record if we have more than a given
1864 // (naive) threshold of metadatas, otherwise it is not worth it.
1865 if (VE.getNonMDStrings().size() > IndexThreshold) {
1866 // Write a placeholder value in for the offset of the metadata index,
1867 // which is written after the records, so that it can include
1868 // the offset of each entry. The placeholder offset will be
1869 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00001870 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00001871 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1872 }
1873
1874 // Compute and save the bit offset to the current position, which will be
1875 // patched when we emit the index later. We can simply subtract the 64-bit
1876 // fixed size from the current bit number to get the location to backpatch.
1877 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1878
1879 // This index will contain the bitpos for each individual record.
1880 std::vector<uint64_t> IndexPos;
1881 IndexPos.reserve(VE.getNonMDStrings().size());
1882
1883 // Write all the records
1884 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1885
1886 if (VE.getNonMDStrings().size() > IndexThreshold) {
1887 // Now that we have emitted all the records we will emit the index. But
1888 // first
1889 // backpatch the forward reference so that the reader can skip the records
1890 // efficiently.
1891 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1892 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1893
1894 // Delta encode the index.
1895 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1896 for (auto &Elt : IndexPos) {
1897 auto EltDelta = Elt - PreviousValue;
1898 PreviousValue = Elt;
1899 Elt = EltDelta;
1900 }
1901 // Emit the index record.
1902 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1903 IndexPos.clear();
1904 }
1905
1906 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00001907 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00001908
1909 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1910 SmallVector<uint64_t, 4> Record;
1911 Record.push_back(VE.getValueID(&GO));
1912 pushGlobalMetadataAttachment(Record, GO);
1913 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1914 };
1915 for (const Function &F : M)
1916 if (F.isDeclaration() && F.hasMetadata())
1917 AddDeclAttachedMetadata(F);
1918 // FIXME: Only store metadata for declarations here, and move data for global
1919 // variable definitions to a separate block (PR28134).
1920 for (const GlobalVariable &GV : M.globals())
1921 if (GV.hasMetadata())
1922 AddDeclAttachedMetadata(GV);
1923
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001924 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001925}
1926
Teresa Johnson37687f32016-04-23 04:30:47 +00001927void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00001928 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001929 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001930
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001931 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001932 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001933 writeMetadataStrings(VE.getMDStrings(), Record);
1934 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001935 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00001936}
1937
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001938void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1939 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1940 // [n x [id, mdnode]]
1941 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1942 GO.getAllMetadata(MDs);
1943 for (const auto &I : MDs) {
1944 Record.push_back(I.first);
1945 Record.push_back(VE.getMetadataID(I.second));
1946 }
1947}
1948
1949void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001950 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00001951
Devang Patelaf206b82009-09-18 19:26:43 +00001952 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001953
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001954 if (F.hasMetadata()) {
1955 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001956 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001957 Record.clear();
1958 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001959
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001960 // Write metadata attachments
1961 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1962 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001963 for (const BasicBlock &BB : F)
1964 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00001965 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001966 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001967
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001968 // If no metadata, ignore instruction.
1969 if (MDs.empty()) continue;
1970
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001971 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001972
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001973 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1974 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001975 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00001976 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001977 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001978 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00001979 }
1980
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001981 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001982}
1983
Peter Collingbourne21521892016-06-21 23:42:48 +00001984void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00001985 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Devang Patelaf206b82009-09-18 19:26:43 +00001987 // Write metadata kinds
1988 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00001989 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001990 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001991
Dan Gohman43aa8f02010-07-20 21:42:28 +00001992 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00001993
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001994 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001995
Dan Gohman43aa8f02010-07-20 21:42:28 +00001996 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00001997 Record.push_back(MDKindID);
1998 StringRef KName = Names[MDKindID];
1999 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002000
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002001 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002002 Record.clear();
2003 }
2004
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002005 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002006}
2007
Teresa Johnson37687f32016-04-23 04:30:47 +00002008void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002009 // Write metadata kinds
2010 //
2011 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2012 //
2013 // OPERAND_BUNDLE_TAG - [strchr x N]
2014
2015 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002016 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002017
2018 if (Tags.empty())
2019 return;
2020
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002021 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002022
2023 SmallVector<uint64_t, 64> Record;
2024
2025 for (auto Tag : Tags) {
2026 Record.append(Tag.begin(), Tag.end());
2027
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002028 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002029 Record.clear();
2030 }
2031
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002032 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002033}
2034
Jan Wen Voungafaced02012-10-11 20:20:40 +00002035static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2036 if ((int64_t)V >= 0)
2037 Vals.push_back(V << 1);
2038 else
2039 Vals.push_back((-V << 1) | 1);
2040}
2041
Teresa Johnson37687f32016-04-23 04:30:47 +00002042void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2043 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002044 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002045
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002046 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002047
2048 unsigned AggregateAbbrev = 0;
2049 unsigned String8Abbrev = 0;
2050 unsigned CString7Abbrev = 0;
2051 unsigned CString6Abbrev = 0;
2052 // If this is a constant pool for the module, emit module-specific abbrevs.
2053 if (isGlobal) {
2054 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002055 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002056 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002059 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002060
2061 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002062 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002063 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002066 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002067 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002068 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002069 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002072 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002073 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002074 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002075 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002078 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002079 }
2080
Devang Patel8cca7b42009-08-04 05:01:35 +00002081 SmallVector<uint64_t, 64> Record;
2082
2083 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002084 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002085 for (unsigned i = FirstVal; i != LastVal; ++i) {
2086 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002087 // If we need to switch types, do so now.
2088 if (V->getType() != LastTy) {
2089 LastTy = V->getType();
2090 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002091 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2092 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002093 Record.clear();
2094 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002095
Chris Lattner52523562007-04-24 00:16:04 +00002096 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002097 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002098 unsigned(IA->isAlignStack()) << 1 |
2099 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002100
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002101 // Add the asm string.
2102 const std::string &AsmStr = IA->getAsmString();
2103 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002104 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002105
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002106 // Add the constraint string.
2107 const std::string &ConstraintStr = IA->getConstraintString();
2108 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002109 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002110 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002111 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002112 continue;
2113 }
2114 const Constant *C = cast<Constant>(V);
2115 unsigned Code = -1U;
2116 unsigned AbbrevToUse = 0;
2117 if (C->isNullValue()) {
2118 Code = bitc::CST_CODE_NULL;
2119 } else if (isa<UndefValue>(C)) {
2120 Code = bitc::CST_CODE_UNDEF;
2121 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002122 if (IV->getBitWidth() <= 64) {
2123 uint64_t V = IV->getSExtValue();
2124 emitSignedInt64(Record, V);
2125 Code = bitc::CST_CODE_INTEGER;
2126 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2127 } else { // Wide integers, > 64 bits in size.
2128 // We have an arbitrary precision integer value to write whose
2129 // bit width is > 64. However, in canonical unsigned integer
2130 // format it is likely that the high bits are going to be zero.
2131 // So, we only write the number of active words.
2132 unsigned NWords = IV->getValue().getActiveWords();
2133 const uint64_t *RawWords = IV->getValue().getRawData();
2134 for (unsigned i = 0; i != NWords; ++i) {
2135 emitSignedInt64(Record, RawWords[i]);
2136 }
2137 Code = bitc::CST_CODE_WIDE_INTEGER;
2138 }
Chris Lattner52523562007-04-24 00:16:04 +00002139 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2140 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002141 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002142 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002143 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002144 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002145 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002146 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002147 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002148 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002149 Record.push_back((p[1] << 48) | (p[0] >> 16));
2150 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002151 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002152 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002153 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002154 Record.push_back(p[0]);
2155 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002156 } else {
2157 assert (0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002158 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002159 } else if (isa<ConstantDataSequential>(C) &&
2160 cast<ConstantDataSequential>(C)->isString()) {
2161 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2162 // Emit constant strings specially.
2163 unsigned NumElts = Str->getNumElements();
2164 // If this is a null-terminated string, use the denser CSTRING encoding.
2165 if (Str->isCString()) {
2166 Code = bitc::CST_CODE_CSTRING;
2167 --NumElts; // Don't encode the null, which isn't allowed by char6.
2168 } else {
2169 Code = bitc::CST_CODE_STRING;
2170 AbbrevToUse = String8Abbrev;
2171 }
2172 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2173 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2174 for (unsigned i = 0; i != NumElts; ++i) {
2175 unsigned char V = Str->getElementAsInteger(i);
2176 Record.push_back(V);
2177 isCStr7 &= (V & 128) == 0;
2178 if (isCStrChar6)
2179 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2180 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002181
Chris Lattner372dd1e2012-01-30 00:51:16 +00002182 if (isCStrChar6)
2183 AbbrevToUse = CString6Abbrev;
2184 else if (isCStr7)
2185 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002186 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002187 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002188 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002189 Type *EltTy = CDS->getType()->getElementType();
2190 if (isa<IntegerType>(EltTy)) {
2191 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2192 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002193 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002194 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2195 Record.push_back(
2196 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002197 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002198 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002199 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002200 for (const Value *Op : C->operands())
2201 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002202 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002203 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002204 switch (CE->getOpcode()) {
2205 default:
2206 if (Instruction::isCast(CE->getOpcode())) {
2207 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002208 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002209 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2210 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002211 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002212 } else {
2213 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2214 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002215 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002216 Record.push_back(VE.getValueID(C->getOperand(0)));
2217 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002218 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002219 if (Flags != 0)
2220 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002221 }
2222 break;
David Blaikieb9263572015-03-13 21:03:36 +00002223 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002224 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002225 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002226 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002227 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2228 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2229 Record.push_back((*Idx << 1) | GO->isInBounds());
2230 } else if (GO->isInBounds())
2231 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002232 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2233 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2234 Record.push_back(VE.getValueID(C->getOperand(i)));
2235 }
2236 break;
David Blaikieb9263572015-03-13 21:03:36 +00002237 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002238 case Instruction::Select:
2239 Code = bitc::CST_CODE_CE_SELECT;
2240 Record.push_back(VE.getValueID(C->getOperand(0)));
2241 Record.push_back(VE.getValueID(C->getOperand(1)));
2242 Record.push_back(VE.getValueID(C->getOperand(2)));
2243 break;
2244 case Instruction::ExtractElement:
2245 Code = bitc::CST_CODE_CE_EXTRACTELT;
2246 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2247 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002248 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002249 Record.push_back(VE.getValueID(C->getOperand(1)));
2250 break;
2251 case Instruction::InsertElement:
2252 Code = bitc::CST_CODE_CE_INSERTELT;
2253 Record.push_back(VE.getValueID(C->getOperand(0)));
2254 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002255 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002256 Record.push_back(VE.getValueID(C->getOperand(2)));
2257 break;
2258 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002259 // If the return type and argument types are the same, this is a
2260 // standard shufflevector instruction. If the types are different,
2261 // then the shuffle is widening or truncating the input vectors, and
2262 // the argument type must also be encoded.
2263 if (C->getType() == C->getOperand(0)->getType()) {
2264 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2265 } else {
2266 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2267 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2268 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002269 Record.push_back(VE.getValueID(C->getOperand(0)));
2270 Record.push_back(VE.getValueID(C->getOperand(1)));
2271 Record.push_back(VE.getValueID(C->getOperand(2)));
2272 break;
2273 case Instruction::ICmp:
2274 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002275 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002276 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2277 Record.push_back(VE.getValueID(C->getOperand(0)));
2278 Record.push_back(VE.getValueID(C->getOperand(1)));
2279 Record.push_back(CE->getPredicate());
2280 break;
2281 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002282 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002283 Code = bitc::CST_CODE_BLOCKADDRESS;
2284 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2285 Record.push_back(VE.getValueID(BA->getFunction()));
2286 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002287 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002288#ifndef NDEBUG
2289 C->dump();
2290#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002291 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002292 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002293 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002294 Record.clear();
2295 }
2296
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002297 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002298}
2299
Teresa Johnson37687f32016-04-23 04:30:47 +00002300void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002301 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002302
Chris Lattner52523562007-04-24 00:16:04 +00002303 // Find the first constant to emit, which is the first non-globalvalue value.
2304 // We know globalvalues have been emitted by WriteModuleInfo.
2305 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2306 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002307 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002308 return;
2309 }
2310 }
2311}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002312
Teresa Johnson37687f32016-04-23 04:30:47 +00002313/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002314/// many values, because we need to know what type to create for forward
2315/// references. However, most operands are not forward references, so this type
2316/// field is not needed.
2317///
2318/// This function adds V's value ID to Vals. If the value ID is higher than the
2319/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002320/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002321bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2322 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002323 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002324 // Make encoding relative to the InstID.
2325 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002326 if (ValID >= InstID) {
2327 Vals.push_back(VE.getTypeID(V->getType()));
2328 return true;
2329 }
2330 return false;
2331}
2332
Teresa Johnson37687f32016-04-23 04:30:47 +00002333void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2334 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002335 SmallVector<unsigned, 64> Record;
2336 LLVMContext &C = CS.getInstruction()->getContext();
2337
2338 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002339 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002340 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002341
2342 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002343 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002344
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002345 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002346 Record.clear();
2347 }
2348}
2349
Teresa Johnson37687f32016-04-23 04:30:47 +00002350/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002351/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002352void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2353 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002354 unsigned ValID = VE.getValueID(V);
2355 Vals.push_back(InstID - ValID);
2356}
2357
Teresa Johnson37687f32016-04-23 04:30:47 +00002358void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2359 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002360 unsigned ValID = VE.getValueID(V);
2361 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2362 emitSignedInt64(Vals, diff);
2363}
2364
Chris Lattnere6e364c2007-04-26 05:53:54 +00002365/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002366void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2367 unsigned InstID,
2368 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002369 unsigned Code = 0;
2370 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002371 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002372 switch (I.getOpcode()) {
2373 default:
2374 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002375 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002376 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002377 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002378 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002379 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002380 } else {
2381 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002382 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002383 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002384 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002385 pushValue(I.getOperand(1), InstID, Vals);
2386 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2387 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002388 if (Flags != 0) {
2389 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2390 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2391 Vals.push_back(Flags);
2392 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002393 }
2394 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002395
David Blaikieb5b5efd2015-02-25 01:08:52 +00002396 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002397 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002398 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2399 auto &GEPInst = cast<GetElementPtrInst>(I);
2400 Vals.push_back(GEPInst.isInBounds());
2401 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002402 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002403 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002404 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002405 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002406 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002407 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002408 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002409 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002410 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002411 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002412 }
2413 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002414 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002415 pushValueAndType(I.getOperand(0), InstID, Vals);
2416 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002417 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002418 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002419 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002420 }
Chris Lattner0a603252007-05-01 02:13:26 +00002421 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002422 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002423 pushValueAndType(I.getOperand(1), InstID, Vals);
2424 pushValue(I.getOperand(2), InstID, Vals);
2425 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002426 break;
2427 case Instruction::ExtractElement:
2428 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002429 pushValueAndType(I.getOperand(0), InstID, Vals);
2430 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002431 break;
2432 case Instruction::InsertElement:
2433 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002434 pushValueAndType(I.getOperand(0), InstID, Vals);
2435 pushValue(I.getOperand(1), InstID, Vals);
2436 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002437 break;
2438 case Instruction::ShuffleVector:
2439 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002440 pushValueAndType(I.getOperand(0), InstID, Vals);
2441 pushValue(I.getOperand(1), InstID, Vals);
2442 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002443 break;
2444 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002445 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002446 // compare returning Int1Ty or vector of Int1Ty
2447 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002448 pushValueAndType(I.getOperand(0), InstID, Vals);
2449 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002450 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002451 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002452 if (Flags != 0)
2453 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002454 break;
James Molloy88eb5352015-07-10 12:52:00 +00002455 }
Chris Lattner0a603252007-05-01 02:13:26 +00002456
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002457 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002458 {
2459 Code = bitc::FUNC_CODE_INST_RET;
2460 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002461 if (NumOperands == 0)
2462 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2463 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002464 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002465 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2466 } else {
2467 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002468 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002469 }
2470 }
Chris Lattner0a603252007-05-01 02:13:26 +00002471 break;
2472 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002473 {
2474 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002475 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002476 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2477 if (II.isConditional()) {
2478 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002479 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002480 }
Chris Lattner0a603252007-05-01 02:13:26 +00002481 }
2482 break;
2483 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002484 {
2485 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002486 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002487 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002488 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002489 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002490 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002491 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2492 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002493 }
2494 }
Chris Lattner0a603252007-05-01 02:13:26 +00002495 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002496 case Instruction::IndirectBr:
2497 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002498 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002499 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002500 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002501 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002502 Vals.push_back(VE.getValueID(I.getOperand(i)));
2503 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002504
Chris Lattnerb811e952007-05-01 07:03:37 +00002505 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002506 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002507 const Value *Callee = II->getCalledValue();
2508 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002509
2510 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002511 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002512
Chris Lattner0a603252007-05-01 02:13:26 +00002513 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002514
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002515 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002516 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002517 Vals.push_back(VE.getValueID(II->getNormalDest()));
2518 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002519 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002520 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521
Chris Lattner0a603252007-05-01 02:13:26 +00002522 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002523 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002524 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002525
2526 // Emit type/value pairs for varargs params.
2527 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002528 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002529 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002530 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002531 }
2532 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002533 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002534 case Instruction::Resume:
2535 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002536 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002537 break;
David Majnemer654e1302015-07-31 17:58:14 +00002538 case Instruction::CleanupRet: {
2539 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2540 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002541 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002542 if (CRI.hasUnwindDest())
2543 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2544 break;
2545 }
2546 case Instruction::CatchRet: {
2547 Code = bitc::FUNC_CODE_INST_CATCHRET;
2548 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002549 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002550 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2551 break;
2552 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002553 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002554 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002555 const auto &FuncletPad = cast<FuncletPadInst>(I);
2556 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2557 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002558 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002559
2560 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002561 Vals.push_back(NumArgOperands);
2562 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002563 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002564 break;
2565 }
2566 case Instruction::CatchSwitch: {
2567 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2568 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2569
Teresa Johnson37687f32016-04-23 04:30:47 +00002570 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002571
2572 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2573 Vals.push_back(NumHandlers);
2574 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2575 Vals.push_back(VE.getValueID(CatchPadBB));
2576
2577 if (CatchSwitch.hasUnwindDest())
2578 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002579 break;
2580 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002581 case Instruction::Unreachable:
2582 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002583 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002584 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002585
Jay Foad372ad642011-06-20 14:18:48 +00002586 case Instruction::PHI: {
2587 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002588 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002589 // With the newer instruction encoding, forward references could give
2590 // negative valued IDs. This is most common for PHIs, so we use
2591 // signed VBRs.
2592 SmallVector<uint64_t, 128> Vals64;
2593 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002594 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002595 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002596 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002597 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002598 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002599 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002600 Vals64.clear();
2601 return;
Jay Foad372ad642011-06-20 14:18:48 +00002602 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002603
Bill Wendlingfae14752011-08-12 20:24:12 +00002604 case Instruction::LandingPad: {
2605 const LandingPadInst &LP = cast<LandingPadInst>(I);
2606 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2607 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002608 Vals.push_back(LP.isCleanup());
2609 Vals.push_back(LP.getNumClauses());
2610 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2611 if (LP.isCatch(I))
2612 Vals.push_back(LandingPadInst::Catch);
2613 else
2614 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002615 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002616 }
2617 break;
2618 }
2619
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002620 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002621 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002622 const AllocaInst &AI = cast<AllocaInst>(I);
2623 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002624 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002625 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002626 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2627 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2628 "not enough bits for maximum alignment");
2629 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2630 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002631 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002632 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002633 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002634 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002636
Chris Lattner0a603252007-05-01 02:13:26 +00002637 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002638 if (cast<LoadInst>(I).isAtomic()) {
2639 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002640 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002641 } else {
2642 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002643 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002644 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2645 }
David Blaikie85035652015-02-25 01:07:20 +00002646 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002647 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2648 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002649 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002650 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2651 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002652 }
Chris Lattner0a603252007-05-01 02:13:26 +00002653 break;
2654 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002655 if (cast<StoreInst>(I).isAtomic())
2656 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2657 else
2658 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002659 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2660 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002661 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2662 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002663 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002664 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2665 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002666 }
Chris Lattner0a603252007-05-01 02:13:26 +00002667 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002668 case Instruction::AtomicCmpXchg:
2669 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002670 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2671 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2672 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002673 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002674 Vals.push_back(
2675 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2676 Vals.push_back(
2677 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2678 Vals.push_back(
2679 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002680 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002681 break;
2682 case Instruction::AtomicRMW:
2683 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002684 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2685 pushValue(I.getOperand(1), InstID, Vals); // val.
2686 Vals.push_back(
2687 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002688 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002689 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2690 Vals.push_back(
2691 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002692 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002693 case Instruction::Fence:
2694 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002695 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2696 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002697 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002698 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002699 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002700 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002701
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002702 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002703 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002704
Chris Lattnerc44070802011-06-17 18:17:37 +00002705 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002706
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002707 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002708
Teresa Johnson37687f32016-04-23 04:30:47 +00002709 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002710 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2711 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2712 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2713 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002714 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2715 unsigned(Flags != 0) << bitc::CALL_FMF);
2716 if (Flags != 0)
2717 Vals.push_back(Flags);
2718
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002719 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002720 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002721
Chris Lattner0a603252007-05-01 02:13:26 +00002722 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002723 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2724 // Check for labels (can happen with asm labels).
2725 if (FTy->getParamType(i)->isLabelTy())
2726 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2727 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002728 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002729 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002730
Chris Lattnerb811e952007-05-01 07:03:37 +00002731 // Emit type/value pairs for varargs params.
2732 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002733 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002734 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002735 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002736 }
2737 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002738 }
Chris Lattner0a603252007-05-01 02:13:26 +00002739 case Instruction::VAArg:
2740 Code = bitc::FUNC_CODE_INST_VAARG;
2741 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002742 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002743 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2744 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002745 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002746
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002747 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002748 Vals.clear();
2749}
2750
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002751/// Write a GlobalValue VST to the module. The purpose of this data structure is
2752/// to allow clients to efficiently find the function body.
2753void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2754 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2755 // Get the offset of the VST we are writing, and backpatch it into
2756 // the VST forward declaration record.
2757 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2758 // The BitcodeStartBit was the stream offset of the identification block.
2759 VSTOffset -= bitcodeStartBit();
2760 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2761 // Note that we add 1 here because the offset is relative to one word
2762 // before the start of the identification block, which was historically
2763 // always the start of the regular bitcode header.
2764 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002765
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002766 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002767
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002768 auto Abbv = std::make_shared<BitCodeAbbrev>();
2769 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2771 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2772 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002773
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002774 for (const Function &F : M) {
2775 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002776
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002777 if (F.isDeclaration())
2778 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002779
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002780 Record[0] = VE.getValueID(&F);
2781
2782 // Save the word offset of the function (from the start of the
2783 // actual bitcode written to the stream).
2784 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2785 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2786 // Note that we add 1 here because the offset is relative to one word
2787 // before the start of the identification block, which was historically
2788 // always the start of the regular bitcode header.
2789 Record[1] = BitcodeIndex / 32 + 1;
2790
2791 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002792 }
2793
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002794 Stream.ExitBlock();
2795}
2796
2797/// Emit names for arguments, instructions and basic blocks in a function.
2798void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2799 const ValueSymbolTable &VST) {
2800 if (VST.empty())
2801 return;
2802
2803 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2804
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002805 // FIXME: Set up the abbrev, we know how many values there are!
2806 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002807 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808
Yaron Keren001e2e42015-08-10 07:04:29 +00002809 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002810 // Figure out the encoding to use for the name.
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002811 StringEncoding Bits =
2812 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002813
Chris Lattnera0987962007-05-04 21:31:13 +00002814 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002815 NameVals.push_back(VE.getValueID(Name.getValue()));
2816
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002817 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002818 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002819 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002820 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002821 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002822 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002823 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002824 } else {
2825 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002826 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002827 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002828 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002829 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002831
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002832 for (const auto P : Name.getKey())
2833 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002835 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002836 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002837 NameVals.clear();
2838 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002839
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002840 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002841}
2842
Teresa Johnson37687f32016-04-23 04:30:47 +00002843void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002844 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2845 unsigned Code;
2846 if (isa<BasicBlock>(Order.V))
2847 Code = bitc::USELIST_CODE_BB;
2848 else
2849 Code = bitc::USELIST_CODE_DEFAULT;
2850
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002851 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002852 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002853 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002854}
2855
Teresa Johnson37687f32016-04-23 04:30:47 +00002856void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002857 assert(VE.shouldPreserveUseListOrder() &&
2858 "Expected to be preserving use-list order");
2859
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002860 auto hasMore = [&]() {
2861 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2862 };
2863 if (!hasMore())
2864 // Nothing to do.
2865 return;
2866
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002867 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002868 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002869 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002870 VE.UseListOrders.pop_back();
2871 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002872 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002873}
2874
Teresa Johnson403a7872015-10-04 14:33:43 +00002875/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002876void ModuleBitcodeWriter::writeFunction(
2877 const Function &F,
2878 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002879 // Save the bitcode index of the start of this function block for recording
2880 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002881 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002882
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002883 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002884 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002885
2886 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
Chris Lattnere6e364c2007-04-26 05:53:54 +00002888 // Emit the number of basic blocks, so the reader can create them ahead of
2889 // time.
2890 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002891 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002892 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002893
Chris Lattnere6e364c2007-04-26 05:53:54 +00002894 // If there are function-local constants, emit them now.
2895 unsigned CstStart, CstEnd;
2896 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00002897 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002898
Victor Hernandez6c730de2010-01-14 01:50:08 +00002899 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002900 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00002901
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002902 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002903 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002904
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002905 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002906
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002907 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002908 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002909 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002910 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2911 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002912 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002913
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002914 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002915 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002916
Chris Lattner07d09ed2010-04-03 02:17:50 +00002917 // If the instruction has metadata, write a metadata attachment later.
2918 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002919
Chris Lattner07d09ed2010-04-03 02:17:50 +00002920 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002921 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002922 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002923 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002924
2925 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00002926 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002927 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002928 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002929 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002930
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002931 Vals.push_back(DL->getLine());
2932 Vals.push_back(DL->getColumn());
2933 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2934 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002935 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002936 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00002937
2938 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002939 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002940
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002941 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002942 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002943 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00002944
Chris Lattner07d09ed2010-04-03 02:17:50 +00002945 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002946 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002947 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00002948 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00002949 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002950 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00002951}
2952
Chris Lattner702658c2007-05-04 18:26:27 +00002953// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002954void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00002955 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00002956 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00002957 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00002958 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002959
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002960 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002961 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002962 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2963 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2964 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2965 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002966 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002967 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002968 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002969 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002970
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002971 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002972 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002973 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2974 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2975 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002977 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002978 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002979 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002980 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002981 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002982 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00002983 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2984 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2985 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002987 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002988 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002989 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00002990 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002991 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002992 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002993 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00002996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002997 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002998 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002999 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003000 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003001
3002
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003003
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003004 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003005 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003006 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003008 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003009 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003010 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003011 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003012 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003013
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003014 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003015 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003016 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3017 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003018 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003019 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003020 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003021 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003022
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003023 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003024 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003025 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3026 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3027 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003028 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003029 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3030
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003031 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003032 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003033 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003034 }
3035 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003036 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003037 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003038 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003039 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003040 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003041 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003042
Chris Lattnerb80751d2007-05-05 07:44:49 +00003043 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003044
Chris Lattnerb80751d2007-05-05 07:44:49 +00003045 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003046 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003047 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3050 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003053 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003054 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003055 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003056 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003057 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003058 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003059 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003063 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003064 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003065 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003066 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003067 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003068 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003069 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003074 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003075 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003076 llvm_unreachable("Unexpected abbrev ordering!");
3077 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003078 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003079 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003080 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3081 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003083 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003084 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003085 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003086 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003087 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003088 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003089
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003090 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003091 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003092 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003093 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003094 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003095 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003096 }
3097 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003098 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003099 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003101 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003102 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003103 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003104 }
3105 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003106 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003107 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003108 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003109 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003110 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003111 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003112 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003113 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003114 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3115 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3116 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3117 Log2_32_Ceil(VE.getTypes().size() + 1)));
3118 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3119 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003120 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003121 FUNCTION_INST_GEP_ABBREV)
3122 llvm_unreachable("Unexpected abbrev ordering!");
3123 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003124
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003125 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003126}
3127
Teresa Johnson403a7872015-10-04 14:33:43 +00003128/// Write the module path strings, currently only used when generating
3129/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003130void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003131 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003132
3133 // TODO: See which abbrev sizes we actually need to emit
3134
3135 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003136 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003137 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003141 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003142
3143 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003144 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003145 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003149 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003150
3151 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003152 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003153 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003157 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003158
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003159 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003160 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003161 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3166 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003167 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003168
3169 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003170 forEachModule(
3171 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3172 StringEncoding Bits =
3173 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3174 unsigned AbbrevToUse = Abbrev8Bit;
3175 if (Bits == SE_Char6)
3176 AbbrevToUse = Abbrev6Bit;
3177 else if (Bits == SE_Fixed7)
3178 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003179
Teresa Johnson7a27b132017-06-02 01:56:02 +00003180 Vals.push_back(MPSE.getValue().first);
Teresa Johnson403a7872015-10-04 14:33:43 +00003181
Teresa Johnson7a27b132017-06-02 01:56:02 +00003182 for (const auto P : MPSE.getKey())
3183 Vals.push_back((unsigned char)P);
Teresa Johnson403a7872015-10-04 14:33:43 +00003184
Teresa Johnson7a27b132017-06-02 01:56:02 +00003185 // Emit the finished record.
3186 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003187
Teresa Johnson7a27b132017-06-02 01:56:02 +00003188 Vals.clear();
3189 // Emit an optional hash for the module now
3190 auto &Hash = MPSE.getValue().second;
3191 bool AllZero =
3192 true; // Detect if the hash is empty, and do not generate it
3193 for (auto Val : Hash) {
3194 if (Val)
3195 AllZero = false;
3196 Vals.push_back(Val);
3197 }
3198 if (!AllZero) {
3199 // Emit the hash record.
3200 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3201 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003202
Teresa Johnson7a27b132017-06-02 01:56:02 +00003203 Vals.clear();
3204 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003205 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003206}
3207
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003208/// Write the function type metadata related records that need to appear before
3209/// a function summary entry (whether per-module or combined).
3210static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3211 FunctionSummary *FS) {
3212 if (!FS->type_tests().empty())
3213 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3214
3215 SmallVector<uint64_t, 64> Record;
3216
3217 auto WriteVFuncIdVec = [&](uint64_t Ty,
3218 ArrayRef<FunctionSummary::VFuncId> VFs) {
3219 if (VFs.empty())
3220 return;
3221 Record.clear();
3222 for (auto &VF : VFs) {
3223 Record.push_back(VF.GUID);
3224 Record.push_back(VF.Offset);
3225 }
3226 Stream.EmitRecord(Ty, Record);
3227 };
3228
3229 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3230 FS->type_test_assume_vcalls());
3231 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3232 FS->type_checked_load_vcalls());
3233
3234 auto WriteConstVCallVec = [&](uint64_t Ty,
3235 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3236 for (auto &VC : VCs) {
3237 Record.clear();
3238 Record.push_back(VC.VFunc.GUID);
3239 Record.push_back(VC.VFunc.Offset);
3240 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3241 Stream.EmitRecord(Ty, Record);
3242 }
3243 };
3244
3245 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3246 FS->type_test_assume_const_vcalls());
3247 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3248 FS->type_checked_load_const_vcalls());
3249}
3250
Teresa Johnson403a7872015-10-04 14:33:43 +00003251// Helper to emit a single function summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003252void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003253 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003254 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3255 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003256 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003257
Teresa Johnson28e457b2016-04-24 14:57:11 +00003258 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003259 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003260
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003261 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003262 NameVals.push_back(FS->instCount());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003263 NameVals.push_back(FS->refs().size());
3264
3265 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003266 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003267
3268 bool HasProfileData = F.getEntryCount().hasValue();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003269 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003270 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003271 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003272 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003273 }
3274
3275 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3276 unsigned Code =
3277 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003278
3279 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003280 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003281 NameVals.clear();
3282}
3283
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003284// Collect the global value references in the given variable's initializer,
3285// and emit them in a summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003286void ModuleBitcodeWriter::writeModuleLevelReferences(
3287 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3288 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003289 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3290 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003291 // Only declarations should not have a summary (a declaration might however
3292 // have a summary if the def was in module level asm).
3293 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003294 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003295 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003296 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003297 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003298 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003299 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003300
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003301 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003302 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003303 NameVals.push_back(VE.getValueID(RI.getValue()));
3304 // Sort the refs for determinism output, the vector returned by FS->refs() has
3305 // been initialized from a DenseSet.
3306 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003307
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003308 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3309 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003310 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003311}
Teresa Johnson403a7872015-10-04 14:33:43 +00003312
Mehdi Amini8fe69362016-04-24 03:18:11 +00003313// Current version for the summary.
3314// This is bumped whenever we introduce changes in the way some record are
3315// interpreted, like flags for instance.
Teresa Johnson519465b2017-01-05 14:32:16 +00003316static const uint64_t INDEX_VERSION = 3;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003317
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003318/// Emit the per-module summary section alongside the rest of
3319/// the module's bitcode.
Teresa Johnson37687f32016-04-23 04:30:47 +00003320void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003321 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003322
Mehdi Amini8fe69362016-04-24 03:18:11 +00003323 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3324
Teresa Johnson620c1402016-09-20 23:07:17 +00003325 if (Index->begin() == Index->end()) {
3326 Stream.ExitBlock();
3327 return;
3328 }
3329
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003330 for (const auto &GVI : valueIds()) {
3331 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3332 ArrayRef<uint64_t>{GVI.second, GVI.first});
3333 }
3334
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003335 // Abbrev for FS_PERMODULE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003336 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003337 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003342 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003343 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3344 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003345 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003346
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003347 // Abbrev for FS_PERMODULE_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003348 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003349 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003354 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003357 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003358
3359 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003360 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003361 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003366 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003367
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003368 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003369 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003370 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003374 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003375
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003376 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003377 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003378 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003379 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003380 // Summary emission does not support anonymous functions, they have to
3381 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003382 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003383 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003384
Peter Collingbourne9667b912017-05-04 18:03:25 +00003385 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.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
3388 // however have a summary if the def was in module level asm).
3389 assert(F.isDeclaration());
3390 continue;
3391 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003392 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003393 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3394 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003395 }
3396
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003397 // Capture references from GlobalVariable initializers, which are outside
3398 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003399 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003400 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003401
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003402 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003403 auto *Aliasee = A.getBaseObject();
3404 if (!Aliasee->hasName())
3405 // Nameless function don't have an entry in the summary, skip it.
3406 continue;
3407 auto AliasId = VE.getValueID(&A);
3408 auto AliaseeId = VE.getValueID(Aliasee);
3409 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003410 auto *Summary = Index->getGlobalValueSummary(A);
3411 AliasSummary *AS = cast<AliasSummary>(Summary);
3412 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003413 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003414 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003415 NameVals.clear();
3416 }
3417
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003418 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003419}
3420
Teresa Johnson26ab5772016-03-15 00:04:37 +00003421/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003422void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003423 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003424 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003425
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003426 for (const auto &GVI : valueIds()) {
3427 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3428 ArrayRef<uint64_t>{GVI.second, GVI.first});
3429 }
3430
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003431 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003432 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003433 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3438 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003439 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003440 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3441 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003442 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003443
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003444 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003445 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003446 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3451 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003452 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003455 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003456
3457 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003458 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003459 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003465 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003466
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003467 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003468 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003469 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003470 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003474 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003475
Teresa Johnson02e98332016-04-27 13:28:35 +00003476 // The aliases are emitted as a post-pass, and will point to the value
3477 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003478 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003479
Teresa Johnson02e98332016-04-27 13:28:35 +00003480 // Save the value id for each summary for alias emission.
3481 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3482
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003483 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003484
3485 // For local linkage, we also emit the original name separately
3486 // immediately after the record.
3487 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3488 if (!GlobalValue::isLocalLinkage(S.linkage()))
3489 return;
3490 NameVals.push_back(S.getOriginalName());
3491 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3492 NameVals.clear();
3493 };
3494
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003495 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003496 GlobalValueSummary *S = I.second;
3497 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003498
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003499 auto ValueId = getValueId(I.first);
3500 assert(ValueId);
3501 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003502
Teresa Johnson84174c32016-05-10 13:48:23 +00003503 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3504 // Will process aliases as a post-pass because the reader wants all
3505 // global to be loaded first.
3506 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003507 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003508 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003509
Teresa Johnson84174c32016-05-10 13:48:23 +00003510 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003511 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003512 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3513 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3514 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003515 auto RefValueId = getValueId(RI.getGUID());
3516 if (!RefValueId)
3517 continue;
3518 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003519 }
3520
Teresa Johnson403a7872015-10-04 14:33:43 +00003521 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003522 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3523 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003524 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003525 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003526 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003527 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003528
3529 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003530 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003531
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003532 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003533 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3534 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3535 NameVals.push_back(FS->instCount());
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003536 // Fill in below
3537 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003538
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003539 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003540 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003541 auto RefValueId = getValueId(RI.getGUID());
3542 if (!RefValueId)
3543 continue;
3544 NameVals.push_back(*RefValueId);
3545 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003546 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003547 NameVals[4] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003548
3549 bool HasProfileData = false;
3550 for (auto &EI : FS->calls()) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003551 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003552 if (HasProfileData)
3553 break;
3554 }
3555
3556 for (auto &EI : FS->calls()) {
3557 // If this GUID doesn't have a value id, it doesn't have a function
3558 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003559 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003560 auto CallValueId = getValueId(GUID);
3561 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003562 // For SamplePGO, the indirect call targets for local functions will
3563 // have its original name annotated in profile. We try to find the
3564 // corresponding PGOFuncName as the GUID.
3565 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003566 if (GUID == 0)
3567 continue;
3568 CallValueId = getValueId(GUID);
3569 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003570 continue;
3571 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003572 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003573 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003574 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003575 }
3576
3577 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3578 unsigned Code =
3579 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3580
3581 // Emit the finished record.
3582 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3583 NameVals.clear();
3584 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003585 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003586
Teresa Johnson28e457b2016-04-24 14:57:11 +00003587 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003588 auto AliasValueId = SummaryToValueIdMap[AS];
3589 assert(AliasValueId);
3590 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003591 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003592 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003593 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3594 assert(AliaseeValueId);
3595 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003596
3597 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003598 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003599 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003600 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003601 }
3602
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003603 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003604}
3605
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003606/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3607/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003608static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003609 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003610
3611 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003612 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003613 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3614 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003616 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003617 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003618 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003619
3620 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003621 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003622 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3623 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003624 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003625 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003626 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3627 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003628}
3629
Teresa Johnson37687f32016-04-23 04:30:47 +00003630void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003631 // Emit the module's hash.
3632 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003633 if (GenerateHash) {
3634 SHA1 Hasher;
3635 uint32_t Vals[5];
3636 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3637 Buffer.size() - BlockStartPos));
3638 StringRef Hash = Hasher.result();
3639 for (int Pos = 0; Pos < 20; Pos += 4) {
3640 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3641 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003642
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003643 // Emit the finished record.
3644 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3645
3646 if (ModHash)
3647 // Save the written hash value.
3648 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3649 } else if (ModHash)
3650 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003651}
3652
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003653void ModuleBitcodeWriter::write() {
3654 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003655
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003656 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3657 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003658
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003659 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003660
3661 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003662 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003663
Bill Wendlingdc095552013-02-10 23:09:32 +00003664 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003665 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003666
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003667 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003668 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003669
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003670 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003671 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003672
Teresa Johnson37687f32016-04-23 04:30:47 +00003673 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003674
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003675 // Emit top-level description of module, including target triple, inline asm,
3676 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003677 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003678
Devang Patele059ba6e2009-07-23 01:07:34 +00003679 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003680 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003681
Peter Collingbourne21521892016-06-21 23:42:48 +00003682 // Emit metadata kind names.
3683 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003684
Devang Patelaf206b82009-09-18 19:26:43 +00003685 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003686 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003687
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003688 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003689 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003690 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003691
Teresa Johnson37687f32016-04-23 04:30:47 +00003692 writeOperandBundleTags();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003693
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003694 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003695 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003696 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003697 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003698 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003699
3700 // Need to write after the above call to WriteFunction which populates
3701 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003702 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003703 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003704
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003705 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003706
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003707 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003708
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003709 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003710}
3711
Teresa Johnson37687f32016-04-23 04:30:47 +00003712static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3713 uint32_t &Position) {
3714 support::endian::write32le(&Buffer[Position], Value);
3715 Position += 4;
3716}
3717
3718/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003719/// header and trailer to make it compatible with the system archiver. To do
3720/// this we emit the following header, and then emit a trailer that pads the
3721/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003722///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003723/// struct bc_header {
3724/// uint32_t Magic; // 0x0B17C0DE
3725/// uint32_t Version; // Version, currently always 0.
3726/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3727/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3728/// uint32_t CPUType; // CPU specifier.
3729/// ... potentially more later ...
3730/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003731static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003732 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003733 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003734
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003735 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003736 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3737 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3738 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003739 enum {
3740 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3741 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003742 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003743 DARWIN_CPU_TYPE_POWERPC = 18
3744 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003745
Evan Chengcffdcae2011-06-14 01:51:33 +00003746 Triple::ArchType Arch = TT.getArch();
3747 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003748 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003749 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003750 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003751 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003752 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003753 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003754 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003755 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003756 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003757
Chris Lattnera660f4b2008-07-09 05:14:23 +00003758 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003759 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003760 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003761 unsigned BCOffset = BWH_HeaderSize;
3762 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003763
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003764 // Write the magic and version.
3765 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003766 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3767 writeInt32ToBuffer(0, Buffer, Position); // Version.
3768 writeInt32ToBuffer(BCOffset, Buffer, Position);
3769 writeInt32ToBuffer(BCSize, Buffer, Position);
3770 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003771
Chris Lattnera660f4b2008-07-09 05:14:23 +00003772 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003773 while (Buffer.size() & 15)
3774 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003775}
3776
Teresa Johnson403a7872015-10-04 14:33:43 +00003777/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003778static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003779 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003780 Stream.Emit((unsigned)'B', 8);
3781 Stream.Emit((unsigned)'C', 8);
3782 Stream.Emit(0x0, 4);
3783 Stream.Emit(0xC, 4);
3784 Stream.Emit(0xE, 4);
3785 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003786}
3787
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003788BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3789 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3790 writeBitcodeHeader(*Stream);
3791}
3792
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003793BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3794
3795void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3796 Stream->EnterSubblock(Block, 3);
3797
3798 auto Abbv = std::make_shared<BitCodeAbbrev>();
3799 Abbv->Add(BitCodeAbbrevOp(Record));
3800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3801 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3802
3803 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3804
3805 Stream->ExitBlock();
3806}
3807
3808void BitcodeWriter::writeStrtab() {
3809 assert(!WroteStrtab);
3810
3811 std::vector<char> Strtab;
3812 StrtabBuilder.finalizeInOrder();
3813 Strtab.resize(StrtabBuilder.getSize());
3814 StrtabBuilder.write((uint8_t *)Strtab.data());
3815
3816 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3817 {Strtab.data(), Strtab.size()});
3818
3819 WroteStrtab = true;
3820}
3821
3822void BitcodeWriter::copyStrtab(StringRef Strtab) {
3823 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3824 WroteStrtab = true;
3825}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003826
3827void BitcodeWriter::writeModule(const Module *M,
3828 bool ShouldPreserveUseListOrder,
3829 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003830 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003831 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003832 ShouldPreserveUseListOrder, Index,
3833 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003834 ModuleWriter.write();
3835}
3836
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003837/// WriteBitcodeToFile - Write the specified module to the specified output
3838/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00003839void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00003840 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003841 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003842 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00003843 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003844 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003845
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003846 // If this is darwin or another generic macho target, reserve space for the
3847 // header.
3848 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00003849 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003850 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003851
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003852 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003853 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3854 ModHash);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003855 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003856
Akira Hatanaka1235d282016-01-23 16:02:10 +00003857 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00003858 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003859
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003860 // Write the generated bitstream to "Out".
3861 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003862}
Teresa Johnson403a7872015-10-04 14:33:43 +00003863
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003864void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003865 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00003866
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003867 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00003868
3869 // Write the module paths in the combined index.
3870 writeModStrings();
3871
3872 // Write the summary combined index records.
3873 writeCombinedGlobalValueSummary();
3874
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003875 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00003876}
3877
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003878// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00003879// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00003880// writing the combined index file for ThinLTO. When writing a subset of the
3881// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3882void llvm::WriteIndexToFile(
3883 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00003884 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003885 SmallVector<char, 0> Buffer;
3886 Buffer.reserve(256 * 1024);
3887
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003888 BitstreamWriter Stream(Buffer);
3889 writeBitcodeHeader(Stream);
3890
3891 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00003892 IndexWriter.write();
Teresa Johnson403a7872015-10-04 14:33:43 +00003893
3894 Out.write((char *)&Buffer.front(), Buffer.size());
3895}