blob: 90c26e3f54eb1f3993c68e81d68a516f30633b8b [file] [log] [blame]
Zonr Chang66a1a5a2010-10-22 11:00:11 +08001/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "slang_rs_metadata_spec.h"
18
19#include <map>
20#include <list>
21#include <string>
22#include <cstdlib>
23
24#include "llvm/Module.h"
25#include "llvm/Metadata.h"
26
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29
30#include "slang_rs_type_spec.h"
31
32#define RS_METADATA_STRTAB_MN "#rs_metadata_strtab"
33#define RS_TYPE_INFO_MN "#rs_type_info"
34#define RS_EXPORT_VAR_MN "#rs_export_var"
35#define RS_EXPORT_FUNC_MN "#rs_export_func"
36#define RS_EXPORT_RECORD_TYPE_NAME_MN_PREFIX "%"
37
38///////////////////////////////////////////////////////////////////////////////
39// Useful utility functions
40///////////////////////////////////////////////////////////////////////////////
41static bool EncodeInteger(llvm::LLVMContext &C,
42 unsigned I,
43 llvm::SmallVectorImpl<llvm::Value*> &Op) {
44 llvm::StringRef S(reinterpret_cast<const char*>(&I), sizeof(I));
45 llvm::MDString *MDS = llvm::MDString::get(C, S);
46
47 if (MDS == NULL)
48 return false;
49 Op.push_back(MDS);
50 return true;
51}
52
53///////////////////////////////////////////////////////////////////////////////
54// class RSMetadataEncoderInternal
55///////////////////////////////////////////////////////////////////////////////
56namespace {
57
58class RSMetadataEncoderInternal {
59 private:
60 llvm::Module *mModule;
61
62 typedef std::map</* key */unsigned, unsigned/* index */> TypesMapTy;
63 TypesMapTy mTypes;
64 std::list<unsigned> mEncodedRSTypeInfo; // simply a sequece of integers
65 unsigned mCurTypeIndex;
66
67 // A special type for lookup created record type. It uses record name as key.
68 typedef std::map</* name */std::string, unsigned/* index */> RecordTypesMapTy;
69 RecordTypesMapTy mRecordTypes;
70
71 typedef std::map<std::string, unsigned/* index */> StringsMapTy;
72 StringsMapTy mStrings;
73 std::list<const char*> mEncodedStrings;
74 unsigned mCurStringIndex;
75
76 llvm::NamedMDNode *mVarInfoMetadata;
77 llvm::NamedMDNode *mFuncInfoMetadata;
78
79 // This function check the return value of function:
80 // joinString, encodeTypeBase, encode*Type(), encodeRSType, encodeRSVar,
81 // and encodeRSFunc. Return false if the value of Index indicates failure.
82 inline bool checkReturnIndex(unsigned &Index) {
83 if (Index == 0)
84 return false;
85 else
86 Index--;
87 return true;
88 }
89
90 unsigned joinString(const std::string &S);
91
92 unsigned encodeTypeBase(const struct RSTypeBase *Base);
93 unsigned encodeTypeBaseAsKey(const struct RSTypeBase *Base);
94#define ENUM_RS_DATA_TYPE_CLASS(x) \
95 unsigned encode ## x ## Type(const union RSType *T);
96RS_DATA_TYPE_CLASS_ENUMS
97#undef ENUM_RS_DATA_TYPE_CLASS
98
99 unsigned encodeRSType(const union RSType *T);
100
101 int flushStringTable();
102 int flushTypeInfo();
103
104 public:
105 RSMetadataEncoderInternal(llvm::Module *M);
106
107 int encodeRSVar(const RSVar *V);
108 int encodeRSFunc(const RSFunction *F);
109
110 int finalize();
111};
112
113}
114
115RSMetadataEncoderInternal::RSMetadataEncoderInternal(llvm::Module *M)
116 : mModule(M),
117 mCurTypeIndex(0),
118 mCurStringIndex(0),
119 mVarInfoMetadata(NULL),
120 mFuncInfoMetadata(NULL) {
121 mTypes.clear();
122 mEncodedRSTypeInfo.clear();
123 mRecordTypes.clear();
124 mStrings.clear();
125
126 return;
127}
128
129// Return (StringIndex + 1) when successfully join the string and 0 if there's
130// any error.
131unsigned RSMetadataEncoderInternal::joinString(const std::string &S) {
132 StringsMapTy::const_iterator I = mStrings.find(S);
133
134 if (I != mStrings.end())
135 return (I->second + 1);
136
137 // Add S into mStrings
138 std::pair<StringsMapTy::iterator, bool> Res =
139 mStrings.insert(std::make_pair(S, mCurStringIndex));
140 // Insertion failed
141 if (!Res.second)
142 return 0;
143
144 // Add S into mEncodedStrings
145 mEncodedStrings.push_back(Res.first->first.c_str());
146 mCurStringIndex++;
147
148 // Return (StringIndex + 1)
149 return (Res.first->second + 1);
150}
151
152unsigned
153RSMetadataEncoderInternal::encodeTypeBase(const struct RSTypeBase *Base) {
154 mEncodedRSTypeInfo.push_back(Base->bits);
155 return ++mCurTypeIndex;
156}
157
158unsigned RSMetadataEncoderInternal::encodeTypeBaseAsKey(
159 const struct RSTypeBase *Base) {
160 TypesMapTy::const_iterator I = mTypes.find(Base->bits);
161 if (I != mTypes.end())
162 return (I->second + 1);
163
164 // Add Base into mTypes
165 std::pair<TypesMapTy::iterator, bool> Res =
166 mTypes.insert(std::make_pair(Base->bits, mCurTypeIndex));
167 // Insertion failed
168 if (!Res.second)
169 return 0;
170
171 // Push to mEncodedRSTypeInfo. This will also update mCurTypeIndex.
172 return encodeTypeBase(Base);
173}
174
175unsigned RSMetadataEncoderInternal::encodePrimitiveType(const union RSType *T) {
176 return encodeTypeBaseAsKey(RS_GET_TYPE_BASE(T));
177}
178
179unsigned RSMetadataEncoderInternal::encodePointerType(const union RSType *T) {
180 // Encode pointee type first
181 unsigned PointeeType = encodeRSType(RS_POINTER_TYPE_GET_POINTEE_TYPE(T));
182 if (!checkReturnIndex(PointeeType))
183 return 0;
184
185 unsigned Res = encodeTypeBaseAsKey(RS_GET_TYPE_BASE(T));
186 // Push PointeeType after the base type
187 mEncodedRSTypeInfo.push_back(PointeeType);
188 return Res;
189}
190
191unsigned RSMetadataEncoderInternal::encodeVectorType(const union RSType *T) {
192 return encodeTypeBaseAsKey(RS_GET_TYPE_BASE(T));
193}
194
195unsigned RSMetadataEncoderInternal::encodeMatrixType(const union RSType *T) {
196 return encodeTypeBaseAsKey(RS_GET_TYPE_BASE(T));
197}
198
199unsigned
200RSMetadataEncoderInternal::encodeConstantArrayType(const union RSType *T) {
201 // Encode element type
202 unsigned ElementType =
203 encodeRSType(RS_CONSTANT_ARRAY_TYPE_GET_ELEMENT_TYPE(T));
204 if (!checkReturnIndex(ElementType))
205 return 0;
206
207 unsigned Res = encodeTypeBase(RS_GET_TYPE_BASE(T));
208 // Push the ElementType after the type base
209 mEncodedRSTypeInfo.push_back(ElementType);
210 return Res;
211}
212
213unsigned RSMetadataEncoderInternal::encodeRecordType(const union RSType *T) {
214 // Construct record name
215 std::string RecordInfoMetadataName(RS_EXPORT_RECORD_TYPE_NAME_MN_PREFIX);
216 RecordInfoMetadataName.append(RS_RECORD_TYPE_GET_NAME(T));
217
218 // Try to find it in mRecordTypes
219 RecordTypesMapTy::const_iterator I =
220 mRecordTypes.find(RecordInfoMetadataName);
221
222 // This record type has been encoded before. Fast return its index here.
223 if (I != mRecordTypes.end())
224 return (I->second + 1);
225
226 // Encode this record type into mTypes. Encode record name string first.
227 unsigned RecordName = joinString(RecordInfoMetadataName);
228 if (!checkReturnIndex(RecordName))
229 return 0;
230
231 unsigned Base = encodeTypeBase(RS_GET_TYPE_BASE(T));
232 if (!checkReturnIndex(Base))
233 return 0;
234
235 // Push record name after encoding the type base
236 mEncodedRSTypeInfo.push_back(RecordName);
237
238 // Add this record type into the map
239 std::pair<StringsMapTy::iterator, bool> Res =
240 mRecordTypes.insert(std::make_pair(RecordInfoMetadataName, Base));
241 // Insertion failed
242 if (!Res.second)
243 return 0;
244
245 // Create a named MDNode for this record type. We cannot create this before
246 // encoding type base into Types and updating mRecordTypes. This is because
247 // we may have structure like:
248 //
249 // struct foo {
250 // ...
251 // struct foo *bar; // self type reference
252 // ...
253 // }
254 llvm::NamedMDNode *RecordInfoMetadata =
255 mModule->getOrInsertNamedMetadata(RecordInfoMetadataName);
256
257 assert((RecordInfoMetadata->getNumOperands() == 0) &&
258 "Record created before!");
259
260 // Encode field info into this named MDNode
261 llvm::SmallVector<llvm::Value*, 3> FieldInfo;
262
263 for (unsigned i = 0; i < RS_RECORD_TYPE_GET_NUM_FIELDS(T); i++) {
264 // 1. field name
265 unsigned FieldName = joinString(RS_RECORD_TYPE_GET_FIELD_NAME(T, i));
266 if (!checkReturnIndex(FieldName))
267 return 0;
268 if (!EncodeInteger(mModule->getContext(),
269 FieldName,
270 FieldInfo))
271 return 0;
272
273 // 2. field type
274 unsigned FieldType = encodeRSType(RS_RECORD_TYPE_GET_FIELD_TYPE(T, i));
275 if (!checkReturnIndex(FieldType))
276 return 0;
277 if (!EncodeInteger(mModule->getContext(),
278 FieldType,
279 FieldInfo))
280 return 0;
281
282 // 3. field data kind
283 if (!EncodeInteger(mModule->getContext(),
284 RS_RECORD_TYPE_GET_FIELD_DATA_KIND(T, i),
285 FieldInfo))
286 return 0;
287
288 RecordInfoMetadata->addOperand(llvm::MDNode::get(mModule->getContext(),
289 FieldInfo.data(),
290 FieldInfo.size()));
291 FieldInfo.clear();
292 }
293
294 return (Res.first->second + 1);
295}
296
297unsigned RSMetadataEncoderInternal::encodeRSType(const union RSType *T) {
298 switch (static_cast<enum RSTypeClass>(RS_TYPE_GET_CLASS(T))) {
299#define ENUM_RS_DATA_TYPE_CLASS(x) \
300 case RS_TC_ ## x: return encode ## x ## Type(T);
301 RS_DATA_TYPE_CLASS_ENUMS
302#undef ENUM_RS_DATA_TYPE_CLASS
303 default: return 0;
304 }
305 return 0;
306}
307
308int RSMetadataEncoderInternal::encodeRSVar(const RSVar *V) {
309 // check parameter
310 if ((V == NULL) || (V->name == NULL) || (V->type == NULL))
311 return -1;
312
313 // 1. var name
314 unsigned VarName = joinString(V->name);
315 if (!checkReturnIndex(VarName))
316 return -2;
317
318 // 2. type
319 unsigned Type = encodeRSType(V->type);
320
321 llvm::SmallVector<llvm::Value*, 1> VarInfo;
322
323 if (!EncodeInteger(mModule->getContext(), VarName, VarInfo))
324 return -3;
325 if (!EncodeInteger(mModule->getContext(), Type, VarInfo))
326 return -4;
327
328 if (mVarInfoMetadata == NULL)
329 mVarInfoMetadata = mModule->getOrInsertNamedMetadata(RS_EXPORT_VAR_MN);
330
331 mVarInfoMetadata->addOperand(llvm::MDNode::get(mModule->getContext(),
332 VarInfo.data(),
333 VarInfo.size()));
334
335 return 0;
336}
337
338int RSMetadataEncoderInternal::encodeRSFunc(const RSFunction *F) {
339 // check parameter
340 if ((F == NULL) || (F->name == NULL))
341 return -1;
342
343 // 1. var name
344 unsigned FuncName = joinString(F->name);
345 if (!checkReturnIndex(FuncName))
346 return -2;
347
348 llvm::SmallVector<llvm::Value*, 1> FuncInfo;
349 if (!EncodeInteger(mModule->getContext(), FuncName, FuncInfo))
350 return -3;
351
352 if (mFuncInfoMetadata == NULL)
353 mFuncInfoMetadata = mModule->getOrInsertNamedMetadata(RS_EXPORT_FUNC_MN);
354
355 mFuncInfoMetadata->addOperand(llvm::MDNode::get(mModule->getContext(),
356 FuncInfo.data(),
357 FuncInfo.size()));
358
359 return 0;
360}
361
362// Write string table and string index table
363int RSMetadataEncoderInternal::flushStringTable() {
364 assert((mCurStringIndex == mEncodedStrings.size()));
365 assert((mCurStringIndex == mStrings.size()));
366
367 if (mCurStringIndex == 0)
368 return 0;
369
370 // Prepare named MDNode for string table and string index table.
371 llvm::NamedMDNode *RSMetadataStrTab =
372 mModule->getOrInsertNamedMetadata(RS_METADATA_STRTAB_MN);
373 RSMetadataStrTab->dropAllReferences();
374
375 unsigned StrTabSize = 0;
376 unsigned *StrIdx = reinterpret_cast<unsigned*>(
377 ::malloc((mStrings.size() + 1) * sizeof(unsigned)));
378
379 if (StrIdx == NULL)
380 return -1;
381
382 unsigned StrIdxI = 0; // iterator for array StrIdx
383
384 // count StrTabSize and fill StrIdx by the way
385 for (std::list<const char*>::const_iterator I = mEncodedStrings.begin(),
386 E = mEncodedStrings.end();
387 I != E;
388 I++) {
389 StrIdx[StrIdxI++] = StrTabSize;
390 StrTabSize += ::strlen(*I) + 1 /* for '\0' */;
391 }
392 StrIdx[StrIdxI] = StrTabSize;
393
394 // Allocate
395 char *StrTab = reinterpret_cast<char*>(::malloc(StrTabSize));
396 if (StrTab == NULL) {
397 free(StrIdx);
398 return -1;
399 }
400
401 llvm::StringRef StrTabData(StrTab, StrTabSize);
402 llvm::StringRef StrIdxData(reinterpret_cast<const char*>(StrIdx),
403 mStrings.size() * sizeof(unsigned));
404
405 // Copy
406 StrIdxI = 1;
407 for (std::list<const char*>::const_iterator I = mEncodedStrings.begin(),
408 E = mEncodedStrings.end();
409 I != E;
410 I++) {
411 // Get string length from StrIdx (O(1)) instead of call strlen again (O(n)).
412 unsigned CurStrLength = StrIdx[StrIdxI] - StrIdx[StrIdxI - 1];
413 ::memcpy(StrTab, *I, CurStrLength);
414 // Move forward the pointer
415 StrTab += CurStrLength;
416 StrIdxI++;
417 }
418
419 // Flush to metadata
420 llvm::Value *StrTabMDS =
421 llvm::MDString::get(mModule->getContext(), StrTabData);
422 llvm::Value *StrIdxMDS =
423 llvm::MDString::get(mModule->getContext(), StrIdxData);
424
425 if ((StrTabMDS == NULL) || (StrIdxMDS == NULL)) {
426 free(StrIdx);
427 free(StrTab);
428 return -1;
429 }
430
431 llvm::SmallVector<llvm::Value*, 2> StrTabVal;
432 StrTabVal.push_back(StrTabMDS);
433 StrTabVal.push_back(StrIdxMDS);
434 RSMetadataStrTab->addOperand(llvm::MDNode::get(mModule->getContext(),
435 StrTabVal.data(),
436 StrTabVal.size()));
437
438 return 0;
439}
440
441// Write RS type stream
442int RSMetadataEncoderInternal::flushTypeInfo() {
443 unsigned TypeInfoCount = mEncodedRSTypeInfo.size();
444 if (TypeInfoCount <= 0)
445 return 0;
446
447 llvm::NamedMDNode *RSTypeInfo =
448 mModule->getOrInsertNamedMetadata(RS_TYPE_INFO_MN);
449 RSTypeInfo->dropAllReferences();
450
451 unsigned *TypeInfos =
452 reinterpret_cast<unsigned*>(::malloc(TypeInfoCount * sizeof(unsigned)));
453 unsigned TypeInfosIdx = 0; // iterator for array TypeInfos
454
455 if (TypeInfos == NULL)
456 return -1;
457
458 for (std::list<unsigned>::const_iterator I = mEncodedRSTypeInfo.begin(),
459 E = mEncodedRSTypeInfo.end();
460 I != E;
461 I++)
462 TypeInfos[TypeInfosIdx++] = *I;
463
464 llvm::StringRef TypeInfoData(reinterpret_cast<const char*>(TypeInfos),
465 TypeInfoCount * sizeof(unsigned));
466 llvm::Value *TypeInfoMDS =
467 llvm::MDString::get(mModule->getContext(), TypeInfoData);
468 if (TypeInfoMDS == NULL) {
469 free(TypeInfos);
470 return -1;
471 }
472
473 RSTypeInfo->addOperand(llvm::MDNode::get(mModule->getContext(),
474 &TypeInfoMDS, 1));
475 free(TypeInfos);
476
477 return 0;
478}
479
480int RSMetadataEncoderInternal::finalize() {
481 int Res = flushStringTable();
482 if (Res != 0)
483 return Res;
484
485 Res = flushTypeInfo();
486 if (Res != 0)
487 return Res;
488
489 return 0;
490}
491
492///////////////////////////////////////////////////////////////////////////////
493// APIs
494///////////////////////////////////////////////////////////////////////////////
495RSMetadataEncoder *CreateRSMetadataEncoder(llvm::Module *M) {
496 return reinterpret_cast<RSMetadataEncoder*>(new RSMetadataEncoderInternal(M));
497}
498
499int RSEncodeVarMetadata(RSMetadataEncoder *E, const RSVar *V) {
500 return reinterpret_cast<RSMetadataEncoderInternal*>(E)->encodeRSVar(V);
501}
502
503int RSEncodeFunctionMetadata(RSMetadataEncoder *E, const RSFunction *F) {
504 return reinterpret_cast<RSMetadataEncoderInternal*>(E)->encodeRSFunc(F);
505}
506
507void DestroyRSMetadataEncoder(RSMetadataEncoder *E) {
508 RSMetadataEncoderInternal *C =
509 reinterpret_cast<RSMetadataEncoderInternal*>(E);
510 delete C;
511 return;
512}
513
514int FinalizeRSMetadataEncoder(RSMetadataEncoder *E) {
515 RSMetadataEncoderInternal *C =
516 reinterpret_cast<RSMetadataEncoderInternal*>(E);
517 int Res = C->finalize();
518 DestroyRSMetadataEncoder(E);
519 return Res;
520}