blob: d5879fec95cbe73e2f0bcfce0be73a1325c3bd55 [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.
David Blaikie358c0122017-06-02 18:25:29 +0000354 template<typename Functor>
355 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000356 if (ModuleToSummariesForIndex) {
357 for (auto &M : *ModuleToSummariesForIndex)
358 for (auto &Summary : M.second)
359 Callback(Summary);
360 } else {
361 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000362 for (auto &Summary : Summaries.second.SummaryList)
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000363 Callback({Summaries.first, Summary.get()});
Teresa Johnson84174c32016-05-10 13:48:23 +0000364 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000365 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000366
Teresa Johnson7a27b132017-06-02 01:56:02 +0000367 /// Calls the callback for each entry in the modulePaths StringMap that
368 /// should be written to the module path string table. This hides the details
369 /// of whether they are being pulled from the entire index or just those in a
370 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000371 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000372 if (ModuleToSummariesForIndex) {
373 for (const auto &M : *ModuleToSummariesForIndex) {
374 const auto &MPI = Index.modulePaths().find(M.first);
375 if (MPI == Index.modulePaths().end()) {
376 // This should only happen if the bitcode file was empty, in which
377 // case we shouldn't be importing (the ModuleToSummariesForIndex
378 // would only include the module we are writing and index for).
379 assert(ModuleToSummariesForIndex->size() == 1);
380 continue;
381 }
382 Callback(*MPI);
383 }
384 } else {
385 for (const auto &MPSE : Index.modulePaths())
386 Callback(MPSE);
387 }
388 }
389
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000390 /// Main entry point for writing a combined index to bitcode.
391 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000392
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000393private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000394 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000395 void writeCombinedGlobalValueSummary();
396
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000397 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000398 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000399 if (VMI == GUIDToValueIdMap.end())
400 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000401 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000402 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000403 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
404};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000405} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000406
407static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000408 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000409 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000410 case Instruction::Trunc : return bitc::CAST_TRUNC;
411 case Instruction::ZExt : return bitc::CAST_ZEXT;
412 case Instruction::SExt : return bitc::CAST_SEXT;
413 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
414 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
415 case Instruction::UIToFP : return bitc::CAST_UITOFP;
416 case Instruction::SIToFP : return bitc::CAST_SITOFP;
417 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
418 case Instruction::FPExt : return bitc::CAST_FPEXT;
419 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
420 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
421 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000422 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000423 }
424}
425
Teresa Johnson37687f32016-04-23 04:30:47 +0000426static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000427 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000428 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000429 case Instruction::Add:
430 case Instruction::FAdd: return bitc::BINOP_ADD;
431 case Instruction::Sub:
432 case Instruction::FSub: return bitc::BINOP_SUB;
433 case Instruction::Mul:
434 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000435 case Instruction::UDiv: return bitc::BINOP_UDIV;
436 case Instruction::FDiv:
437 case Instruction::SDiv: return bitc::BINOP_SDIV;
438 case Instruction::URem: return bitc::BINOP_UREM;
439 case Instruction::FRem:
440 case Instruction::SRem: return bitc::BINOP_SREM;
441 case Instruction::Shl: return bitc::BINOP_SHL;
442 case Instruction::LShr: return bitc::BINOP_LSHR;
443 case Instruction::AShr: return bitc::BINOP_ASHR;
444 case Instruction::And: return bitc::BINOP_AND;
445 case Instruction::Or: return bitc::BINOP_OR;
446 case Instruction::Xor: return bitc::BINOP_XOR;
447 }
448}
449
Teresa Johnson37687f32016-04-23 04:30:47 +0000450static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000451 switch (Op) {
452 default: llvm_unreachable("Unknown RMW operation!");
453 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
454 case AtomicRMWInst::Add: return bitc::RMW_ADD;
455 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
456 case AtomicRMWInst::And: return bitc::RMW_AND;
457 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
458 case AtomicRMWInst::Or: return bitc::RMW_OR;
459 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
460 case AtomicRMWInst::Max: return bitc::RMW_MAX;
461 case AtomicRMWInst::Min: return bitc::RMW_MIN;
462 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
463 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
464 }
465}
466
Teresa Johnson37687f32016-04-23 04:30:47 +0000467static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000468 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000469 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
470 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
471 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
472 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
473 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
474 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
475 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000476 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000477 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000478}
479
Teresa Johnson37687f32016-04-23 04:30:47 +0000480static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000481 switch (SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000482 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
483 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
484 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000485 llvm_unreachable("Invalid synch scope");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000486}
487
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000488static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
489 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000490 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000491
Chris Lattnere14cb882007-05-04 19:11:41 +0000492 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000493 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
494 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
495 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000496 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000498
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000499 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000500 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000501}
502
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000503static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
504 switch (Kind) {
505 case Attribute::Alignment:
506 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000507 case Attribute::AllocSize:
508 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000509 case Attribute::AlwaysInline:
510 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000511 case Attribute::ArgMemOnly:
512 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000513 case Attribute::Builtin:
514 return bitc::ATTR_KIND_BUILTIN;
515 case Attribute::ByVal:
516 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000517 case Attribute::Convergent:
518 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000519 case Attribute::InAlloca:
520 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000521 case Attribute::Cold:
522 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000523 case Attribute::InaccessibleMemOnly:
524 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
525 case Attribute::InaccessibleMemOrArgMemOnly:
526 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000527 case Attribute::InlineHint:
528 return bitc::ATTR_KIND_INLINE_HINT;
529 case Attribute::InReg:
530 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000531 case Attribute::JumpTable:
532 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000533 case Attribute::MinSize:
534 return bitc::ATTR_KIND_MIN_SIZE;
535 case Attribute::Naked:
536 return bitc::ATTR_KIND_NAKED;
537 case Attribute::Nest:
538 return bitc::ATTR_KIND_NEST;
539 case Attribute::NoAlias:
540 return bitc::ATTR_KIND_NO_ALIAS;
541 case Attribute::NoBuiltin:
542 return bitc::ATTR_KIND_NO_BUILTIN;
543 case Attribute::NoCapture:
544 return bitc::ATTR_KIND_NO_CAPTURE;
545 case Attribute::NoDuplicate:
546 return bitc::ATTR_KIND_NO_DUPLICATE;
547 case Attribute::NoImplicitFloat:
548 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
549 case Attribute::NoInline:
550 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000551 case Attribute::NoRecurse:
552 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000553 case Attribute::NonLazyBind:
554 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000555 case Attribute::NonNull:
556 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000557 case Attribute::Dereferenceable:
558 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000559 case Attribute::DereferenceableOrNull:
560 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000561 case Attribute::NoRedZone:
562 return bitc::ATTR_KIND_NO_RED_ZONE;
563 case Attribute::NoReturn:
564 return bitc::ATTR_KIND_NO_RETURN;
565 case Attribute::NoUnwind:
566 return bitc::ATTR_KIND_NO_UNWIND;
567 case Attribute::OptimizeForSize:
568 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000569 case Attribute::OptimizeNone:
570 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000571 case Attribute::ReadNone:
572 return bitc::ATTR_KIND_READ_NONE;
573 case Attribute::ReadOnly:
574 return bitc::ATTR_KIND_READ_ONLY;
575 case Attribute::Returned:
576 return bitc::ATTR_KIND_RETURNED;
577 case Attribute::ReturnsTwice:
578 return bitc::ATTR_KIND_RETURNS_TWICE;
579 case Attribute::SExt:
580 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000581 case Attribute::Speculatable:
582 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000583 case Attribute::StackAlignment:
584 return bitc::ATTR_KIND_STACK_ALIGNMENT;
585 case Attribute::StackProtect:
586 return bitc::ATTR_KIND_STACK_PROTECT;
587 case Attribute::StackProtectReq:
588 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
589 case Attribute::StackProtectStrong:
590 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000591 case Attribute::SafeStack:
592 return bitc::ATTR_KIND_SAFESTACK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000593 case Attribute::StructRet:
594 return bitc::ATTR_KIND_STRUCT_RET;
595 case Attribute::SanitizeAddress:
596 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
597 case Attribute::SanitizeThread:
598 return bitc::ATTR_KIND_SANITIZE_THREAD;
599 case Attribute::SanitizeMemory:
600 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000601 case Attribute::SwiftError:
602 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000603 case Attribute::SwiftSelf:
604 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000605 case Attribute::UWTable:
606 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000607 case Attribute::WriteOnly:
608 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000609 case Attribute::ZExt:
610 return bitc::ATTR_KIND_Z_EXT;
611 case Attribute::EndAttrKinds:
612 llvm_unreachable("Can not encode end-attribute kinds marker.");
613 case Attribute::None:
614 llvm_unreachable("Can not encode none-attribute.");
615 }
616
617 llvm_unreachable("Trying to encode unknown attribute");
618}
619
Teresa Johnson37687f32016-04-23 04:30:47 +0000620void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000621 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
622 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000623 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000624
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000625 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000626
627 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000628 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
629 unsigned AttrListIndex = Pair.first;
630 AttributeSet AS = Pair.second;
631 Record.push_back(VE.getAttributeGroupID(Pair));
632 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000633
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000634 for (Attribute Attr : AS) {
635 if (Attr.isEnumAttribute()) {
636 Record.push_back(0);
637 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
638 } else if (Attr.isIntAttribute()) {
639 Record.push_back(1);
640 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
641 Record.push_back(Attr.getValueAsInt());
642 } else {
643 StringRef Kind = Attr.getKindAsString();
644 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000645
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000646 Record.push_back(Val.empty() ? 3 : 4);
647 Record.append(Kind.begin(), Kind.end());
648 Record.push_back(0);
649 if (!Val.empty()) {
650 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000651 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000652 }
653 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000654 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000655
656 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
657 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000658 }
659
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000660 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000661}
662
Teresa Johnson37687f32016-04-23 04:30:47 +0000663void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000664 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000665 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000666
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000667 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000668
669 SmallVector<uint64_t, 64> Record;
670 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000671 AttributeList AL = Attrs[i];
672 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
673 AttributeSet AS = AL.getAttributes(i);
674 if (AS.hasAttributes())
675 Record.push_back(VE.getAttributeGroupID({i, AS}));
676 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000677
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000678 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000679 Record.clear();
680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000681
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000682 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000683}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000684
685/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000686void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000687 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000688
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000689 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000690 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
David Blaikie7b028102015-02-25 00:51:52 +0000692 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000693
Chris Lattnerccee7062007-05-05 06:30:12 +0000694 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000695 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000696 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000697 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000698 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000699 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000700
Chris Lattnerccee7062007-05-05 06:30:12 +0000701 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000702 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000703 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
707
David Blaikie7ad9dc12017-01-04 22:36:33 +0000708 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000709
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000710 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000711 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000712 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
716
David Blaikie7ad9dc12017-01-04 22:36:33 +0000717 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000718
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000719 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000720 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000721 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
722 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000724 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000725
726 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000727 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000728 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000731 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
732
David Blaikie7ad9dc12017-01-04 22:36:33 +0000733 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000734
Chris Lattnerccee7062007-05-05 06:30:12 +0000735 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000736 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000737 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
740
David Blaikie7ad9dc12017-01-04 22:36:33 +0000741 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000743 // Emit an entry count so the reader can reserve space.
744 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000745 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000746 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000747
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000748 // Loop over all of the types, emitting each in turn.
749 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000750 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000751 int AbbrevToUse = 0;
752 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000753
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000754 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000755 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
756 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
757 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
758 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
759 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
760 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000761 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000762 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
763 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
764 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000765 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000766 case Type::IntegerTyID:
767 // INTEGER: [width]
768 Code = bitc::TYPE_CODE_INTEGER;
769 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
770 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000771 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000772 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000773 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000774 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000775 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000776 unsigned AddressSpace = PTy->getAddressSpace();
777 TypeVals.push_back(AddressSpace);
778 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000779 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000780 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000781 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000782 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000783 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000784 Code = bitc::TYPE_CODE_FUNCTION;
785 TypeVals.push_back(FT->isVarArg());
786 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000787 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
788 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000789 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000790 break;
791 }
792 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000793 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000794 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000795 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000796 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000797 for (StructType::element_iterator I = ST->element_begin(),
798 E = ST->element_end(); I != E; ++I)
799 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000800
Chris Lattner335d3992011-08-12 18:06:37 +0000801 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000802 Code = bitc::TYPE_CODE_STRUCT_ANON;
803 AbbrevToUse = StructAnonAbbrev;
804 } else {
805 if (ST->isOpaque()) {
806 Code = bitc::TYPE_CODE_OPAQUE;
807 } else {
808 Code = bitc::TYPE_CODE_STRUCT_NAMED;
809 AbbrevToUse = StructNamedAbbrev;
810 }
811
812 // Emit the name if it is present.
813 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000814 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000815 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000816 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000817 break;
818 }
819 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000820 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000821 // ARRAY: [numelts, eltty]
822 Code = bitc::TYPE_CODE_ARRAY;
823 TypeVals.push_back(AT->getNumElements());
824 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000825 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000826 break;
827 }
828 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000829 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000830 // VECTOR [numelts, eltty]
831 Code = bitc::TYPE_CODE_VECTOR;
832 TypeVals.push_back(VT->getNumElements());
833 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
834 break;
835 }
836 }
837
838 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000839 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000840 TypeVals.clear();
841 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000842
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000843 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000844}
845
Teresa Johnson5e22e442016-02-06 16:07:35 +0000846static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
847 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000848 case GlobalValue::ExternalLinkage:
849 return 0;
850 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000851 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000852 case GlobalValue::AppendingLinkage:
853 return 2;
854 case GlobalValue::InternalLinkage:
855 return 3;
856 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000857 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000858 case GlobalValue::ExternalWeakLinkage:
859 return 7;
860 case GlobalValue::CommonLinkage:
861 return 8;
862 case GlobalValue::PrivateLinkage:
863 return 9;
864 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000865 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000866 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000867 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000868 case GlobalValue::AvailableExternallyLinkage:
869 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000870 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000871 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000872}
873
Teresa Johnson5e22e442016-02-06 16:07:35 +0000874static unsigned getEncodedLinkage(const GlobalValue &GV) {
875 return getEncodedLinkage(GV.getLinkage());
876}
877
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000878// Decode the flags for GlobalValue in the summary
879static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
880 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000881
Mehdi Amini1380edf2017-02-03 07:41:43 +0000882 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000883 RawFlags |= (Flags.Live << 1);
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000884 // Linkage don't need to be remapped at that time for the summary. Any future
885 // change to the getEncodedLinkage() function will need to be taken into
886 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000887 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
888
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000889 return RawFlags;
890}
891
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000892static unsigned getEncodedVisibility(const GlobalValue &GV) {
893 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000894 case GlobalValue::DefaultVisibility: return 0;
895 case GlobalValue::HiddenVisibility: return 1;
896 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000897 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000898 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000899}
900
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000901static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
902 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000903 case GlobalValue::DefaultStorageClass: return 0;
904 case GlobalValue::DLLImportStorageClass: return 1;
905 case GlobalValue::DLLExportStorageClass: return 2;
906 }
907 llvm_unreachable("Invalid DLL storage class");
908}
909
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000910static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000911 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000912 case GlobalVariable::NotThreadLocal: return 0;
913 case GlobalVariable::GeneralDynamicTLSModel: return 1;
914 case GlobalVariable::LocalDynamicTLSModel: return 2;
915 case GlobalVariable::InitialExecTLSModel: return 3;
916 case GlobalVariable::LocalExecTLSModel: return 4;
917 }
918 llvm_unreachable("Invalid TLS model");
919}
920
David Majnemerdad0a642014-06-27 18:19:56 +0000921static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
922 switch (C.getSelectionKind()) {
923 case Comdat::Any:
924 return bitc::COMDAT_SELECTION_KIND_ANY;
925 case Comdat::ExactMatch:
926 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
927 case Comdat::Largest:
928 return bitc::COMDAT_SELECTION_KIND_LARGEST;
929 case Comdat::NoDuplicates:
930 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
931 case Comdat::SameSize:
932 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
933 }
934 llvm_unreachable("Invalid selection kind");
935}
936
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000937static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
938 switch (GV.getUnnamedAddr()) {
939 case GlobalValue::UnnamedAddr::None: return 0;
940 case GlobalValue::UnnamedAddr::Local: return 2;
941 case GlobalValue::UnnamedAddr::Global: return 1;
942 }
943 llvm_unreachable("Invalid unnamed_addr");
944}
945
Teresa Johnson37687f32016-04-23 04:30:47 +0000946void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +0000947 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +0000948 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000949 // COMDAT: [strtab offset, strtab size, selection_kind]
950 Vals.push_back(StrtabBuilder.add(C->getName()));
951 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +0000952 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000953 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +0000954 Vals.clear();
955 }
956}
957
Teresa Johnsonff642b92015-09-17 20:12:00 +0000958/// Write a record that will eventually hold the word offset of the
959/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +0000960/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000961void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +0000962 // Write a placeholder value in for the offset of the real VST,
963 // which is written after the function blocks so that it can include
964 // the offset of each function. The placeholder offset will be
965 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000966 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +0000967 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
968 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
969 // hold the real VST offset. Must use fixed instead of VBR as we don't
970 // know how many VBR chunks to reserve ahead of time.
971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000972 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +0000973
974 // Emit the placeholder
975 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000976 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +0000977
Teresa Johnson37687f32016-04-23 04:30:47 +0000978 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +0000979 // patched when the real VST is written. We can simply subtract the 32-bit
980 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000981 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +0000982}
983
Teresa Johnsone1164de2016-02-10 21:55:02 +0000984enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
985
986/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +0000987static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +0000988 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +0000989 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +0000990 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +0000991 isChar6 = BitCodeAbbrevOp::isChar6(C);
992 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +0000993 // don't bother scanning the rest.
994 return SE_Fixed8;
995 }
996 if (isChar6)
997 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +0000998 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +0000999}
1000
Teresa Johnsonff642b92015-09-17 20:12:00 +00001001/// Emit top-level description of module, including target triple, inline asm,
1002/// descriptors for global variables, and function prototype info.
1003/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001004void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001005 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001006 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001007 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001008 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001009 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001010 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001011 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001012 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001013 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001014 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001015
Gordon Henriksend930f912008-08-17 18:44:35 +00001016 // Emit information about sections and GC, computing how many there are. Also
1017 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001018 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001019 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001020 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001021 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001022 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001023 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001024 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001025 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001026 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001027 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001028 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001029 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001030 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001031 Entry = SectionMap.size();
1032 }
1033 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001034 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001035 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001036 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1037 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001038 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001039 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001040 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001041 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001042 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001043 Entry = SectionMap.size();
1044 }
1045 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001046 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001047 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001048 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001049 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001050 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1051 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001052 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001053 }
1054 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001055 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001056
Chris Lattner4b00d922007-04-23 16:04:05 +00001057 // Emit abbrev for globals, now that we know # sections and max alignment.
1058 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001059 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001060 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001061 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001062 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001066 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1068 //| explicitType << 1
1069 //| constant
1070 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1071 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1072 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001073 Abbv->Add(BitCodeAbbrevOp(0));
1074 else {
1075 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001077 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001078 }
1079 if (SectionMap.empty()) // Section.
1080 Abbv->Add(BitCodeAbbrevOp(0));
1081 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001083 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001084 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001085 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001086 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001087
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001088 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001089 // Emit the module's source file name.
1090 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001091 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001092 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1093 if (Bits == SE_Char6)
1094 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1095 else if (Bits == SE_Fixed7)
1096 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1097
1098 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1099 auto Abbv = std::make_shared<BitCodeAbbrev>();
1100 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1102 Abbv->Add(AbbrevOpToUse);
1103 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1104
1105 for (const auto P : M.getSourceFileName())
1106 Vals.push_back((unsigned char)P);
1107
1108 // Emit the finished record.
1109 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1110 Vals.clear();
1111 }
1112
1113 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001114 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001115 unsigned AbbrevToUse = 0;
1116
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001117 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001118 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001119 // unnamed_addr, externally_initialized, dllstorageclass,
Javed Absarf3d79042017-05-11 12:28:08 +00001120 // comdat, attributes]
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001121 Vals.push_back(StrtabBuilder.add(GV.getName()));
1122 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001123 Vals.push_back(VE.getTypeID(GV.getValueType()));
1124 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001125 Vals.push_back(GV.isDeclaration() ? 0 :
1126 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001127 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001128 Vals.push_back(Log2_32(GV.getAlignment())+1);
1129 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1130 if (GV.isThreadLocal() ||
1131 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001132 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1133 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001134 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001135 GV.hasComdat() ||
1136 GV.hasAttributes()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001137 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001138 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001139 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001140 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001141 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001142 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001143
1144 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1145 Vals.push_back(VE.getAttributeListID(AL));
Chris Lattner4b00d922007-04-23 16:04:05 +00001146 } else {
1147 AbbrevToUse = SimpleGVarAbbrev;
1148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001149
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001150 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001151 Vals.clear();
1152 }
1153
1154 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001155 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001156 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1157 // linkage, paramattrs, alignment, section, visibility, gc,
1158 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1159 // prefixdata, personalityfn]
1160 Vals.push_back(StrtabBuilder.add(F.getName()));
1161 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001162 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001163 Vals.push_back(F.getCallingConv());
1164 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001165 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001166 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001167 Vals.push_back(Log2_32(F.getAlignment())+1);
1168 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001169 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001170 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001171 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001172 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1173 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001174 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001175 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001176 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1177 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001178 Vals.push_back(
1179 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001180
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001181 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001182 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001183 Vals.clear();
1184 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001185
Chris Lattner44c17072007-04-26 02:46:40 +00001186 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001187 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001188 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1189 // visibility, dllstorageclass, threadlocal, unnamed_addr]
1190 Vals.push_back(StrtabBuilder.add(A.getName()));
1191 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001192 Vals.push_back(VE.getTypeID(A.getValueType()));
1193 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001194 Vals.push_back(VE.getValueID(A.getAliasee()));
1195 Vals.push_back(getEncodedLinkage(A));
1196 Vals.push_back(getEncodedVisibility(A));
1197 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001198 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001199 Vals.push_back(getEncodedUnnamedAddr(A));
Chris Lattner44c17072007-04-26 02:46:40 +00001200 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001201 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001202 Vals.clear();
1203 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001204
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001205 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001206 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001207 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1208 // val#, linkage, visibility]
1209 Vals.push_back(StrtabBuilder.add(I.getName()));
1210 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001211 Vals.push_back(VE.getTypeID(I.getValueType()));
1212 Vals.push_back(I.getType()->getAddressSpace());
1213 Vals.push_back(VE.getValueID(I.getResolver()));
1214 Vals.push_back(getEncodedLinkage(I));
1215 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001216 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001217 Vals.clear();
1218 }
1219
Teresa Johnson37687f32016-04-23 04:30:47 +00001220 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001221}
1222
Teresa Johnson37687f32016-04-23 04:30:47 +00001223static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001224 uint64_t Flags = 0;
1225
Sanjay Patelc00017d2014-10-15 17:45:13 +00001226 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001227 if (OBO->hasNoSignedWrap())
1228 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1229 if (OBO->hasNoUnsignedWrap())
1230 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001231 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001232 if (PEO->isExact())
1233 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001234 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001235 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001236 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001237 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001238 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001239 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001240 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001241 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001242 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001243 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001244 Flags |= FastMathFlags::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001245 if (FPMO->hasAllowContract())
1246 Flags |= FastMathFlags::AllowContract;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001247 }
1248
1249 return Flags;
1250}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001251
Teresa Johnson37687f32016-04-23 04:30:47 +00001252void ModuleBitcodeWriter::writeValueAsMetadata(
1253 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001254 // Mimic an MDNode with a value as one operand.
1255 Value *V = MD->getValue();
1256 Record.push_back(VE.getTypeID(V->getType()));
1257 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001258 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001259 Record.clear();
1260}
1261
Teresa Johnson37687f32016-04-23 04:30:47 +00001262void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1263 SmallVectorImpl<uint64_t> &Record,
1264 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001265 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001266 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001267 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1268 "Unexpected function-local metadata");
1269 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001270 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001271 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1272 : bitc::METADATA_NODE,
1273 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001274 Record.clear();
1275}
Devang Patele059ba6e2009-07-23 01:07:34 +00001276
Teresa Johnson37687f32016-04-23 04:30:47 +00001277unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001278 // Assume the column is usually under 128, and always output the inlined-at
1279 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001280 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001281 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1282 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1284 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001287 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001288}
1289
Teresa Johnson37687f32016-04-23 04:30:47 +00001290void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1291 SmallVectorImpl<uint64_t> &Record,
1292 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001293 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001294 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001295
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001296 Record.push_back(N->isDistinct());
1297 Record.push_back(N->getLine());
1298 Record.push_back(N->getColumn());
1299 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001300 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001301
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001302 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001303 Record.clear();
1304}
1305
Teresa Johnson37687f32016-04-23 04:30:47 +00001306unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001307 // Assume the column is usually under 128, and always output the inlined-at
1308 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001309 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001310 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1315 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001317 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001318}
1319
Teresa Johnson37687f32016-04-23 04:30:47 +00001320void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1321 SmallVectorImpl<uint64_t> &Record,
1322 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001323 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001324 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001325
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001326 Record.push_back(N->isDistinct());
1327 Record.push_back(N->getTag());
1328 Record.push_back(0); // Per-tag version field; unused for now.
1329
1330 for (auto &I : N->operands())
1331 Record.push_back(VE.getMetadataOrNullID(I));
1332
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001333 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001334 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001335}
1336
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001337static uint64_t rotateSign(int64_t I) {
1338 uint64_t U = I;
1339 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001340}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001341
Teresa Johnson37687f32016-04-23 04:30:47 +00001342void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1343 SmallVectorImpl<uint64_t> &Record,
1344 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001345 Record.push_back(N->isDistinct());
1346 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001347 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001348
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001349 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001350 Record.clear();
1351}
1352
Teresa Johnson37687f32016-04-23 04:30:47 +00001353void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1354 SmallVectorImpl<uint64_t> &Record,
1355 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001356 Record.push_back(N->isDistinct());
1357 Record.push_back(rotateSign(N->getValue()));
1358 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1359
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001360 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001361 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001362}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001363
Teresa Johnson37687f32016-04-23 04:30:47 +00001364void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1365 SmallVectorImpl<uint64_t> &Record,
1366 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001367 Record.push_back(N->isDistinct());
1368 Record.push_back(N->getTag());
1369 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1370 Record.push_back(N->getSizeInBits());
1371 Record.push_back(N->getAlignInBits());
1372 Record.push_back(N->getEncoding());
1373
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001374 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001375 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001376}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001377
Teresa Johnson37687f32016-04-23 04:30:47 +00001378void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1379 SmallVectorImpl<uint64_t> &Record,
1380 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001381 Record.push_back(N->isDistinct());
1382 Record.push_back(N->getTag());
1383 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1384 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1385 Record.push_back(N->getLine());
1386 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001387 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001388 Record.push_back(N->getSizeInBits());
1389 Record.push_back(N->getAlignInBits());
1390 Record.push_back(N->getOffsetInBits());
1391 Record.push_back(N->getFlags());
1392 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1393
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001394 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1395 // that there is no DWARF address space associated with DIDerivedType.
1396 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1397 Record.push_back(*DWARFAddressSpace + 1);
1398 else
1399 Record.push_back(0);
1400
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001401 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001402 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001403}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001404
Teresa Johnson37687f32016-04-23 04:30:47 +00001405void ModuleBitcodeWriter::writeDICompositeType(
1406 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1407 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001408 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001409 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001410 Record.push_back(N->getTag());
1411 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1412 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1413 Record.push_back(N->getLine());
1414 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1415 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1416 Record.push_back(N->getSizeInBits());
1417 Record.push_back(N->getAlignInBits());
1418 Record.push_back(N->getOffsetInBits());
1419 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001420 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001421 Record.push_back(N->getRuntimeLang());
1422 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001423 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001424 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1425
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001426 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001427 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001428}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001429
Teresa Johnson37687f32016-04-23 04:30:47 +00001430void ModuleBitcodeWriter::writeDISubroutineType(
1431 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1432 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001433 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001434 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001435 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001436 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001437 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001438
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001439 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001440 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001441}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001442
Teresa Johnson37687f32016-04-23 04:30:47 +00001443void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1444 SmallVectorImpl<uint64_t> &Record,
1445 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001446 Record.push_back(N->isDistinct());
1447 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1448 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001449 Record.push_back(N->getChecksumKind());
1450 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001451
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001452 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001453 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001454}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001455
Teresa Johnson37687f32016-04-23 04:30:47 +00001456void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1457 SmallVectorImpl<uint64_t> &Record,
1458 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001459 assert(N->isDistinct() && "Expected distinct compile units");
1460 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001461 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001462 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001463 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1464 Record.push_back(N->isOptimized());
1465 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1466 Record.push_back(N->getRuntimeVersion());
1467 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1468 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001469 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1470 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001471 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001472 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1473 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001474 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001475 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001476 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001477 Record.push_back(N->getDebugInfoForProfiling());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001478
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001479 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001480 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001481}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001482
Teresa Johnson37687f32016-04-23 04:30:47 +00001483void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1484 SmallVectorImpl<uint64_t> &Record,
1485 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001486 uint64_t HasUnitFlag = 1 << 1;
1487 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001488 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1489 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1490 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1491 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1492 Record.push_back(N->getLine());
1493 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1494 Record.push_back(N->isLocalToUnit());
1495 Record.push_back(N->isDefinition());
1496 Record.push_back(N->getScopeLine());
1497 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1498 Record.push_back(N->getVirtuality());
1499 Record.push_back(N->getVirtualIndex());
1500 Record.push_back(N->getFlags());
1501 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001502 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001503 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001504 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001505 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001506 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001507 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001508
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001509 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001510 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001511}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001512
Teresa Johnson37687f32016-04-23 04:30:47 +00001513void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1514 SmallVectorImpl<uint64_t> &Record,
1515 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001516 Record.push_back(N->isDistinct());
1517 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1518 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1519 Record.push_back(N->getLine());
1520 Record.push_back(N->getColumn());
1521
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001522 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001523 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001524}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001525
Teresa Johnson37687f32016-04-23 04:30:47 +00001526void ModuleBitcodeWriter::writeDILexicalBlockFile(
1527 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1528 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001529 Record.push_back(N->isDistinct());
1530 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1531 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1532 Record.push_back(N->getDiscriminator());
1533
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001534 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001535 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001536}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001537
Teresa Johnson37687f32016-04-23 04:30:47 +00001538void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1539 SmallVectorImpl<uint64_t> &Record,
1540 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001541 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001542 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001543 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001544
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001545 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001546 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001547}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001548
Teresa Johnson37687f32016-04-23 04:30:47 +00001549void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1550 SmallVectorImpl<uint64_t> &Record,
1551 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001552 Record.push_back(N->isDistinct());
1553 Record.push_back(N->getMacinfoType());
1554 Record.push_back(N->getLine());
1555 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1556 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1557
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001558 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001559 Record.clear();
1560}
1561
Teresa Johnson37687f32016-04-23 04:30:47 +00001562void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1563 SmallVectorImpl<uint64_t> &Record,
1564 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001565 Record.push_back(N->isDistinct());
1566 Record.push_back(N->getMacinfoType());
1567 Record.push_back(N->getLine());
1568 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1569 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1570
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001571 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001572 Record.clear();
1573}
1574
Teresa Johnson37687f32016-04-23 04:30:47 +00001575void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1576 SmallVectorImpl<uint64_t> &Record,
1577 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001578 Record.push_back(N->isDistinct());
1579 for (auto &I : N->operands())
1580 Record.push_back(VE.getMetadataOrNullID(I));
1581
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001582 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001583 Record.clear();
1584}
1585
Teresa Johnson37687f32016-04-23 04:30:47 +00001586void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1587 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1588 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001589 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001590 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1591 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1592
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001593 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001594 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001595}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001596
Teresa Johnson37687f32016-04-23 04:30:47 +00001597void ModuleBitcodeWriter::writeDITemplateValueParameter(
1598 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1599 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001600 Record.push_back(N->isDistinct());
1601 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001602 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1603 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1604 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1605
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001606 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001607 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001608}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001609
Teresa Johnson37687f32016-04-23 04:30:47 +00001610void ModuleBitcodeWriter::writeDIGlobalVariable(
1611 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1612 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001613 const uint64_t Version = 1 << 1;
1614 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001615 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1616 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1618 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1619 Record.push_back(N->getLine());
1620 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1621 Record.push_back(N->isLocalToUnit());
1622 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001623 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001624 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001625 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001626
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001627 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001628 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001629}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001630
Teresa Johnson37687f32016-04-23 04:30:47 +00001631void ModuleBitcodeWriter::writeDILocalVariable(
1632 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1633 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001634 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001635 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001636 // 1) Record has no artificial tag (Record[1]),
1637 // has no obsolete inlinedAt field (Record[9]).
1638 // In this case Record size will be 8, HasAlignment flag is false.
1639 // 2) Record has artificial tag (Record[1]),
1640 // has no obsolete inlignedAt field (Record[9]).
1641 // In this case Record size will be 9, HasAlignment flag is false.
1642 // 3) Record has both artificial tag (Record[1]) and
1643 // obsolete inlignedAt field (Record[9]).
1644 // In this case Record size will be 10, HasAlignment flag is false.
1645 // 4) Record has neither artificial tag, nor inlignedAt field, but
1646 // HasAlignment flag is true and Record[8] contains alignment value.
1647 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001648 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001649 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1650 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1651 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1652 Record.push_back(N->getLine());
1653 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1654 Record.push_back(N->getArg());
1655 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001656 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001657
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001658 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001659 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001660}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001661
Teresa Johnson37687f32016-04-23 04:30:47 +00001662void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1663 SmallVectorImpl<uint64_t> &Record,
1664 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001665 Record.reserve(N->getElements().size() + 1);
Adrian Prantl6825fb62017-04-18 01:21:53 +00001666 const uint64_t Version = 2 << 1;
1667 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001668 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001669
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001670 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001671 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001672}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001673
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001674void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1675 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1676 unsigned Abbrev) {
1677 Record.push_back(N->isDistinct());
1678 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1679 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1680
1681 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1682 Record.clear();
1683}
1684
Teresa Johnson37687f32016-04-23 04:30:47 +00001685void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1686 SmallVectorImpl<uint64_t> &Record,
1687 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001688 Record.push_back(N->isDistinct());
1689 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1690 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1691 Record.push_back(N->getLine());
1692 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1693 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1694 Record.push_back(N->getAttributes());
1695 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1696
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001697 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001698 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001699}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001700
Teresa Johnson37687f32016-04-23 04:30:47 +00001701void ModuleBitcodeWriter::writeDIImportedEntity(
1702 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1703 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001704 Record.push_back(N->isDistinct());
1705 Record.push_back(N->getTag());
1706 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1707 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1708 Record.push_back(N->getLine());
1709 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1710
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001711 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001712 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001713}
1714
Teresa Johnson37687f32016-04-23 04:30:47 +00001715unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001716 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001717 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001720 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001721}
1722
Teresa Johnson37687f32016-04-23 04:30:47 +00001723void ModuleBitcodeWriter::writeNamedMetadata(
1724 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001725 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001726 return;
1727
Teresa Johnson37687f32016-04-23 04:30:47 +00001728 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001729 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001730 // Write name.
1731 StringRef Str = NMD.getName();
1732 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001733 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001734 Record.clear();
1735
1736 // Write named metadata operands.
1737 for (const MDNode *N : NMD.operands())
1738 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001739 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001740 Record.clear();
1741 }
1742}
1743
Teresa Johnson37687f32016-04-23 04:30:47 +00001744unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001745 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001746 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1747 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1748 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1749 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001750 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001751}
1752
1753/// Write out a record for MDString.
1754///
1755/// All the metadata strings in a metadata block are emitted in a single
1756/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001757void ModuleBitcodeWriter::writeMetadataStrings(
1758 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001759 if (Strings.empty())
1760 return;
1761
1762 // Start the record with the number of strings.
1763 Record.push_back(bitc::METADATA_STRINGS);
1764 Record.push_back(Strings.size());
1765
1766 // Emit the sizes of the strings in the blob.
1767 SmallString<256> Blob;
1768 {
1769 BitstreamWriter W(Blob);
1770 for (const Metadata *MD : Strings)
1771 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1772 W.FlushToWord();
1773 }
1774
1775 // Add the offset to the strings to the record.
1776 Record.push_back(Blob.size());
1777
1778 // Add the strings to the blob.
1779 for (const Metadata *MD : Strings)
1780 Blob.append(cast<MDString>(MD)->getString());
1781
1782 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001783 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001784 Record.clear();
1785}
1786
Mehdi Aminie98f9252016-12-28 22:30:28 +00001787// Generates an enum to use as an index in the Abbrev array of Metadata record.
1788enum MetadataAbbrev : unsigned {
1789#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1790#include "llvm/IR/Metadata.def"
1791 LastPlusOne
1792};
1793
Teresa Johnson37687f32016-04-23 04:30:47 +00001794void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001795 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1796 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001797 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001798 return;
1799
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001800 // Initialize MDNode abbreviations.
1801#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1802#include "llvm/IR/Metadata.def"
1803
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001804 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001805 if (IndexPos)
1806 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001807 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001808 assert(N->isResolved() && "Expected forward references to be resolved");
1809
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001810 switch (N->getMetadataID()) {
1811 default:
1812 llvm_unreachable("Invalid MDNode subclass");
1813#define HANDLE_MDNODE_LEAF(CLASS) \
1814 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001815 if (MDAbbrevs) \
1816 write##CLASS(cast<CLASS>(N), Record, \
1817 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1818 else \
1819 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001820 continue;
1821#include "llvm/IR/Metadata.def"
1822 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001823 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001824 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001825 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001826}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001827
Teresa Johnson37687f32016-04-23 04:30:47 +00001828void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001829 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001830 return;
1831
Mehdi Aminie98f9252016-12-28 22:30:28 +00001832 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001833 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001834
1835 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1836 // block and load any metadata.
1837 std::vector<unsigned> MDAbbrevs;
1838
1839 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1840 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1841 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1842 createGenericDINodeAbbrev();
1843
David Blaikie7ad9dc12017-01-04 22:36:33 +00001844 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001845 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001846 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1847 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001848 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001849
David Blaikie7ad9dc12017-01-04 22:36:33 +00001850 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001851 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1852 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1853 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001854 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001855
1856 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001857 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00001858
1859 // We only emit an index for the metadata record if we have more than a given
1860 // (naive) threshold of metadatas, otherwise it is not worth it.
1861 if (VE.getNonMDStrings().size() > IndexThreshold) {
1862 // Write a placeholder value in for the offset of the metadata index,
1863 // which is written after the records, so that it can include
1864 // the offset of each entry. The placeholder offset will be
1865 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00001866 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00001867 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1868 }
1869
1870 // Compute and save the bit offset to the current position, which will be
1871 // patched when we emit the index later. We can simply subtract the 64-bit
1872 // fixed size from the current bit number to get the location to backpatch.
1873 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1874
1875 // This index will contain the bitpos for each individual record.
1876 std::vector<uint64_t> IndexPos;
1877 IndexPos.reserve(VE.getNonMDStrings().size());
1878
1879 // Write all the records
1880 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1881
1882 if (VE.getNonMDStrings().size() > IndexThreshold) {
1883 // Now that we have emitted all the records we will emit the index. But
1884 // first
1885 // backpatch the forward reference so that the reader can skip the records
1886 // efficiently.
1887 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1888 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1889
1890 // Delta encode the index.
1891 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1892 for (auto &Elt : IndexPos) {
1893 auto EltDelta = Elt - PreviousValue;
1894 PreviousValue = Elt;
1895 Elt = EltDelta;
1896 }
1897 // Emit the index record.
1898 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1899 IndexPos.clear();
1900 }
1901
1902 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00001903 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00001904
1905 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1906 SmallVector<uint64_t, 4> Record;
1907 Record.push_back(VE.getValueID(&GO));
1908 pushGlobalMetadataAttachment(Record, GO);
1909 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1910 };
1911 for (const Function &F : M)
1912 if (F.isDeclaration() && F.hasMetadata())
1913 AddDeclAttachedMetadata(F);
1914 // FIXME: Only store metadata for declarations here, and move data for global
1915 // variable definitions to a separate block (PR28134).
1916 for (const GlobalVariable &GV : M.globals())
1917 if (GV.hasMetadata())
1918 AddDeclAttachedMetadata(GV);
1919
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001920 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001921}
1922
Teresa Johnson37687f32016-04-23 04:30:47 +00001923void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00001924 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001925 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001926
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001927 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001928 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001929 writeMetadataStrings(VE.getMDStrings(), Record);
1930 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001931 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00001932}
1933
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001934void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1935 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1936 // [n x [id, mdnode]]
1937 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1938 GO.getAllMetadata(MDs);
1939 for (const auto &I : MDs) {
1940 Record.push_back(I.first);
1941 Record.push_back(VE.getMetadataID(I.second));
1942 }
1943}
1944
1945void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001946 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00001947
Devang Patelaf206b82009-09-18 19:26:43 +00001948 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001949
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001950 if (F.hasMetadata()) {
1951 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001952 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001953 Record.clear();
1954 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001955
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001956 // Write metadata attachments
1957 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1958 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001959 for (const BasicBlock &BB : F)
1960 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00001961 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001962 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001963
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001964 // If no metadata, ignore instruction.
1965 if (MDs.empty()) continue;
1966
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001967 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001968
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001969 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1970 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001971 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00001972 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001973 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001974 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00001975 }
1976
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001977 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001978}
1979
Peter Collingbourne21521892016-06-21 23:42:48 +00001980void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00001981 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001982
Devang Patelaf206b82009-09-18 19:26:43 +00001983 // Write metadata kinds
1984 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00001985 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001986 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001987
Dan Gohman43aa8f02010-07-20 21:42:28 +00001988 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00001989
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001990 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001991
Dan Gohman43aa8f02010-07-20 21:42:28 +00001992 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00001993 Record.push_back(MDKindID);
1994 StringRef KName = Names[MDKindID];
1995 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001996
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001997 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00001998 Record.clear();
1999 }
2000
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002001 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002002}
2003
Teresa Johnson37687f32016-04-23 04:30:47 +00002004void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002005 // Write metadata kinds
2006 //
2007 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2008 //
2009 // OPERAND_BUNDLE_TAG - [strchr x N]
2010
2011 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002012 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002013
2014 if (Tags.empty())
2015 return;
2016
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002017 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002018
2019 SmallVector<uint64_t, 64> Record;
2020
2021 for (auto Tag : Tags) {
2022 Record.append(Tag.begin(), Tag.end());
2023
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002024 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002025 Record.clear();
2026 }
2027
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002028 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002029}
2030
Jan Wen Voungafaced02012-10-11 20:20:40 +00002031static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2032 if ((int64_t)V >= 0)
2033 Vals.push_back(V << 1);
2034 else
2035 Vals.push_back((-V << 1) | 1);
2036}
2037
Teresa Johnson37687f32016-04-23 04:30:47 +00002038void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2039 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002040 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002041
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002042 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002043
2044 unsigned AggregateAbbrev = 0;
2045 unsigned String8Abbrev = 0;
2046 unsigned CString7Abbrev = 0;
2047 unsigned CString6Abbrev = 0;
2048 // If this is a constant pool for the module, emit module-specific abbrevs.
2049 if (isGlobal) {
2050 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002051 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002052 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002055 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002056
2057 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002058 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002059 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002062 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002063 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002064 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002065 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002068 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002069 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002070 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002071 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2072 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002074 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002075 }
2076
Devang Patel8cca7b42009-08-04 05:01:35 +00002077 SmallVector<uint64_t, 64> Record;
2078
2079 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002080 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002081 for (unsigned i = FirstVal; i != LastVal; ++i) {
2082 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002083 // If we need to switch types, do so now.
2084 if (V->getType() != LastTy) {
2085 LastTy = V->getType();
2086 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002087 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2088 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002089 Record.clear();
2090 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002091
Chris Lattner52523562007-04-24 00:16:04 +00002092 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002093 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002094 unsigned(IA->isAlignStack()) << 1 |
2095 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002096
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002097 // Add the asm string.
2098 const std::string &AsmStr = IA->getAsmString();
2099 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002100 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002102 // Add the constraint string.
2103 const std::string &ConstraintStr = IA->getConstraintString();
2104 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002105 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002106 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002107 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002108 continue;
2109 }
2110 const Constant *C = cast<Constant>(V);
2111 unsigned Code = -1U;
2112 unsigned AbbrevToUse = 0;
2113 if (C->isNullValue()) {
2114 Code = bitc::CST_CODE_NULL;
2115 } else if (isa<UndefValue>(C)) {
2116 Code = bitc::CST_CODE_UNDEF;
2117 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002118 if (IV->getBitWidth() <= 64) {
2119 uint64_t V = IV->getSExtValue();
2120 emitSignedInt64(Record, V);
2121 Code = bitc::CST_CODE_INTEGER;
2122 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2123 } else { // Wide integers, > 64 bits in size.
2124 // We have an arbitrary precision integer value to write whose
2125 // bit width is > 64. However, in canonical unsigned integer
2126 // format it is likely that the high bits are going to be zero.
2127 // So, we only write the number of active words.
2128 unsigned NWords = IV->getValue().getActiveWords();
2129 const uint64_t *RawWords = IV->getValue().getRawData();
2130 for (unsigned i = 0; i != NWords; ++i) {
2131 emitSignedInt64(Record, RawWords[i]);
2132 }
2133 Code = bitc::CST_CODE_WIDE_INTEGER;
2134 }
Chris Lattner52523562007-04-24 00:16:04 +00002135 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2136 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002137 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002138 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002139 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002140 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002141 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002142 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002143 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002144 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002145 Record.push_back((p[1] << 48) | (p[0] >> 16));
2146 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002147 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002148 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002149 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002150 Record.push_back(p[0]);
2151 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002152 } else {
2153 assert (0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002154 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002155 } else if (isa<ConstantDataSequential>(C) &&
2156 cast<ConstantDataSequential>(C)->isString()) {
2157 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2158 // Emit constant strings specially.
2159 unsigned NumElts = Str->getNumElements();
2160 // If this is a null-terminated string, use the denser CSTRING encoding.
2161 if (Str->isCString()) {
2162 Code = bitc::CST_CODE_CSTRING;
2163 --NumElts; // Don't encode the null, which isn't allowed by char6.
2164 } else {
2165 Code = bitc::CST_CODE_STRING;
2166 AbbrevToUse = String8Abbrev;
2167 }
2168 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2169 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2170 for (unsigned i = 0; i != NumElts; ++i) {
2171 unsigned char V = Str->getElementAsInteger(i);
2172 Record.push_back(V);
2173 isCStr7 &= (V & 128) == 0;
2174 if (isCStrChar6)
2175 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2176 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002177
Chris Lattner372dd1e2012-01-30 00:51:16 +00002178 if (isCStrChar6)
2179 AbbrevToUse = CString6Abbrev;
2180 else if (isCStr7)
2181 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002182 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002183 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002184 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002185 Type *EltTy = CDS->getType()->getElementType();
2186 if (isa<IntegerType>(EltTy)) {
2187 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2188 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002189 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002190 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2191 Record.push_back(
2192 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002193 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002194 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002195 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002196 for (const Value *Op : C->operands())
2197 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002198 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002199 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002200 switch (CE->getOpcode()) {
2201 default:
2202 if (Instruction::isCast(CE->getOpcode())) {
2203 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002204 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002205 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2206 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002207 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002208 } else {
2209 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2210 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002211 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002212 Record.push_back(VE.getValueID(C->getOperand(0)));
2213 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002214 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002215 if (Flags != 0)
2216 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002217 }
2218 break;
David Blaikieb9263572015-03-13 21:03:36 +00002219 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002220 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002221 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002222 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002223 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2224 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2225 Record.push_back((*Idx << 1) | GO->isInBounds());
2226 } else if (GO->isInBounds())
2227 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002228 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2229 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2230 Record.push_back(VE.getValueID(C->getOperand(i)));
2231 }
2232 break;
David Blaikieb9263572015-03-13 21:03:36 +00002233 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002234 case Instruction::Select:
2235 Code = bitc::CST_CODE_CE_SELECT;
2236 Record.push_back(VE.getValueID(C->getOperand(0)));
2237 Record.push_back(VE.getValueID(C->getOperand(1)));
2238 Record.push_back(VE.getValueID(C->getOperand(2)));
2239 break;
2240 case Instruction::ExtractElement:
2241 Code = bitc::CST_CODE_CE_EXTRACTELT;
2242 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2243 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002244 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002245 Record.push_back(VE.getValueID(C->getOperand(1)));
2246 break;
2247 case Instruction::InsertElement:
2248 Code = bitc::CST_CODE_CE_INSERTELT;
2249 Record.push_back(VE.getValueID(C->getOperand(0)));
2250 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002251 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002252 Record.push_back(VE.getValueID(C->getOperand(2)));
2253 break;
2254 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002255 // If the return type and argument types are the same, this is a
2256 // standard shufflevector instruction. If the types are different,
2257 // then the shuffle is widening or truncating the input vectors, and
2258 // the argument type must also be encoded.
2259 if (C->getType() == C->getOperand(0)->getType()) {
2260 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2261 } else {
2262 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2263 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2264 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002265 Record.push_back(VE.getValueID(C->getOperand(0)));
2266 Record.push_back(VE.getValueID(C->getOperand(1)));
2267 Record.push_back(VE.getValueID(C->getOperand(2)));
2268 break;
2269 case Instruction::ICmp:
2270 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002271 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002272 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2273 Record.push_back(VE.getValueID(C->getOperand(0)));
2274 Record.push_back(VE.getValueID(C->getOperand(1)));
2275 Record.push_back(CE->getPredicate());
2276 break;
2277 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002278 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002279 Code = bitc::CST_CODE_BLOCKADDRESS;
2280 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2281 Record.push_back(VE.getValueID(BA->getFunction()));
2282 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002283 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002284#ifndef NDEBUG
2285 C->dump();
2286#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002287 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002288 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002289 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002290 Record.clear();
2291 }
2292
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002293 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002294}
2295
Teresa Johnson37687f32016-04-23 04:30:47 +00002296void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002297 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002298
Chris Lattner52523562007-04-24 00:16:04 +00002299 // Find the first constant to emit, which is the first non-globalvalue value.
2300 // We know globalvalues have been emitted by WriteModuleInfo.
2301 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2302 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002303 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002304 return;
2305 }
2306 }
2307}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002308
Teresa Johnson37687f32016-04-23 04:30:47 +00002309/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002310/// many values, because we need to know what type to create for forward
2311/// references. However, most operands are not forward references, so this type
2312/// field is not needed.
2313///
2314/// This function adds V's value ID to Vals. If the value ID is higher than the
2315/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002316/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002317bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2318 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002319 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002320 // Make encoding relative to the InstID.
2321 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002322 if (ValID >= InstID) {
2323 Vals.push_back(VE.getTypeID(V->getType()));
2324 return true;
2325 }
2326 return false;
2327}
2328
Teresa Johnson37687f32016-04-23 04:30:47 +00002329void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2330 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002331 SmallVector<unsigned, 64> Record;
2332 LLVMContext &C = CS.getInstruction()->getContext();
2333
2334 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002335 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002336 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002337
2338 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002339 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002340
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002341 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002342 Record.clear();
2343 }
2344}
2345
Teresa Johnson37687f32016-04-23 04:30:47 +00002346/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002347/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002348void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2349 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002350 unsigned ValID = VE.getValueID(V);
2351 Vals.push_back(InstID - ValID);
2352}
2353
Teresa Johnson37687f32016-04-23 04:30:47 +00002354void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2355 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002356 unsigned ValID = VE.getValueID(V);
2357 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2358 emitSignedInt64(Vals, diff);
2359}
2360
Chris Lattnere6e364c2007-04-26 05:53:54 +00002361/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002362void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2363 unsigned InstID,
2364 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002365 unsigned Code = 0;
2366 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002367 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002368 switch (I.getOpcode()) {
2369 default:
2370 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002371 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002372 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002373 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002374 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002375 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002376 } else {
2377 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002378 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002379 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002380 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002381 pushValue(I.getOperand(1), InstID, Vals);
2382 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2383 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002384 if (Flags != 0) {
2385 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2386 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2387 Vals.push_back(Flags);
2388 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002389 }
2390 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002391
David Blaikieb5b5efd2015-02-25 01:08:52 +00002392 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002393 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002394 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2395 auto &GEPInst = cast<GetElementPtrInst>(I);
2396 Vals.push_back(GEPInst.isInBounds());
2397 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002398 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002399 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002400 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002401 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002402 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002403 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002404 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002405 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002406 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002407 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002408 }
2409 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002410 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002411 pushValueAndType(I.getOperand(0), InstID, Vals);
2412 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002413 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002414 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002415 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002416 }
Chris Lattner0a603252007-05-01 02:13:26 +00002417 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002418 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002419 pushValueAndType(I.getOperand(1), InstID, Vals);
2420 pushValue(I.getOperand(2), InstID, Vals);
2421 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002422 break;
2423 case Instruction::ExtractElement:
2424 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002425 pushValueAndType(I.getOperand(0), InstID, Vals);
2426 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002427 break;
2428 case Instruction::InsertElement:
2429 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002430 pushValueAndType(I.getOperand(0), InstID, Vals);
2431 pushValue(I.getOperand(1), InstID, Vals);
2432 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002433 break;
2434 case Instruction::ShuffleVector:
2435 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002436 pushValueAndType(I.getOperand(0), InstID, Vals);
2437 pushValue(I.getOperand(1), InstID, Vals);
2438 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002439 break;
2440 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002441 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002442 // compare returning Int1Ty or vector of Int1Ty
2443 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002444 pushValueAndType(I.getOperand(0), InstID, Vals);
2445 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002446 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002447 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002448 if (Flags != 0)
2449 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002450 break;
James Molloy88eb5352015-07-10 12:52:00 +00002451 }
Chris Lattner0a603252007-05-01 02:13:26 +00002452
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002454 {
2455 Code = bitc::FUNC_CODE_INST_RET;
2456 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002457 if (NumOperands == 0)
2458 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2459 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002460 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002461 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2462 } else {
2463 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002464 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002465 }
2466 }
Chris Lattner0a603252007-05-01 02:13:26 +00002467 break;
2468 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002469 {
2470 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002471 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002472 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2473 if (II.isConditional()) {
2474 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002475 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002476 }
Chris Lattner0a603252007-05-01 02:13:26 +00002477 }
2478 break;
2479 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002480 {
2481 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002482 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002483 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002484 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002485 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002486 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002487 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2488 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002489 }
2490 }
Chris Lattner0a603252007-05-01 02:13:26 +00002491 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002492 case Instruction::IndirectBr:
2493 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002494 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002495 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002496 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002497 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002498 Vals.push_back(VE.getValueID(I.getOperand(i)));
2499 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002500
Chris Lattnerb811e952007-05-01 07:03:37 +00002501 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002502 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002503 const Value *Callee = II->getCalledValue();
2504 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002505
2506 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002507 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002508
Chris Lattner0a603252007-05-01 02:13:26 +00002509 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002510
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002511 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002512 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002513 Vals.push_back(VE.getValueID(II->getNormalDest()));
2514 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002515 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002516 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002517
Chris Lattner0a603252007-05-01 02:13:26 +00002518 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002519 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002520 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002521
2522 // Emit type/value pairs for varargs params.
2523 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002524 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002525 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002526 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002527 }
2528 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002529 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002530 case Instruction::Resume:
2531 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002532 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002533 break;
David Majnemer654e1302015-07-31 17:58:14 +00002534 case Instruction::CleanupRet: {
2535 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2536 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002537 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002538 if (CRI.hasUnwindDest())
2539 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2540 break;
2541 }
2542 case Instruction::CatchRet: {
2543 Code = bitc::FUNC_CODE_INST_CATCHRET;
2544 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002545 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002546 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2547 break;
2548 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002549 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002550 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002551 const auto &FuncletPad = cast<FuncletPadInst>(I);
2552 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2553 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002554 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002555
2556 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002557 Vals.push_back(NumArgOperands);
2558 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002559 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002560 break;
2561 }
2562 case Instruction::CatchSwitch: {
2563 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2564 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2565
Teresa Johnson37687f32016-04-23 04:30:47 +00002566 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002567
2568 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2569 Vals.push_back(NumHandlers);
2570 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2571 Vals.push_back(VE.getValueID(CatchPadBB));
2572
2573 if (CatchSwitch.hasUnwindDest())
2574 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002575 break;
2576 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002577 case Instruction::Unreachable:
2578 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002579 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002580 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002581
Jay Foad372ad642011-06-20 14:18:48 +00002582 case Instruction::PHI: {
2583 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002584 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002585 // With the newer instruction encoding, forward references could give
2586 // negative valued IDs. This is most common for PHIs, so we use
2587 // signed VBRs.
2588 SmallVector<uint64_t, 128> Vals64;
2589 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002590 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002591 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002592 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002593 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002594 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002595 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002596 Vals64.clear();
2597 return;
Jay Foad372ad642011-06-20 14:18:48 +00002598 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002599
Bill Wendlingfae14752011-08-12 20:24:12 +00002600 case Instruction::LandingPad: {
2601 const LandingPadInst &LP = cast<LandingPadInst>(I);
2602 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2603 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002604 Vals.push_back(LP.isCleanup());
2605 Vals.push_back(LP.getNumClauses());
2606 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2607 if (LP.isCatch(I))
2608 Vals.push_back(LandingPadInst::Catch);
2609 else
2610 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002611 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002612 }
2613 break;
2614 }
2615
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002616 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002617 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002618 const AllocaInst &AI = cast<AllocaInst>(I);
2619 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002620 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002621 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002622 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2623 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2624 "not enough bits for maximum alignment");
2625 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2626 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002627 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002628 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002629 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002630 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002631 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002632
Chris Lattner0a603252007-05-01 02:13:26 +00002633 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002634 if (cast<LoadInst>(I).isAtomic()) {
2635 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002636 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002637 } else {
2638 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002639 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002640 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2641 }
David Blaikie85035652015-02-25 01:07:20 +00002642 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002643 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2644 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002645 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002646 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2647 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002648 }
Chris Lattner0a603252007-05-01 02:13:26 +00002649 break;
2650 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002651 if (cast<StoreInst>(I).isAtomic())
2652 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2653 else
2654 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002655 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2656 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002657 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2658 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002659 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002660 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2661 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002662 }
Chris Lattner0a603252007-05-01 02:13:26 +00002663 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002664 case Instruction::AtomicCmpXchg:
2665 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002666 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2667 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2668 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002669 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002670 Vals.push_back(
2671 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2672 Vals.push_back(
2673 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2674 Vals.push_back(
2675 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002676 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002677 break;
2678 case Instruction::AtomicRMW:
2679 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002680 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2681 pushValue(I.getOperand(1), InstID, Vals); // val.
2682 Vals.push_back(
2683 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002684 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002685 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2686 Vals.push_back(
2687 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002688 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002689 case Instruction::Fence:
2690 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002691 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2692 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002693 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002694 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002695 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002696 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002697
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002698 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002699 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002700
Chris Lattnerc44070802011-06-17 18:17:37 +00002701 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002702
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002703 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002704
Teresa Johnson37687f32016-04-23 04:30:47 +00002705 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002706 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2707 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2708 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2709 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002710 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2711 unsigned(Flags != 0) << bitc::CALL_FMF);
2712 if (Flags != 0)
2713 Vals.push_back(Flags);
2714
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002715 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002716 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002717
Chris Lattner0a603252007-05-01 02:13:26 +00002718 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002719 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2720 // Check for labels (can happen with asm labels).
2721 if (FTy->getParamType(i)->isLabelTy())
2722 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2723 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002724 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002725 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002726
Chris Lattnerb811e952007-05-01 07:03:37 +00002727 // Emit type/value pairs for varargs params.
2728 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002729 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002730 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002731 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002732 }
2733 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002734 }
Chris Lattner0a603252007-05-01 02:13:26 +00002735 case Instruction::VAArg:
2736 Code = bitc::FUNC_CODE_INST_VAARG;
2737 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002738 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002739 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2740 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002743 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002744 Vals.clear();
2745}
2746
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002747/// Write a GlobalValue VST to the module. The purpose of this data structure is
2748/// to allow clients to efficiently find the function body.
2749void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2750 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2751 // Get the offset of the VST we are writing, and backpatch it into
2752 // the VST forward declaration record.
2753 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2754 // The BitcodeStartBit was the stream offset of the identification block.
2755 VSTOffset -= bitcodeStartBit();
2756 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2757 // Note that we add 1 here because the offset is relative to one word
2758 // before the start of the identification block, which was historically
2759 // always the start of the regular bitcode header.
2760 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002761
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002762 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002763
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002764 auto Abbv = std::make_shared<BitCodeAbbrev>();
2765 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2768 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002769
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002770 for (const Function &F : M) {
2771 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002772
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002773 if (F.isDeclaration())
2774 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002775
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002776 Record[0] = VE.getValueID(&F);
2777
2778 // Save the word offset of the function (from the start of the
2779 // actual bitcode written to the stream).
2780 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2781 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2782 // Note that we add 1 here because the offset is relative to one word
2783 // before the start of the identification block, which was historically
2784 // always the start of the regular bitcode header.
2785 Record[1] = BitcodeIndex / 32 + 1;
2786
2787 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002788 }
2789
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002790 Stream.ExitBlock();
2791}
2792
2793/// Emit names for arguments, instructions and basic blocks in a function.
2794void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2795 const ValueSymbolTable &VST) {
2796 if (VST.empty())
2797 return;
2798
2799 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2800
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002801 // FIXME: Set up the abbrev, we know how many values there are!
2802 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002803 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002804
Yaron Keren001e2e42015-08-10 07:04:29 +00002805 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002806 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00002807 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002808
Chris Lattnera0987962007-05-04 21:31:13 +00002809 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002810 NameVals.push_back(VE.getValueID(Name.getValue()));
2811
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002812 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002813 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002814 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002815 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002816 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002817 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002818 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002819 } else {
2820 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002821 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002822 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002823 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002824 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002825 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002826
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002827 for (const auto P : Name.getKey())
2828 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002829
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002830 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002831 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002832 NameVals.clear();
2833 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002834
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002835 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002836}
2837
Teresa Johnson37687f32016-04-23 04:30:47 +00002838void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002839 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2840 unsigned Code;
2841 if (isa<BasicBlock>(Order.V))
2842 Code = bitc::USELIST_CODE_BB;
2843 else
2844 Code = bitc::USELIST_CODE_DEFAULT;
2845
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002846 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002847 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002848 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002849}
2850
Teresa Johnson37687f32016-04-23 04:30:47 +00002851void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002852 assert(VE.shouldPreserveUseListOrder() &&
2853 "Expected to be preserving use-list order");
2854
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002855 auto hasMore = [&]() {
2856 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2857 };
2858 if (!hasMore())
2859 // Nothing to do.
2860 return;
2861
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002862 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002863 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002864 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002865 VE.UseListOrders.pop_back();
2866 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002867 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002868}
2869
Teresa Johnson403a7872015-10-04 14:33:43 +00002870/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002871void ModuleBitcodeWriter::writeFunction(
2872 const Function &F,
2873 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002874 // Save the bitcode index of the start of this function block for recording
2875 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002876 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002877
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002878 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002879 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002880
2881 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002882
Chris Lattnere6e364c2007-04-26 05:53:54 +00002883 // Emit the number of basic blocks, so the reader can create them ahead of
2884 // time.
2885 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002886 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002887 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002888
Chris Lattnere6e364c2007-04-26 05:53:54 +00002889 // If there are function-local constants, emit them now.
2890 unsigned CstStart, CstEnd;
2891 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00002892 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002893
Victor Hernandez6c730de2010-01-14 01:50:08 +00002894 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002895 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00002896
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002897 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002898 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002899
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002900 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002901
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002902 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002903 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002904 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002905 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2906 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002907 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002908
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002909 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002910 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002911
Chris Lattner07d09ed2010-04-03 02:17:50 +00002912 // If the instruction has metadata, write a metadata attachment later.
2913 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002914
Chris Lattner07d09ed2010-04-03 02:17:50 +00002915 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002916 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002917 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002918 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002919
2920 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00002921 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002922 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002923 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002924 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002925
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002926 Vals.push_back(DL->getLine());
2927 Vals.push_back(DL->getColumn());
2928 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2929 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002930 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002931 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00002932
2933 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002934 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002935
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002936 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002937 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002938 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00002939
Chris Lattner07d09ed2010-04-03 02:17:50 +00002940 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002941 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002942 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00002943 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00002944 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002945 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00002946}
2947
Chris Lattner702658c2007-05-04 18:26:27 +00002948// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002949void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00002950 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00002951 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00002952 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00002953 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002954
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002955 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002956 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002961 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002962 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002963 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002965
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002966 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002967 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002968 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2971 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002972 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002973 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002974 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002975 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002976 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002977 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00002978 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002982 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002983 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002984 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00002985 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002986 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002987 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002988 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00002991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002992 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002993 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002994 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002995 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002996
2997
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002998
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002999 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003000 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003001 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003003 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003004 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003005 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003006 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003007 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003008
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003009 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003010 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003011 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003013 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003014 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003015 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003016 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003017
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003018 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003019 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003020 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3022 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003023 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003024 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3025
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003026 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003027 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003028 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003029 }
3030 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003031 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003032 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003033 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003034 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003035 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003037
Chris Lattnerb80751d2007-05-05 07:44:49 +00003038 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003039
Chris Lattnerb80751d2007-05-05 07:44:49 +00003040 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003041 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003042 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3045 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3047 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003048 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003049 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003050 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003051 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003052 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003053 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003054 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003058 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003059 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003060 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003061 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003062 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003063 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003064 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003069 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003070 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003071 llvm_unreachable("Unexpected abbrev ordering!");
3072 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003073 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003074 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003075 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003078 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003079 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003080 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003081 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003082 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003083 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003085 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003086 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003087 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003088 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003089 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003090 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003091 }
3092 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003093 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003094 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3095 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003096 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003097 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003098 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003099 }
3100 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003101 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003102 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003103 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003104 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003105 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003106 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003107 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003108 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003109 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3111 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3112 Log2_32_Ceil(VE.getTypes().size() + 1)));
3113 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003115 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003116 FUNCTION_INST_GEP_ABBREV)
3117 llvm_unreachable("Unexpected abbrev ordering!");
3118 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003119
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003120 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003121}
3122
Teresa Johnson403a7872015-10-04 14:33:43 +00003123/// Write the module path strings, currently only used when generating
3124/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003125void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003126 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003127
3128 // TODO: See which abbrev sizes we actually need to emit
3129
3130 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003131 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003132 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3133 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3134 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003136 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003137
3138 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003139 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003140 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3142 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003144 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003145
3146 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003147 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003148 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3151 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003152 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003153
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003154 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003155 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003156 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003162 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003163
3164 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003165 forEachModule(
3166 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003167 StringRef Key = MPSE.getKey();
3168 const auto &Value = MPSE.getValue();
3169 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003170 unsigned AbbrevToUse = Abbrev8Bit;
3171 if (Bits == SE_Char6)
3172 AbbrevToUse = Abbrev6Bit;
3173 else if (Bits == SE_Fixed7)
3174 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003175
David Blaikieb6b42e02017-06-02 17:24:26 +00003176 Vals.push_back(Value.first);
3177 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003178
Teresa Johnson7a27b132017-06-02 01:56:02 +00003179 // Emit the finished record.
3180 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003181
Teresa Johnson7a27b132017-06-02 01:56:02 +00003182 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003183 const auto &Hash = Value.second;
3184 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3185 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003186 // Emit the hash record.
3187 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3188 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003189
Teresa Johnson7a27b132017-06-02 01:56:02 +00003190 Vals.clear();
3191 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003192 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003193}
3194
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003195/// Write the function type metadata related records that need to appear before
3196/// a function summary entry (whether per-module or combined).
3197static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3198 FunctionSummary *FS) {
3199 if (!FS->type_tests().empty())
3200 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3201
3202 SmallVector<uint64_t, 64> Record;
3203
3204 auto WriteVFuncIdVec = [&](uint64_t Ty,
3205 ArrayRef<FunctionSummary::VFuncId> VFs) {
3206 if (VFs.empty())
3207 return;
3208 Record.clear();
3209 for (auto &VF : VFs) {
3210 Record.push_back(VF.GUID);
3211 Record.push_back(VF.Offset);
3212 }
3213 Stream.EmitRecord(Ty, Record);
3214 };
3215
3216 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3217 FS->type_test_assume_vcalls());
3218 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3219 FS->type_checked_load_vcalls());
3220
3221 auto WriteConstVCallVec = [&](uint64_t Ty,
3222 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3223 for (auto &VC : VCs) {
3224 Record.clear();
3225 Record.push_back(VC.VFunc.GUID);
3226 Record.push_back(VC.VFunc.Offset);
3227 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3228 Stream.EmitRecord(Ty, Record);
3229 }
3230 };
3231
3232 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3233 FS->type_test_assume_const_vcalls());
3234 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3235 FS->type_checked_load_const_vcalls());
3236}
3237
Teresa Johnson403a7872015-10-04 14:33:43 +00003238// Helper to emit a single function summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003239void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003240 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003241 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3242 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003243 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003244
Teresa Johnson28e457b2016-04-24 14:57:11 +00003245 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003246 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003247
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003248 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003249 NameVals.push_back(FS->instCount());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003250 NameVals.push_back(FS->refs().size());
3251
3252 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003253 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003254
3255 bool HasProfileData = F.getEntryCount().hasValue();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003256 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003257 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003258 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003259 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003260 }
3261
3262 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3263 unsigned Code =
3264 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003265
3266 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003267 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003268 NameVals.clear();
3269}
3270
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003271// Collect the global value references in the given variable's initializer,
3272// and emit them in a summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003273void ModuleBitcodeWriter::writeModuleLevelReferences(
3274 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3275 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003276 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3277 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003278 // Only declarations should not have a summary (a declaration might however
3279 // have a summary if the def was in module level asm).
3280 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003281 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003282 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003283 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003284 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003285 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003286 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003287
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003288 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003289 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003290 NameVals.push_back(VE.getValueID(RI.getValue()));
3291 // Sort the refs for determinism output, the vector returned by FS->refs() has
3292 // been initialized from a DenseSet.
3293 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003294
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003295 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3296 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003297 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003298}
Teresa Johnson403a7872015-10-04 14:33:43 +00003299
Mehdi Amini8fe69362016-04-24 03:18:11 +00003300// Current version for the summary.
3301// This is bumped whenever we introduce changes in the way some record are
3302// interpreted, like flags for instance.
Teresa Johnson519465b2017-01-05 14:32:16 +00003303static const uint64_t INDEX_VERSION = 3;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003304
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003305/// Emit the per-module summary section alongside the rest of
3306/// the module's bitcode.
Teresa Johnson37687f32016-04-23 04:30:47 +00003307void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003308 // By default we compile with ThinLTO if the module has a summary, but the
3309 // client can request full LTO with a module flag.
3310 bool IsThinLTO = true;
3311 if (auto *MD =
3312 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3313 IsThinLTO = MD->getZExtValue();
3314 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3315 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3316 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003317
Mehdi Amini8fe69362016-04-24 03:18:11 +00003318 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3319
Teresa Johnson620c1402016-09-20 23:07:17 +00003320 if (Index->begin() == Index->end()) {
3321 Stream.ExitBlock();
3322 return;
3323 }
3324
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003325 for (const auto &GVI : valueIds()) {
3326 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3327 ArrayRef<uint64_t>{GVI.second, GVI.first});
3328 }
3329
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003330 // Abbrev for FS_PERMODULE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003331 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003332 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003333 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003337 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003340 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003341
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003342 // Abbrev for FS_PERMODULE_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003343 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003344 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3345 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003349 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003352 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003353
3354 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003355 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003356 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003358 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003361 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003362
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003363 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003364 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003365 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003369 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003370
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003371 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003372 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003373 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003374 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003375 // Summary emission does not support anonymous functions, they have to
3376 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003377 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003378 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003379
Peter Collingbourne9667b912017-05-04 18:03:25 +00003380 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3381 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003382 // Only declarations should not have a summary (a declaration might
3383 // however have a summary if the def was in module level asm).
3384 assert(F.isDeclaration());
3385 continue;
3386 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003387 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003388 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3389 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003390 }
3391
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003392 // Capture references from GlobalVariable initializers, which are outside
3393 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003394 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003395 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003396
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003397 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003398 auto *Aliasee = A.getBaseObject();
3399 if (!Aliasee->hasName())
3400 // Nameless function don't have an entry in the summary, skip it.
3401 continue;
3402 auto AliasId = VE.getValueID(&A);
3403 auto AliaseeId = VE.getValueID(Aliasee);
3404 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003405 auto *Summary = Index->getGlobalValueSummary(A);
3406 AliasSummary *AS = cast<AliasSummary>(Summary);
3407 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003408 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003409 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003410 NameVals.clear();
3411 }
3412
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003413 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003414}
3415
Teresa Johnson26ab5772016-03-15 00:04:37 +00003416/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003417void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003418 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003419 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003420
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003421 for (const auto &GVI : valueIds()) {
3422 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3423 ArrayRef<uint64_t>{GVI.second, GVI.first});
3424 }
3425
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003426 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003427 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003428 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003429 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003430 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003431 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003434 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003437 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003438
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003439 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003440 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003441 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003447 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003450 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003451
3452 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003453 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003454 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003457 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003460 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003461
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003462 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003463 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003464 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003467 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003468 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003469 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003470
Teresa Johnson02e98332016-04-27 13:28:35 +00003471 // The aliases are emitted as a post-pass, and will point to the value
3472 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003473 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003474
Teresa Johnson02e98332016-04-27 13:28:35 +00003475 // Save the value id for each summary for alias emission.
3476 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3477
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003478 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003479
3480 // For local linkage, we also emit the original name separately
3481 // immediately after the record.
3482 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3483 if (!GlobalValue::isLocalLinkage(S.linkage()))
3484 return;
3485 NameVals.push_back(S.getOriginalName());
3486 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3487 NameVals.clear();
3488 };
3489
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003490 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003491 GlobalValueSummary *S = I.second;
3492 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003493
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003494 auto ValueId = getValueId(I.first);
3495 assert(ValueId);
3496 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003497
Teresa Johnson84174c32016-05-10 13:48:23 +00003498 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3499 // Will process aliases as a post-pass because the reader wants all
3500 // global to be loaded first.
3501 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003502 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003503 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003504
Teresa Johnson84174c32016-05-10 13:48:23 +00003505 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003506 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003507 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3508 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3509 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003510 auto RefValueId = getValueId(RI.getGUID());
3511 if (!RefValueId)
3512 continue;
3513 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003514 }
3515
Teresa Johnson403a7872015-10-04 14:33:43 +00003516 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003517 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3518 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003519 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003520 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003521 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003522 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003523
3524 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003525 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003526
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003527 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003528 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3529 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3530 NameVals.push_back(FS->instCount());
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003531 // Fill in below
3532 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003533
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003534 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003535 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003536 auto RefValueId = getValueId(RI.getGUID());
3537 if (!RefValueId)
3538 continue;
3539 NameVals.push_back(*RefValueId);
3540 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003541 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003542 NameVals[4] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003543
3544 bool HasProfileData = false;
3545 for (auto &EI : FS->calls()) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003546 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003547 if (HasProfileData)
3548 break;
3549 }
3550
3551 for (auto &EI : FS->calls()) {
3552 // If this GUID doesn't have a value id, it doesn't have a function
3553 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003554 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003555 auto CallValueId = getValueId(GUID);
3556 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003557 // For SamplePGO, the indirect call targets for local functions will
3558 // have its original name annotated in profile. We try to find the
3559 // corresponding PGOFuncName as the GUID.
3560 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003561 if (GUID == 0)
3562 continue;
3563 CallValueId = getValueId(GUID);
3564 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003565 continue;
3566 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003567 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003568 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003569 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003570 }
3571
3572 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3573 unsigned Code =
3574 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3575
3576 // Emit the finished record.
3577 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3578 NameVals.clear();
3579 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003580 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003581
Teresa Johnson28e457b2016-04-24 14:57:11 +00003582 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003583 auto AliasValueId = SummaryToValueIdMap[AS];
3584 assert(AliasValueId);
3585 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003586 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003587 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003588 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3589 assert(AliaseeValueId);
3590 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003591
3592 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003593 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003594 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003595 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003596 }
3597
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003598 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003599}
3600
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003601/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3602/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003603static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003604 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003605
3606 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003607 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003608 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003611 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003612 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003613 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003614
3615 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003616 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003617 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3618 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003619 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003620 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003621 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3622 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003623}
3624
Teresa Johnson37687f32016-04-23 04:30:47 +00003625void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003626 // Emit the module's hash.
3627 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003628 if (GenerateHash) {
3629 SHA1 Hasher;
3630 uint32_t Vals[5];
3631 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3632 Buffer.size() - BlockStartPos));
3633 StringRef Hash = Hasher.result();
3634 for (int Pos = 0; Pos < 20; Pos += 4) {
3635 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3636 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003637
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003638 // Emit the finished record.
3639 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3640
3641 if (ModHash)
3642 // Save the written hash value.
3643 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3644 } else if (ModHash)
3645 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003646}
3647
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003648void ModuleBitcodeWriter::write() {
3649 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003650
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003651 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3652 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003653
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003654 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003655
3656 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003657 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003658
Bill Wendlingdc095552013-02-10 23:09:32 +00003659 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003660 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003661
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003662 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003663 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003664
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003665 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003666 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003667
Teresa Johnson37687f32016-04-23 04:30:47 +00003668 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003669
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003670 // Emit top-level description of module, including target triple, inline asm,
3671 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003672 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003673
Devang Patele059ba6e2009-07-23 01:07:34 +00003674 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003675 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003676
Peter Collingbourne21521892016-06-21 23:42:48 +00003677 // Emit metadata kind names.
3678 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003679
Devang Patelaf206b82009-09-18 19:26:43 +00003680 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003681 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003682
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003683 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003684 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003685 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003686
Teresa Johnson37687f32016-04-23 04:30:47 +00003687 writeOperandBundleTags();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003688
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003689 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003690 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003691 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003692 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003693 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003694
3695 // Need to write after the above call to WriteFunction which populates
3696 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003697 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003698 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003699
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003700 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003701
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003702 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003703
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003704 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003705}
3706
Teresa Johnson37687f32016-04-23 04:30:47 +00003707static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3708 uint32_t &Position) {
3709 support::endian::write32le(&Buffer[Position], Value);
3710 Position += 4;
3711}
3712
3713/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003714/// header and trailer to make it compatible with the system archiver. To do
3715/// this we emit the following header, and then emit a trailer that pads the
3716/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003717///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003718/// struct bc_header {
3719/// uint32_t Magic; // 0x0B17C0DE
3720/// uint32_t Version; // Version, currently always 0.
3721/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3722/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3723/// uint32_t CPUType; // CPU specifier.
3724/// ... potentially more later ...
3725/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003726static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003727 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003728 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003729
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003730 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003731 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3732 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3733 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003734 enum {
3735 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3736 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003737 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003738 DARWIN_CPU_TYPE_POWERPC = 18
3739 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003740
Evan Chengcffdcae2011-06-14 01:51:33 +00003741 Triple::ArchType Arch = TT.getArch();
3742 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003743 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003744 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003745 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003746 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003747 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003748 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003749 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003750 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003751 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003752
Chris Lattnera660f4b2008-07-09 05:14:23 +00003753 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003754 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003755 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003756 unsigned BCOffset = BWH_HeaderSize;
3757 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003758
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003759 // Write the magic and version.
3760 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003761 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3762 writeInt32ToBuffer(0, Buffer, Position); // Version.
3763 writeInt32ToBuffer(BCOffset, Buffer, Position);
3764 writeInt32ToBuffer(BCSize, Buffer, Position);
3765 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003766
Chris Lattnera660f4b2008-07-09 05:14:23 +00003767 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003768 while (Buffer.size() & 15)
3769 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003770}
3771
Teresa Johnson403a7872015-10-04 14:33:43 +00003772/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003773static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003774 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003775 Stream.Emit((unsigned)'B', 8);
3776 Stream.Emit((unsigned)'C', 8);
3777 Stream.Emit(0x0, 4);
3778 Stream.Emit(0xC, 4);
3779 Stream.Emit(0xE, 4);
3780 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003781}
3782
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003783BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3784 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3785 writeBitcodeHeader(*Stream);
3786}
3787
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003788BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3789
3790void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3791 Stream->EnterSubblock(Block, 3);
3792
3793 auto Abbv = std::make_shared<BitCodeAbbrev>();
3794 Abbv->Add(BitCodeAbbrevOp(Record));
3795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3796 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3797
3798 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3799
3800 Stream->ExitBlock();
3801}
3802
3803void BitcodeWriter::writeStrtab() {
3804 assert(!WroteStrtab);
3805
3806 std::vector<char> Strtab;
3807 StrtabBuilder.finalizeInOrder();
3808 Strtab.resize(StrtabBuilder.getSize());
3809 StrtabBuilder.write((uint8_t *)Strtab.data());
3810
3811 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3812 {Strtab.data(), Strtab.size()});
3813
3814 WroteStrtab = true;
3815}
3816
3817void BitcodeWriter::copyStrtab(StringRef Strtab) {
3818 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3819 WroteStrtab = true;
3820}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003821
3822void BitcodeWriter::writeModule(const Module *M,
3823 bool ShouldPreserveUseListOrder,
3824 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003825 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003826 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003827 ShouldPreserveUseListOrder, Index,
3828 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003829 ModuleWriter.write();
3830}
3831
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003832/// WriteBitcodeToFile - Write the specified module to the specified output
3833/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00003834void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00003835 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003836 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003837 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00003838 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003839 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003840
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003841 // If this is darwin or another generic macho target, reserve space for the
3842 // header.
3843 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00003844 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003845 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003846
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003847 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003848 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3849 ModHash);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003850 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003851
Akira Hatanaka1235d282016-01-23 16:02:10 +00003852 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00003853 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003854
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003855 // Write the generated bitstream to "Out".
3856 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003857}
Teresa Johnson403a7872015-10-04 14:33:43 +00003858
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003859void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003860 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00003861
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003862 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00003863
3864 // Write the module paths in the combined index.
3865 writeModStrings();
3866
3867 // Write the summary combined index records.
3868 writeCombinedGlobalValueSummary();
3869
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003870 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00003871}
3872
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003873// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00003874// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00003875// writing the combined index file for ThinLTO. When writing a subset of the
3876// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3877void llvm::WriteIndexToFile(
3878 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00003879 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003880 SmallVector<char, 0> Buffer;
3881 Buffer.reserve(256 * 1024);
3882
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003883 BitstreamWriter Stream(Buffer);
3884 writeBitcodeHeader(Stream);
3885
3886 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00003887 IndexWriter.write();
Teresa Johnson403a7872015-10-04 14:33:43 +00003888
3889 Out.write((char *)&Buffer.front(), Buffer.size());
3890}