Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(82)

Side by Side Diff: lib/Bitcode/NaCl/Reader/NaClBitcodeReader.cpp

Issue 770853002: Fix error reporting in the PNaCl bitcode reader. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-llvm.git@master
Patch Set: Fix nits. Created 6 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 //===- NaClBitcodeReader.cpp ----------------------------------------------===// 1 //===- NaClBitcodeReader.cpp ----------------------------------------------===//
2 // Internal NaClBitcodeReader implementation 2 // Internal NaClBitcodeReader implementation
3 // 3 //
4 // The LLVM Compiler Infrastructure 4 // The LLVM Compiler Infrastructure
5 // 5 //
6 // This file is distributed under the University of Illinois Open Source 6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details. 7 // License. See LICENSE.TXT for details.
8 // 8 //
9 //===----------------------------------------------------------------------===// 9 //===----------------------------------------------------------------------===//
10 10
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
109 109
110 // No type specified, must be invalid reference. 110 // No type specified, must be invalid reference.
111 if (Ty == 0) 111 if (Ty == 0)
112 return true; 112 return true;
113 113
114 // Create a placeholder, which will later be RAUW'd. 114 // Create a placeholder, which will later be RAUW'd.
115 ValuePtrs[Idx] = new Argument(Ty); 115 ValuePtrs[Idx] = new Argument(Ty);
116 return false; 116 return false;
117 } 117 }
118 118
119 namespace {
120 class NaClBitcodeErrorCategoryType : public std::error_category {
121 const char *name() const LLVM_NOEXCEPT override {
122 return "pnacl.bitcode";
123 }
124 std::string message(int IndexError) const override {
125 switch(static_cast<NaClBitcodeReader::ErrorType>(IndexError)) {
126 case NaClBitcodeReader::InvalidBBForInstruction:
127 return "No basic block for instruction";
128 case NaClBitcodeReader::InvalidBitstream:
129 return "Error in bitstream format";
130 case NaClBitcodeReader::InvalidConstantReference:
131 return "Bad constant reference";
132 case NaClBitcodeReader::InvalidMultipleBlocks:
133 return "Multiple blocks for a kind of block that should have only one";
134 case NaClBitcodeReader::InvalidRecord:
135 return "Record doesn't have expected size or structure";
136 case NaClBitcodeReader::InvalidType:
137 return "Invalid type in record";
138 case NaClBitcodeReader::InvalidTypeForValue:
139 return "Type of value in record incorrect";
140 case NaClBitcodeReader::InvalidValue:
141 return "Invalid value in record";
142 case NaClBitcodeReader::MalformedBlock:
143 return "Malformed block. Unable to advance over block";
144 case NaClBitcodeReader::NoFunctionInStream:
145 return "Unable to find function in bitcode stream.";
146 default:
147 return "Unknown bitsteam error";
JF 2014/12/02 00:49:04 I wouldn't put a default here: the compiler will w
Karl 2014/12/03 18:32:09 Done.
148 }
149 }
JF 2014/12/02 00:49:04 Put llvm_unreachable here instead (like BitcodeRea
Karl 2014/12/03 18:32:09 Done.
150 };
151 } // end of anonomous namespace.
152
153 const std::error_category &NaClBitcodeReader::BitcodeErrorCategory() {
154 static NaClBitcodeErrorCategoryType ErrCat;
JF 2014/12/02 00:49:03 BitcodeReader.cpp uses a ManagedStatic instead of
Karl 2014/12/03 18:32:09 Not in our local version. Waiting for merge?
155 return ErrCat;
156 }
157
119 Type *NaClBitcodeReader::getTypeByID(unsigned ID) { 158 Type *NaClBitcodeReader::getTypeByID(unsigned ID) {
120 // The type table size is always specified correctly. 159 // The type table size is always specified correctly.
121 if (ID >= TypeList.size()) 160 if (ID >= TypeList.size())
122 return 0; 161 return 0;
123 162
124 if (Type *Ty = TypeList[ID]) 163 if (Type *Ty = TypeList[ID])
125 return Ty; 164 return Ty;
126 165
127 // If we have a forward reference, the only possible case is when it is to a 166 // If we have a forward reference, the only possible case is when it is to a
128 // named struct. Just create a placeholder for now. 167 // named struct. Just create a placeholder for now.
129 return TypeList[ID] = StructType::create(Context); 168 return TypeList[ID] = StructType::create(Context);
130 } 169 }
131 170
132 171
133 //===----------------------------------------------------------------------===// 172 //===----------------------------------------------------------------------===//
134 // Functions for parsing blocks from the bitcode file 173 // Functions for parsing blocks from the bitcode file
135 //===----------------------------------------------------------------------===// 174 //===----------------------------------------------------------------------===//
136 175
137 176
138 bool NaClBitcodeReader::ParseTypeTable() { 177 std::error_code NaClBitcodeReader::Error(ErrorType E,
178 const std::string &Message) const {
179 if (Verbose)
180 errs() << "Error: " << Message << "\n";
181 return Error(E);
182 }
183
184 std::error_code NaClBitcodeReader::ParseTypeTable() {
139 DEBUG(dbgs() << "-> ParseTypeTable\n"); 185 DEBUG(dbgs() << "-> ParseTypeTable\n");
140 if (Stream.EnterSubBlock(naclbitc::TYPE_BLOCK_ID_NEW)) 186 if (Stream.EnterSubBlock(naclbitc::TYPE_BLOCK_ID_NEW))
141 return Error("Malformed block record"); 187 return Error(MalformedBlock, "Malformed block record");
jvoung (off chromium) 2014/12/01 23:23:49 similar, InvalidRecord or MalformedBlock?
Karl 2014/12/03 18:32:09 Changed to InvalidRecord.
142 188
143 bool result = ParseTypeTableBody(); 189 std::error_code result = ParseTypeTableBody();
144 if (!result) 190 if (!result)
145 DEBUG(dbgs() << "<- ParseTypeTable\n"); 191 DEBUG(dbgs() << "<- ParseTypeTable\n");
146 return result; 192 return result;
147 } 193 }
148 194
149 bool NaClBitcodeReader::ParseTypeTableBody() { 195 std::error_code NaClBitcodeReader::ParseTypeTableBody() {
150 if (!TypeList.empty()) 196 if (!TypeList.empty())
151 return Error("Multiple TYPE_BLOCKs found!"); 197 return Error(InvalidMultipleBlocks, "Multiple TYPE_BLOCKs found!");
152 198
153 SmallVector<uint64_t, 64> Record; 199 SmallVector<uint64_t, 64> Record;
154 unsigned NumRecords = 0; 200 unsigned NumRecords = 0;
155 201
156 // Read all the records for this type table. 202 // Read all the records for this type table.
157 while (1) { 203 while (1) {
158 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 204 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks();
159 205
160 switch (Entry.Kind) { 206 switch (Entry.Kind) {
161 case NaClBitstreamEntry::SubBlock: // Handled for us already. 207 case NaClBitstreamEntry::SubBlock: // Handled for us already.
162 case NaClBitstreamEntry::Error: 208 case NaClBitstreamEntry::Error:
163 Error("Error in the type table block"); 209 return Error(MalformedBlock, "Error in the type table block");
164 return true;
165 case NaClBitstreamEntry::EndBlock: 210 case NaClBitstreamEntry::EndBlock:
166 if (NumRecords != TypeList.size()) 211 if (NumRecords != TypeList.size())
167 return Error("Invalid type forward reference in TYPE_BLOCK"); 212 return Error(MalformedBlock,
168 return false; 213 "Invalid type forward reference in TYPE_BLOCK");
214 return std::error_code();
169 case NaClBitstreamEntry::Record: 215 case NaClBitstreamEntry::Record:
170 // The interesting case. 216 // The interesting case.
171 break; 217 break;
172 } 218 }
173 219
174 // Read a record. 220 // Read a record.
175 Record.clear(); 221 Record.clear();
176 Type *ResultTy = 0; 222 Type *ResultTy = 0;
177 unsigned TypeCode = Stream.readRecord(Entry.ID, Record); 223 unsigned TypeCode = Stream.readRecord(Entry.ID, Record);
178 switch (TypeCode) { 224 switch (TypeCode) {
179 default: { 225 default: {
180 std::string Message; 226 std::string Message;
181 raw_string_ostream StrM(Message); 227 raw_string_ostream StrM(Message);
182 StrM << "Unknown type code in type table: " << TypeCode; 228 StrM << "Unknown type code in type table: " << TypeCode;
183 StrM.flush(); 229 StrM.flush();
184 return Error(Message); 230 return Error(InvalidValue, Message);
185 } 231 }
186 232
187 case naclbitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 233 case naclbitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
188 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 234 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
189 // type list. This allows us to reserve space. 235 // type list. This allows us to reserve space.
190 if (Record.size() != 1) 236 if (Record.size() != 1)
191 return Error("Invalid TYPE_CODE_NUMENTRY record"); 237 return Error(InvalidRecord, "Invalid TYPE_CODE_NUMENTRY record");
192 TypeList.resize(Record[0]); 238 TypeList.resize(Record[0]);
193 // No type was defined, skip the checks that follow the switch. 239 // No type was defined, skip the checks that follow the switch.
194 continue; 240 continue;
195 241
196 case naclbitc::TYPE_CODE_VOID: // VOID 242 case naclbitc::TYPE_CODE_VOID: // VOID
197 if (Record.size() != 0) 243 if (Record.size() != 0)
198 return Error("Invalid TYPE_CODE_VOID record"); 244 return Error(InvalidRecord, "Invalid TYPE_CODE_VOID record");
199 ResultTy = Type::getVoidTy(Context); 245 ResultTy = Type::getVoidTy(Context);
200 break; 246 break;
201 247
202 case naclbitc::TYPE_CODE_FLOAT: // FLOAT 248 case naclbitc::TYPE_CODE_FLOAT: // FLOAT
203 if (Record.size() != 0) 249 if (Record.size() != 0)
204 return Error("Invalid TYPE_CODE_FLOAT record"); 250 return Error(InvalidRecord, "Invalid TYPE_CODE_FLOAT record");
205 ResultTy = Type::getFloatTy(Context); 251 ResultTy = Type::getFloatTy(Context);
206 break; 252 break;
207 253
208 case naclbitc::TYPE_CODE_DOUBLE: // DOUBLE 254 case naclbitc::TYPE_CODE_DOUBLE: // DOUBLE
209 if (Record.size() != 0) 255 if (Record.size() != 0)
210 return Error("Invalid TYPE_CODE_DOUBLE record"); 256 return Error(InvalidRecord, "Invalid TYPE_CODE_DOUBLE record");
211 ResultTy = Type::getDoubleTy(Context); 257 ResultTy = Type::getDoubleTy(Context);
212 break; 258 break;
213 259
214 case naclbitc::TYPE_CODE_INTEGER: // INTEGER: [width] 260 case naclbitc::TYPE_CODE_INTEGER: // INTEGER: [width]
215 if (Record.size() != 1) 261 if (Record.size() != 1)
216 return Error("Invalid TYPE_CODE_INTEGER record"); 262 return Error(InvalidRecord, "Invalid TYPE_CODE_INTEGER record");
217 ResultTy = IntegerType::get(Context, Record[0]); 263 ResultTy = IntegerType::get(Context, Record[0]);
218 break; 264 break;
219 265
220 case naclbitc::TYPE_CODE_FUNCTION: { 266 case naclbitc::TYPE_CODE_FUNCTION: {
221 // FUNCTION: [vararg, retty, paramty x N] 267 // FUNCTION: [vararg, retty, paramty x N]
222 if (Record.size() < 2) 268 if (Record.size() < 2)
223 return Error("Invalid TYPE_CODE_FUNCTION record"); 269 return Error(InvalidRecord, "Invalid TYPE_CODE_FUNCTION record");
224 SmallVector<Type *, 8> ArgTys; 270 SmallVector<Type *, 8> ArgTys;
225 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 271 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
226 if (Type *T = getTypeByID(Record[i])) 272 if (Type *T = getTypeByID(Record[i]))
227 ArgTys.push_back(T); 273 ArgTys.push_back(T);
228 else 274 else
229 break; 275 break;
230 } 276 }
231 277
232 ResultTy = getTypeByID(Record[1]); 278 ResultTy = getTypeByID(Record[1]);
233 if (ResultTy == 0 || ArgTys.size() < Record.size() - 2) 279 if (ResultTy == 0 || ArgTys.size() < Record.size() - 2)
234 return Error("invalid type in function type"); 280 return Error(InvalidType, "invalid type in function type");
235 281
236 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 282 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
237 break; 283 break;
238 } 284 }
239 case naclbitc::TYPE_CODE_VECTOR: { // VECTOR: [numelts, eltty] 285 case naclbitc::TYPE_CODE_VECTOR: { // VECTOR: [numelts, eltty]
240 if (Record.size() != 2) 286 if (Record.size() != 2)
241 return Error("Invalid VECTOR type record"); 287 return Error(InvalidRecord, "Invalid VECTOR type record");
242 if ((ResultTy = getTypeByID(Record[1]))) 288 if ((ResultTy = getTypeByID(Record[1])))
243 ResultTy = VectorType::get(ResultTy, Record[0]); 289 ResultTy = VectorType::get(ResultTy, Record[0]);
244 else 290 else
245 return Error("invalid type in vector type"); 291 return Error(InvalidType, "invalid type in vector type");
246 break; 292 break;
247 } 293 }
248 } 294 }
249 295
250 if (NumRecords >= TypeList.size()) 296 if (NumRecords >= TypeList.size())
251 return Error("invalid TYPE table"); 297 return Error(MalformedBlock, "invalid TYPE table");
252 assert(ResultTy && "Didn't read a type?"); 298 assert(ResultTy && "Didn't read a type?");
253 assert(TypeList[NumRecords] == 0 && "Already read type?"); 299 assert(TypeList[NumRecords] == 0 && "Already read type?");
254 TypeList[NumRecords++] = ResultTy; 300 TypeList[NumRecords++] = ResultTy;
255 } 301 }
302 return std::error_code();
256 } 303 }
257 304
258 namespace { 305 namespace {
259 306
260 // Class to process globals in two passes. In the first pass, build 307 // Class to process globals in two passes. In the first pass, build
261 // the corresponding global variables with no initializers. In the 308 // the corresponding global variables with no initializers. In the
262 // second pass, add initializers. The purpose of putting off 309 // second pass, add initializers. The purpose of putting off
263 // initializers is to make sure that we don't need to generate 310 // initializers is to make sure that we don't need to generate
264 // placeholders for relocation records, and the corresponding cost 311 // placeholders for relocation records, and the corresponding cost
265 // of duplicating initializers when these placeholders are replaced. 312 // of duplicating initializers when these placeholders are replaced.
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
303 Module *TheModule) 350 Module *TheModule)
304 : Reader(Reader), 351 : Reader(Reader),
305 ValueList(ValueList), 352 ValueList(ValueList),
306 Stream(Stream), 353 Stream(Stream),
307 Context(Context), 354 Context(Context),
308 TheModule(TheModule), 355 TheModule(TheModule),
309 FirstValueNo(ValueList.size()), 356 FirstValueNo(ValueList.size()),
310 NumGlobals(0), 357 NumGlobals(0),
311 StartBit(Stream.GetCurrentBitNo()) {} 358 StartBit(Stream.GetCurrentBitNo()) {}
312 359
313 bool GenerateGlobalVarsPass() { 360 std::error_code GenerateGlobalVarsPass() {
314 InitPass(); 361 InitPass();
315 362
316 // The type for the initializer of the global variable. 363 // The type for the initializer of the global variable.
317 SmallVector<Type*, 10> VarType; 364 SmallVector<Type*, 10> VarType;
318 // The alignment value defined for the global variable. 365 // The alignment value defined for the global variable.
319 unsigned VarAlignment = 0; 366 unsigned VarAlignment = 0;
320 // True if the variable is read-only. 367 // True if the variable is read-only.
321 bool VarIsConstant = false; 368 bool VarIsConstant = false;
322 369
323 // Read all records to build global variables without initializers. 370 // Read all records to build global variables without initializers.
324 while (1) { 371 while (1) {
325 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks( 372 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(
326 NaClBitstreamCursor::AF_DontPopBlockAtEnd); 373 NaClBitstreamCursor::AF_DontPopBlockAtEnd);
327 switch (Entry.Kind) { 374 switch (Entry.Kind) {
328 case NaClBitstreamEntry::SubBlock: 375 case NaClBitstreamEntry::SubBlock:
329 case NaClBitstreamEntry::Error: 376 case NaClBitstreamEntry::Error:
330 return Reader.Error("Error in the global vars block"); 377 return Reader.Error(NaClBitcodeReader::MalformedBlock,
378 "Error in the global vars block");
331 case NaClBitstreamEntry::EndBlock: 379 case NaClBitstreamEntry::EndBlock:
332 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo)) 380 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo))
333 return Reader.Error("Error in the global vars block"); 381 return Reader.Error(NaClBitcodeReader::MalformedBlock,
334 return false; 382 "Error in the global vars block");
383 return std::error_code();
335 case NaClBitstreamEntry::Record: 384 case NaClBitstreamEntry::Record:
336 // The interesting case. 385 // The interesting case.
337 break; 386 break;
338 } 387 }
339 388
340 // Read a record. 389 // Read a record.
341 Record.clear(); 390 Record.clear();
342 unsigned Bitcode = Stream.readRecord(Entry.ID, Record); 391 unsigned Bitcode = Stream.readRecord(Entry.ID, Record);
343 switch (Bitcode) { 392 switch (Bitcode) {
344 default: return Reader.Error("Unknown global variable entry"); 393 default:
394 return Reader.Error(NaClBitcodeReader::InvalidValue,
395 "Unknown global variable entry");
345 case naclbitc::GLOBALVAR_VAR: 396 case naclbitc::GLOBALVAR_VAR:
346 // Start the definition of a global variable. 397 // Start the definition of a global variable.
347 if (ProcessingGlobal || Record.size() != 2) 398 if (ProcessingGlobal || Record.size() != 2)
348 return Reader.Error("Bad GLOBALVAR_VAR record"); 399 return Reader.Error(NaClBitcodeReader::InvalidRecord,
400 "Bad GLOBALVAR_VAR record");
349 ProcessingGlobal = true; 401 ProcessingGlobal = true;
350 VarAlignment = (1 << Record[0]) >> 1; 402 VarAlignment = (1 << Record[0]) >> 1;
351 VarIsConstant = Record[1] != 0; 403 VarIsConstant = Record[1] != 0;
352 // Assume (by default) there is a single initializer. 404 // Assume (by default) there is a single initializer.
353 VarInitializersNeeded = 1; 405 VarInitializersNeeded = 1;
354 break; 406 break;
355 case naclbitc::GLOBALVAR_COMPOUND: 407 case naclbitc::GLOBALVAR_COMPOUND:
356 // Global variable has multiple initializers. Changes the 408 // Global variable has multiple initializers. Changes the
357 // default number of initializers to the given value in 409 // default number of initializers to the given value in
358 // Record[0]. 410 // Record[0].
359 if (!ProcessingGlobal || !VarType.empty() || 411 if (!ProcessingGlobal || !VarType.empty() ||
360 VarInitializersNeeded != 1 || Record.size() != 1) 412 VarInitializersNeeded != 1 || Record.size() != 1)
361 return Reader.Error("Bad GLOBALVAR_COMPOUND record"); 413 return Reader.Error(NaClBitcodeReader::InvalidRecord,
414 "Bad GLOBALVAR_COMPOUND record");
362 VarInitializersNeeded = Record[0]; 415 VarInitializersNeeded = Record[0];
363 break; 416 break;
364 case naclbitc::GLOBALVAR_ZEROFILL: { 417 case naclbitc::GLOBALVAR_ZEROFILL: {
365 // Define a type that defines a sequence of zero-filled bytes. 418 // Define a type that defines a sequence of zero-filled bytes.
366 if (!ProcessingGlobal || Record.size() != 1) 419 if (!ProcessingGlobal || Record.size() != 1)
367 return Reader.Error("Bad GLOBALVAR_ZEROFILL record"); 420 return Reader.Error(NaClBitcodeReader::InvalidRecord,
421 "Bad GLOBALVAR_ZEROFILL record");
368 VarType.push_back(ArrayType::get( 422 VarType.push_back(ArrayType::get(
369 Type::getInt8Ty(Context), Record[0])); 423 Type::getInt8Ty(Context), Record[0]));
370 break; 424 break;
371 } 425 }
372 case naclbitc::GLOBALVAR_DATA: { 426 case naclbitc::GLOBALVAR_DATA: {
373 // Defines a type defined by a sequence of byte values. 427 // Defines a type defined by a sequence of byte values.
374 if (!ProcessingGlobal || Record.size() < 1) 428 if (!ProcessingGlobal || Record.size() < 1)
375 return Reader.Error("Bad GLOBALVAR_DATA record"); 429 return Reader.Error(NaClBitcodeReader::InvalidRecord,
430 "Bad GLOBALVAR_DATA record");
376 VarType.push_back(ArrayType::get( 431 VarType.push_back(ArrayType::get(
377 Type::getInt8Ty(Context), Record.size())); 432 Type::getInt8Ty(Context), Record.size()));
378 break; 433 break;
379 } 434 }
380 case naclbitc::GLOBALVAR_RELOC: { 435 case naclbitc::GLOBALVAR_RELOC: {
381 // Define a relocation initializer type. 436 // Define a relocation initializer type.
382 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2) 437 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2)
383 return Reader.Error("Bad GLOBALVAR_RELOC record"); 438 return Reader.Error(NaClBitcodeReader::InvalidRecord,
439 "Bad GLOBALVAR_RELOC record");
384 VarType.push_back(IntegerType::get(Context, 32)); 440 VarType.push_back(IntegerType::get(Context, 32));
385 break; 441 break;
386 } 442 }
387 case naclbitc::GLOBALVAR_COUNT: 443 case naclbitc::GLOBALVAR_COUNT:
388 if (Record.size() != 1 || NumGlobals != 0) 444 if (Record.size() != 1 || NumGlobals != 0)
389 return Reader.Error("Invalid global count record"); 445 return Reader.Error(NaClBitcodeReader::InvalidRecord,
446 "Invalid global count record");
390 NumGlobals = Record[0]; 447 NumGlobals = Record[0];
391 break; 448 break;
392 } 449 }
393 450
394 // If more initializers needed for global variable, continue processing. 451 // If more initializers needed for global variable, continue processing.
395 if (!ProcessingGlobal || VarType.size() < VarInitializersNeeded) 452 if (!ProcessingGlobal || VarType.size() < VarInitializersNeeded)
396 continue; 453 continue;
397 454
398 Type *Ty = 0; 455 Type *Ty = 0;
399 switch (VarType.size()) { 456 switch (VarType.size()) {
400 case 0: 457 case 0:
401 return Reader.Error( 458 return Reader.Error(
459 NaClBitcodeReader::InvalidRecord,
402 "No initializer for global variable in global vars block"); 460 "No initializer for global variable in global vars block");
403 case 1: 461 case 1:
404 Ty = VarType[0]; 462 Ty = VarType[0];
405 break; 463 break;
406 default: 464 default:
407 Ty = StructType::get(Context, VarType, true); 465 Ty = StructType::get(Context, VarType, true);
408 break; 466 break;
409 } 467 }
410 GlobalVariable *GV = new GlobalVariable( 468 GlobalVariable *GV = new GlobalVariable(
411 *TheModule, Ty, VarIsConstant, 469 *TheModule, Ty, VarIsConstant,
412 GlobalValue::InternalLinkage, NULL, ""); 470 GlobalValue::InternalLinkage, NULL, "");
413 GV->setAlignment(VarAlignment); 471 GV->setAlignment(VarAlignment);
414 ValueList.AssignValue(GV, NextValueNo); 472 ValueList.AssignValue(GV, NextValueNo);
415 ++NextValueNo; 473 ++NextValueNo;
416 ProcessingGlobal = false; 474 ProcessingGlobal = false;
417 VarAlignment = 0; 475 VarAlignment = 0;
418 VarIsConstant = false; 476 VarIsConstant = false;
419 VarInitializersNeeded = 0; 477 VarInitializersNeeded = 0;
420 VarType.clear(); 478 VarType.clear();
421 } 479 }
480 return std::error_code();
422 } 481 }
423 482
424 bool GenerateGlobalVarInitsPass() { 483 std::error_code GenerateGlobalVarInitsPass() {
425 InitPass(); 484 InitPass();
426 // The initializer for the global variable. 485 // The initializer for the global variable.
427 SmallVector<Constant *, 10> VarInit; 486 SmallVector<Constant *, 10> VarInit;
428 487
429 while (1) { 488 while (1) {
430 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks( 489 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(
431 NaClBitstreamCursor::AF_DontAutoprocessAbbrevs); 490 NaClBitstreamCursor::AF_DontAutoprocessAbbrevs);
432 switch (Entry.Kind) { 491 switch (Entry.Kind) {
433 case NaClBitstreamEntry::SubBlock: 492 case NaClBitstreamEntry::SubBlock:
434 case NaClBitstreamEntry::Error: 493 case NaClBitstreamEntry::Error:
435 return Reader.Error("Error in the global vars block"); 494 return Reader.Error(NaClBitcodeReader::MalformedBlock,
495 "Error in the global vars block");
436 case NaClBitstreamEntry::EndBlock: 496 case NaClBitstreamEntry::EndBlock:
437 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo)) 497 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo))
438 return Reader.Error("Error in the global vars block"); 498 return Reader.Error(NaClBitcodeReader::MalformedBlock,
439 return false; 499 "Error in the global vars block");
500 return std::error_code();
440 case NaClBitstreamEntry::Record: 501 case NaClBitstreamEntry::Record:
441 if (Entry.ID == naclbitc::DEFINE_ABBREV) { 502 if (Entry.ID == naclbitc::DEFINE_ABBREV) {
442 Stream.SkipAbbrevRecord(); 503 Stream.SkipAbbrevRecord();
443 continue; 504 continue;
444 } 505 }
445 // The interesting case. 506 // The interesting case.
446 break; 507 break;
447 default: 508 default:
448 return Reader.Error("Unexpected record"); 509 return Reader.Error(NaClBitcodeReader::InvalidRecord,
510 "Unexpected record");
449 } 511 }
450 512
451 // Read a record. 513 // Read a record.
452 Record.clear(); 514 Record.clear();
453 unsigned Bitcode = Stream.readRecord(Entry.ID, Record); 515 unsigned Bitcode = Stream.readRecord(Entry.ID, Record);
454 switch (Bitcode) { 516 switch (Bitcode) {
455 default: return Reader.Error("Unknown global variable entry 2"); 517 default:
518 return Reader.Error(NaClBitcodeReader::InvalidValue,
519 "Unknown global variable entry 2");
456 case naclbitc::GLOBALVAR_VAR: 520 case naclbitc::GLOBALVAR_VAR:
457 // Start the definition of a global variable. 521 // Start the definition of a global variable.
458 ProcessingGlobal = true; 522 ProcessingGlobal = true;
459 // Assume (by default) there is a single initializer. 523 // Assume (by default) there is a single initializer.
460 VarInitializersNeeded = 1; 524 VarInitializersNeeded = 1;
461 break; 525 break;
462 case naclbitc::GLOBALVAR_COMPOUND: 526 case naclbitc::GLOBALVAR_COMPOUND:
463 // Global variable has multiple initializers. Changes the 527 // Global variable has multiple initializers. Changes the
464 // default number of initializers to the given value in 528 // default number of initializers to the given value in
465 // Record[0]. 529 // Record[0].
466 if (!ProcessingGlobal || !VarInit.empty() || 530 if (!ProcessingGlobal || !VarInit.empty() ||
467 VarInitializersNeeded != 1 || Record.size() != 1) 531 VarInitializersNeeded != 1 || Record.size() != 1)
468 return Reader.Error("Bad GLOBALVAR_COMPOUND record"); 532 return Reader.Error(NaClBitcodeReader::InvalidRecord,
533 "Bad GLOBALVAR_COMPOUND record");
469 VarInitializersNeeded = Record[0]; 534 VarInitializersNeeded = Record[0];
470 break; 535 break;
471 case naclbitc::GLOBALVAR_ZEROFILL: { 536 case naclbitc::GLOBALVAR_ZEROFILL: {
472 // Define an initializer that defines a sequence of zero-filled bytes. 537 // Define an initializer that defines a sequence of zero-filled bytes.
473 if (!ProcessingGlobal || Record.size() != 1) 538 if (!ProcessingGlobal || Record.size() != 1)
474 return Reader.Error("Bad GLOBALVAR_ZEROFILL record"); 539 return Reader.Error(NaClBitcodeReader::InvalidRecord,
540 "Bad GLOBALVAR_ZEROFILL record");
475 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), 541 Type *Ty = ArrayType::get(Type::getInt8Ty(Context),
476 Record[0]); 542 Record[0]);
477 Constant *Zero = ConstantAggregateZero::get(Ty); 543 Constant *Zero = ConstantAggregateZero::get(Ty);
478 VarInit.push_back(Zero); 544 VarInit.push_back(Zero);
479 break; 545 break;
480 } 546 }
481 case naclbitc::GLOBALVAR_DATA: { 547 case naclbitc::GLOBALVAR_DATA: {
482 // Defines an initializer defined by a sequence of byte values. 548 // Defines an initializer defined by a sequence of byte values.
483 if (!ProcessingGlobal || Record.size() < 1) 549 if (!ProcessingGlobal || Record.size() < 1)
484 return Reader.Error("Bad GLOBALVAR_DATA record"); 550 return Reader.Error(NaClBitcodeReader::InvalidRecord,
551 "Bad GLOBALVAR_DATA record");
485 unsigned Size = Record.size(); 552 unsigned Size = Record.size();
486 uint8_t *Buf = new uint8_t[Size]; 553 uint8_t *Buf = new uint8_t[Size];
487 assert(Buf); 554 assert(Buf);
488 for (unsigned i = 0; i < Size; ++i) 555 for (unsigned i = 0; i < Size; ++i)
489 Buf[i] = Record[i]; 556 Buf[i] = Record[i];
490 Constant *Init = ConstantDataArray::get( 557 Constant *Init = ConstantDataArray::get(
491 Context, ArrayRef<uint8_t>(Buf, Buf + Size)); 558 Context, ArrayRef<uint8_t>(Buf, Buf + Size));
492 VarInit.push_back(Init); 559 VarInit.push_back(Init);
493 delete[] Buf; 560 delete[] Buf;
494 break; 561 break;
495 } 562 }
496 case naclbitc::GLOBALVAR_RELOC: { 563 case naclbitc::GLOBALVAR_RELOC: {
497 // Define a relocation initializer. 564 // Define a relocation initializer.
498 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2) 565 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2)
499 return Reader.Error("Bad GLOBALVAR_RELOC record"); 566 return Reader.Error(NaClBitcodeReader::InvalidRecord,
567 "Bad GLOBALVAR_RELOC record");
500 Constant *BaseVal = cast<Constant>(ValueList[Record[0]]); 568 Constant *BaseVal = cast<Constant>(ValueList[Record[0]]);
501 Type *IntPtrType = IntegerType::get(Context, 32); 569 Type *IntPtrType = IntegerType::get(Context, 32);
502 Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType); 570 Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType);
503 if (Record.size() == 2) { 571 if (Record.size() == 2) {
504 uint32_t Addend = Record[1]; 572 uint32_t Addend = Record[1];
505 Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType, 573 Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType,
506 Addend)); 574 Addend));
507 } 575 }
508 VarInit.push_back(Val); 576 VarInit.push_back(Val);
509 break; 577 break;
510 } 578 }
511 case naclbitc::GLOBALVAR_COUNT: 579 case naclbitc::GLOBALVAR_COUNT:
512 if (Record.size() != 1) 580 if (Record.size() != 1)
513 return Reader.Error("Invalid global count record"); 581 return Reader.Error(NaClBitcodeReader::InvalidRecord,
582 "Invalid global count record");
514 // Note: NumGlobals should have been set in GenerateGlobalVarsPass. 583 // Note: NumGlobals should have been set in GenerateGlobalVarsPass.
515 // Fail if methods are called in wrong order. 584 // Fail if methods are called in wrong order.
516 assert(NumGlobals == Record[0]); 585 assert(NumGlobals == Record[0]);
517 break; 586 break;
518 } 587 }
519 588
520 // If more initializers needed for global variable, continue processing. 589 // If more initializers needed for global variable, continue processing.
521 if (!ProcessingGlobal || VarInit.size() < VarInitializersNeeded) 590 if (!ProcessingGlobal || VarInit.size() < VarInitializersNeeded)
522 continue; 591 continue;
523 592
524 Constant *Init = 0; 593 Constant *Init = 0;
525 switch (VarInit.size()) { 594 switch (VarInit.size()) {
526 case 0: 595 case 0:
527 return Reader.Error( 596 return Reader.Error(NaClBitcodeReader::InvalidRecord,
528 "No initializer for global variable in global vars block"); 597 "No initializer for global variable in global vars block");
529 case 1: 598 case 1:
530 Init = VarInit[0]; 599 Init = VarInit[0];
531 break; 600 break;
532 default: 601 default:
533 Init = ConstantStruct::getAnon(Context, VarInit, true); 602 Init = ConstantStruct::getAnon(Context, VarInit, true);
534 break; 603 break;
535 } 604 }
536 cast<GlobalVariable>(ValueList[NextValueNo])->setInitializer(Init); 605 cast<GlobalVariable>(ValueList[NextValueNo])->setInitializer(Init);
537 ++NextValueNo; 606 ++NextValueNo;
538 ProcessingGlobal = false; 607 ProcessingGlobal = false;
539 VarInitializersNeeded = 0; 608 VarInitializersNeeded = 0;
540 VarInit.clear(); 609 VarInit.clear();
541 } 610 }
611 return std::error_code();
542 } 612 }
543 }; 613 };
544 614
545 } // End anonymous namespace. 615 } // End anonymous namespace.
546 616
547 bool NaClBitcodeReader::ParseGlobalVars() { 617 std::error_code NaClBitcodeReader::ParseGlobalVars() {
548 if (Stream.EnterSubBlock(naclbitc::GLOBALVAR_BLOCK_ID)) 618 if (Stream.EnterSubBlock(naclbitc::GLOBALVAR_BLOCK_ID))
549 return Error("Malformed block record"); 619 return Error(MalformedBlock, "Malformed block record");
jvoung (off chromium) 2014/12/01 23:23:49 Sometimes errors in EnterSubBlock are InvalidRecor
Karl 2014/12/03 18:32:09 Done.
550 620
551 ParseGlobalsHandler PassHandler(*this, ValueList, Stream, Context, TheModule); 621 ParseGlobalsHandler PassHandler(*this, ValueList, Stream, Context, TheModule);
552 if (PassHandler.GenerateGlobalVarsPass()) return true; 622 if (std::error_code EC = PassHandler.GenerateGlobalVarsPass())
623 return EC;
553 return PassHandler.GenerateGlobalVarInitsPass(); 624 return PassHandler.GenerateGlobalVarInitsPass();
554 } 625 }
555 626
556 bool NaClBitcodeReader::ParseValueSymbolTable() { 627 std::error_code NaClBitcodeReader::ParseValueSymbolTable() {
557 DEBUG(dbgs() << "-> ParseValueSymbolTable\n"); 628 DEBUG(dbgs() << "-> ParseValueSymbolTable\n");
558 if (Stream.EnterSubBlock(naclbitc::VALUE_SYMTAB_BLOCK_ID)) 629 if (Stream.EnterSubBlock(naclbitc::VALUE_SYMTAB_BLOCK_ID))
559 return Error("Malformed block record"); 630 return Error(InvalidRecord, "Malformed block record");
560 631
561 SmallVector<uint64_t, 64> Record; 632 SmallVector<uint64_t, 64> Record;
562 633
563 // Read all the records for this value table. 634 // Read all the records for this value table.
564 SmallString<128> ValueName; 635 SmallString<128> ValueName;
565 while (1) { 636 while (1) {
566 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 637 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks();
567 638
568 switch (Entry.Kind) { 639 switch (Entry.Kind) {
569 case NaClBitstreamEntry::SubBlock: // Handled for us already. 640 case NaClBitstreamEntry::SubBlock: // Handled for us already.
570 case NaClBitstreamEntry::Error: 641 case NaClBitstreamEntry::Error:
571 return Error("malformed value symbol table block"); 642 return Error(MalformedBlock, "malformed value symbol table block");
572 case NaClBitstreamEntry::EndBlock: 643 case NaClBitstreamEntry::EndBlock:
573 DEBUG(dbgs() << "<- ParseValueSymbolTable\n"); 644 DEBUG(dbgs() << "<- ParseValueSymbolTable\n");
574 return false; 645 return std::error_code();
575 case NaClBitstreamEntry::Record: 646 case NaClBitstreamEntry::Record:
576 // The interesting case. 647 // The interesting case.
577 break; 648 break;
578 } 649 }
579 650
580 // Read a record. 651 // Read a record.
581 Record.clear(); 652 Record.clear();
582 switch (Stream.readRecord(Entry.ID, Record)) { 653 switch (Stream.readRecord(Entry.ID, Record)) {
583 default: // Default behavior: unknown type. 654 default: // Default behavior: unknown type.
584 break; 655 break;
585 case naclbitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 656 case naclbitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
586 if (ConvertToString(Record, 1, ValueName)) 657 if (ConvertToString(Record, 1, ValueName))
587 return Error("Invalid VST_ENTRY record"); 658 return Error(InvalidRecord, "Invalid VST_ENTRY record");
588 unsigned ValueID = Record[0]; 659 unsigned ValueID = Record[0];
589 if (ValueID >= ValueList.size()) 660 if (ValueID >= ValueList.size())
590 return Error("Invalid Value ID in VST_ENTRY record"); 661 return Error(InvalidValue, "Invalid Value ID in VST_ENTRY record");
591 Value *V = ValueList[ValueID]; 662 Value *V = ValueList[ValueID];
592 663
593 V->setName(StringRef(ValueName.data(), ValueName.size())); 664 V->setName(StringRef(ValueName.data(), ValueName.size()));
594 ValueName.clear(); 665 ValueName.clear();
595 break; 666 break;
596 } 667 }
597 case naclbitc::VST_CODE_BBENTRY: { 668 case naclbitc::VST_CODE_BBENTRY: {
598 if (ConvertToString(Record, 1, ValueName)) 669 if (ConvertToString(Record, 1, ValueName))
599 return Error("Invalid VST_BBENTRY record"); 670 return Error(InvalidRecord, "Invalid VST_BBENTRY record");
600 BasicBlock *BB = getBasicBlock(Record[0]); 671 BasicBlock *BB = getBasicBlock(Record[0]);
601 if (BB == 0) 672 if (BB == 0)
602 return Error("Invalid BB ID in VST_BBENTRY record"); 673 return Error(InvalidValue, "Invalid BB ID in VST_BBENTRY record");
603 674
604 BB->setName(StringRef(ValueName.data(), ValueName.size())); 675 BB->setName(StringRef(ValueName.data(), ValueName.size()));
605 ValueName.clear(); 676 ValueName.clear();
606 break; 677 break;
607 } 678 }
608 } 679 }
609 } 680 }
610 } 681 }
611 682
612 bool NaClBitcodeReader::ParseConstants() { 683 std::error_code NaClBitcodeReader::ParseConstants() {
613 DEBUG(dbgs() << "-> ParseConstants\n"); 684 DEBUG(dbgs() << "-> ParseConstants\n");
614 if (Stream.EnterSubBlock(naclbitc::CONSTANTS_BLOCK_ID)) 685 if (Stream.EnterSubBlock(naclbitc::CONSTANTS_BLOCK_ID))
615 return Error("Malformed block record"); 686 return Error(InvalidRecord, "Malformed block record");
616 687
617 SmallVector<uint64_t, 64> Record; 688 SmallVector<uint64_t, 64> Record;
618 689
619 // Read all the records for this value table. 690 // Read all the records for this value table.
620 Type *CurTy = Type::getInt32Ty(Context); 691 Type *CurTy = Type::getInt32Ty(Context);
621 unsigned NextCstNo = ValueList.size(); 692 unsigned NextCstNo = ValueList.size();
622 while (1) { 693 while (1) {
623 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 694 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks();
624 695
625 switch (Entry.Kind) { 696 switch (Entry.Kind) {
626 case NaClBitstreamEntry::SubBlock: // Handled for us already. 697 case NaClBitstreamEntry::SubBlock: // Handled for us already.
627 case NaClBitstreamEntry::Error: 698 case NaClBitstreamEntry::Error:
628 return Error("malformed block record in AST file"); 699 return Error(MalformedBlock, "malformed block record in AST file");
629 case NaClBitstreamEntry::EndBlock: 700 case NaClBitstreamEntry::EndBlock:
630 if (NextCstNo != ValueList.size()) 701 if (NextCstNo != ValueList.size())
631 return Error("Invalid constant reference!"); 702 return Error(InvalidConstantReference,
703 "Invalid constant reference!");
632 DEBUG(dbgs() << "<- ParseConstants\n"); 704 DEBUG(dbgs() << "<- ParseConstants\n");
633 return false; 705 return std::error_code();
634 case NaClBitstreamEntry::Record: 706 case NaClBitstreamEntry::Record:
635 // The interesting case. 707 // The interesting case.
636 break; 708 break;
637 } 709 }
638 710
639 // Read a record. 711 // Read a record.
640 Record.clear(); 712 Record.clear();
641 Value *V = 0; 713 Value *V = 0;
642 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 714 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
643 switch (BitCode) { 715 switch (BitCode) {
644 default: { 716 default: {
645 std::string Message; 717 std::string Message;
646 raw_string_ostream StrM(Message); 718 raw_string_ostream StrM(Message);
647 StrM << "Invalid Constant code: " << BitCode; 719 StrM << "Invalid Constant code: " << BitCode;
648 StrM.flush(); 720 StrM.flush();
649 return Error(Message); 721 return Error(InvalidValue, Message);
650 } 722 }
651 case naclbitc::CST_CODE_UNDEF: // UNDEF 723 case naclbitc::CST_CODE_UNDEF: // UNDEF
652 V = UndefValue::get(CurTy); 724 V = UndefValue::get(CurTy);
653 break; 725 break;
654 case naclbitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 726 case naclbitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
655 if (Record.empty()) 727 if (Record.empty())
656 return Error("Malformed CST_SETTYPE record"); 728 return Error(NaClBitcodeReader::InvalidRecord,
729 "Malformed CST_SETTYPE record");
657 if (Record[0] >= TypeList.size()) 730 if (Record[0] >= TypeList.size())
658 return Error("Invalid Type ID in CST_SETTYPE record"); 731 return Error(NaClBitcodeReader::InvalidType,
732 "Invalid Type ID in CST_SETTYPE record");
659 CurTy = TypeList[Record[0]]; 733 CurTy = TypeList[Record[0]];
660 continue; // Skip the ValueList manipulation. 734 continue; // Skip the ValueList manipulation.
661 case naclbitc::CST_CODE_INTEGER: // INTEGER: [intval] 735 case naclbitc::CST_CODE_INTEGER: // INTEGER: [intval]
662 if (!CurTy->isIntegerTy() || Record.empty()) 736 if (!CurTy->isIntegerTy() || Record.empty())
663 return Error("Invalid CST_INTEGER record"); 737 return Error(InvalidRecord, "Invalid CST_INTEGER record");
664 V = ConstantInt::get(CurTy, NaClDecodeSignRotatedValue(Record[0])); 738 V = ConstantInt::get(CurTy, NaClDecodeSignRotatedValue(Record[0]));
665 break; 739 break;
666 case naclbitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 740 case naclbitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
667 if (Record.empty()) 741 if (Record.empty())
668 return Error("Invalid FLOAT record"); 742 return Error(NaClBitcodeReader::InvalidRecord, "Invalid FLOAT record");
669 if (CurTy->isFloatTy()) 743 if (CurTy->isFloatTy())
670 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 744 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
671 APInt(32, (uint32_t)Record[0]))); 745 APInt(32, (uint32_t)Record[0])));
672 else if (CurTy->isDoubleTy()) 746 else if (CurTy->isDoubleTy())
673 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 747 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
674 APInt(64, Record[0]))); 748 APInt(64, Record[0])));
675 else 749 else
676 return Error("Unknown type for FLOAT record"); 750 return Error(NaClBitcodeReader::InvalidRecord,
751 "Unknown type for FLOAT record");
677 break; 752 break;
678 } 753 }
679 } 754 }
680 755
681 ValueList.AssignValue(V, NextCstNo); 756 ValueList.AssignValue(V, NextCstNo);
682 ++NextCstNo; 757 ++NextCstNo;
683 } 758 }
759 return std::error_code();
684 } 760 }
685 761
686 /// RememberAndSkipFunctionBody - When we see the block for a function body, 762 /// RememberAndSkipFunctionBody - When we see the block for a function body,
687 /// remember where it is and then skip it. This lets us lazily deserialize the 763 /// remember where it is and then skip it. This lets us lazily deserialize the
688 /// functions. 764 /// functions.
689 bool NaClBitcodeReader::RememberAndSkipFunctionBody() { 765 std::error_code NaClBitcodeReader::RememberAndSkipFunctionBody() {
690 DEBUG(dbgs() << "-> RememberAndSkipFunctionBody\n"); 766 DEBUG(dbgs() << "-> RememberAndSkipFunctionBody\n");
691 // Get the function we are talking about. 767 // Get the function we are talking about.
692 if (FunctionsWithBodies.empty()) 768 if (FunctionsWithBodies.empty())
693 return Error("Insufficient function protos"); 769 return Error(NaClBitcodeReader::MalformedBlock,
jvoung (off chromium) 2014/12/01 23:23:49 Upstream they have a separate error code for this.
Karl 2014/12/03 18:32:09 Changed to match upstream.
770 "Insufficient function protos");
694 771
695 Function *Fn = FunctionsWithBodies.back(); 772 Function *Fn = FunctionsWithBodies.back();
696 FunctionsWithBodies.pop_back(); 773 FunctionsWithBodies.pop_back();
697 774
698 // Save the current stream state. 775 // Save the current stream state.
699 uint64_t CurBit = Stream.GetCurrentBitNo(); 776 uint64_t CurBit = Stream.GetCurrentBitNo();
700 DeferredFunctionInfo[Fn] = CurBit; 777 DeferredFunctionInfo[Fn] = CurBit;
701 778
702 // Skip over the function block for now. 779 // Skip over the function block for now.
703 if (Stream.SkipBlock()) 780 if (Stream.SkipBlock())
704 return Error("Malformed block record"); 781 return Error(MalformedBlock, "Malformed block record");
705 DEBUG(dbgs() << "<- RememberAndSkipFunctionBody\n"); 782 DEBUG(dbgs() << "<- RememberAndSkipFunctionBody\n");
706 return false; 783 return std::error_code();
707 } 784 }
708 785
709 bool NaClBitcodeReader::GlobalCleanup() { 786 std::error_code NaClBitcodeReader::GlobalCleanup() {
710 // Look for intrinsic functions which need to be upgraded at some point 787 // Look for intrinsic functions which need to be upgraded at some point
711 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 788 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
712 FI != FE; ++FI) { 789 FI != FE; ++FI) {
713 Function *NewFn; 790 Function *NewFn;
714 if (UpgradeIntrinsicFunction(FI, NewFn)) 791 if (UpgradeIntrinsicFunction(FI, NewFn))
715 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 792 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
716 } 793 }
717 794
718 // Look for global variables which need to be renamed. 795 // Look for global variables which need to be renamed.
719 for (Module::global_iterator 796 for (Module::global_iterator
720 GI = TheModule->global_begin(), GE = TheModule->global_end(); 797 GI = TheModule->global_begin(), GE = TheModule->global_end();
721 GI != GE; ++GI) 798 GI != GE; ++GI)
722 UpgradeGlobalVariable(GI); 799 UpgradeGlobalVariable(GI);
723 return false; 800 return std::error_code();
724 } 801 }
725 802
726 FunctionType *NaClBitcodeReader::AddPointerTypesToIntrinsicType( 803 FunctionType *NaClBitcodeReader::AddPointerTypesToIntrinsicType(
727 StringRef Name, FunctionType *FTy) { 804 StringRef Name, FunctionType *FTy) {
728 FunctionType *IntrinsicTy = AllowedIntrinsics.getIntrinsicType(Name); 805 FunctionType *IntrinsicTy = AllowedIntrinsics.getIntrinsicType(Name);
729 if (IntrinsicTy == 0) return FTy; 806 if (IntrinsicTy == 0) return FTy;
730 807
731 Type *IReturnTy = IntrinsicTy->getReturnType(); 808 Type *IReturnTy = IntrinsicTy->getReturnType();
732 Type *FReturnTy = FTy->getReturnType(); 809 Type *FReturnTy = FTy->getReturnType();
733 810
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
770 Function *NewIntrinsic = Function::Create( 847 Function *NewIntrinsic = Function::Create(
771 ITy, GlobalValue::ExternalLinkage, "", TheModule); 848 ITy, GlobalValue::ExternalLinkage, "", TheModule);
772 NewIntrinsic->takeName(Func); 849 NewIntrinsic->takeName(Func);
773 ValueList.OverwriteValue(NewIntrinsic, Index); 850 ValueList.OverwriteValue(NewIntrinsic, Index);
774 Func->eraseFromParent(); 851 Func->eraseFromParent();
775 } 852 }
776 } 853 }
777 } 854 }
778 } 855 }
779 856
780 bool NaClBitcodeReader::ParseModule(bool Resume) { 857 std::error_code NaClBitcodeReader::ParseModule(bool Resume) {
781 DEBUG(dbgs() << "-> ParseModule\n"); 858 DEBUG(dbgs() << "-> ParseModule\n");
782 if (Resume) 859 if (Resume)
783 Stream.JumpToBit(NextUnreadBit); 860 Stream.JumpToBit(NextUnreadBit);
784 else if (Stream.EnterSubBlock(naclbitc::MODULE_BLOCK_ID)) 861 else if (Stream.EnterSubBlock(naclbitc::MODULE_BLOCK_ID))
785 return Error("Malformed block record"); 862 return Error(InvalidRecord, "Malformed block record");
786 863
787 SmallVector<uint64_t, 64> Record; 864 SmallVector<uint64_t, 64> Record;
788 865
789 // Read all the records for this module. 866 // Read all the records for this module.
790 while (1) { 867 while (1) {
791 NaClBitstreamEntry Entry = Stream.advance(0, 0); 868 NaClBitstreamEntry Entry = Stream.advance(0, 0);
792 869
793 switch (Entry.Kind) { 870 switch (Entry.Kind) {
794 case NaClBitstreamEntry::Error: 871 case NaClBitstreamEntry::Error:
795 Error("malformed module block"); 872 return Error(MalformedBlock, "malformed module block");
796 return true;
797 case NaClBitstreamEntry::EndBlock: 873 case NaClBitstreamEntry::EndBlock:
798 DEBUG(dbgs() << "<- ParseModule\n"); 874 DEBUG(dbgs() << "<- ParseModule\n");
799 return GlobalCleanup(); 875 return GlobalCleanup();
800 876
801 case NaClBitstreamEntry::SubBlock: 877 case NaClBitstreamEntry::SubBlock:
802 switch (Entry.ID) { 878 switch (Entry.ID) {
803 default: { 879 default: {
804 std::string Message; 880 std::string Message;
805 raw_string_ostream StrM(Message); 881 raw_string_ostream StrM(Message);
806 StrM << "Unknown block ID: " << Entry.ID; 882 StrM << "Unknown block ID: " << Entry.ID;
807 return Error(StrM.str()); 883 return Error(InvalidRecord, StrM.str());
808 } 884 }
809 case naclbitc::BLOCKINFO_BLOCK_ID: 885 case naclbitc::BLOCKINFO_BLOCK_ID:
810 if (Stream.ReadBlockInfoBlock(0)) 886 if (Stream.ReadBlockInfoBlock(0))
811 return Error("Malformed BlockInfoBlock"); 887 return Error(MalformedBlock, "Malformed BlockInfoBlock");
812 break; 888 break;
813 case naclbitc::TYPE_BLOCK_ID_NEW: 889 case naclbitc::TYPE_BLOCK_ID_NEW:
814 if (ParseTypeTable()) 890 if (std::error_code EC = ParseTypeTable())
815 return true; 891 return EC;
816 break; 892 break;
817 case naclbitc::GLOBALVAR_BLOCK_ID: 893 case naclbitc::GLOBALVAR_BLOCK_ID:
818 if (ParseGlobalVars()) 894 if (std::error_code EC = ParseGlobalVars())
819 return true; 895 return EC;
820 break; 896 break;
821 case naclbitc::VALUE_SYMTAB_BLOCK_ID: 897 case naclbitc::VALUE_SYMTAB_BLOCK_ID:
822 if (ParseValueSymbolTable()) 898 if (std::error_code EC = ParseValueSymbolTable())
823 return true; 899 return EC;
824 SeenValueSymbolTable = true; 900 SeenValueSymbolTable = true;
825 // Now that we know the names of the intrinsics, we can add 901 // Now that we know the names of the intrinsics, we can add
826 // pointer types to the intrinsic declarations' types. 902 // pointer types to the intrinsic declarations' types.
827 AddPointerTypesToIntrinsicParams(); 903 AddPointerTypesToIntrinsicParams();
828 break; 904 break;
829 case naclbitc::FUNCTION_BLOCK_ID: 905 case naclbitc::FUNCTION_BLOCK_ID:
830 // If this is the first function body we've seen, reverse the 906 // If this is the first function body we've seen, reverse the
831 // FunctionsWithBodies list. 907 // FunctionsWithBodies list.
832 if (!SeenFirstFunctionBody) { 908 if (!SeenFirstFunctionBody) {
833 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 909 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
834 if (GlobalCleanup()) 910 if (std::error_code EC = GlobalCleanup())
835 return true; 911 return EC;
836 SeenFirstFunctionBody = true; 912 SeenFirstFunctionBody = true;
837 } 913 }
838 914
839 if (RememberAndSkipFunctionBody()) 915 if (std::error_code EC = RememberAndSkipFunctionBody())
840 return true; 916 return EC;
841 917
842 // For streaming bitcode, suspend parsing when we reach the function 918 // For streaming bitcode, suspend parsing when we reach the function
843 // bodies. Subsequent materialization calls will resume it when 919 // bodies. Subsequent materialization calls will resume it when
844 // necessary. For streaming, the function bodies must be at the end of 920 // necessary. For streaming, the function bodies must be at the end of
845 // the bitcode. If the bitcode file is old, the symbol table will be 921 // the bitcode. If the bitcode file is old, the symbol table will be
846 // at the end instead and will not have been seen yet. In this case, 922 // at the end instead and will not have been seen yet. In this case,
847 // just finish the parse now. 923 // just finish the parse now.
848 if (LazyStreamer && SeenValueSymbolTable) { 924 if (LazyStreamer && SeenValueSymbolTable) {
849 NextUnreadBit = Stream.GetCurrentBitNo(); 925 NextUnreadBit = Stream.GetCurrentBitNo();
850 DEBUG(dbgs() << "<- ParseModule\n"); 926 DEBUG(dbgs() << "<- ParseModule\n");
851 return false; 927 return std::error_code();
852 } 928 }
853 break; 929 break;
854 } 930 }
855 continue; 931 continue;
856 932
857 case NaClBitstreamEntry::Record: 933 case NaClBitstreamEntry::Record:
858 // The interesting case. 934 // The interesting case.
859 break; 935 break;
860 } 936 }
861 937
862 // Read a record. 938 // Read a record.
863 unsigned Selector = Stream.readRecord(Entry.ID, Record); 939 unsigned Selector = Stream.readRecord(Entry.ID, Record);
864 switch (Selector) { 940 switch (Selector) {
865 default: { 941 default: {
866 std::string Message; 942 std::string Message;
867 raw_string_ostream StrM(Message); 943 raw_string_ostream StrM(Message);
868 StrM << "Invalid MODULE_CODE: " << Selector; 944 StrM << "Invalid MODULE_CODE: " << Selector;
869 StrM.flush(); 945 StrM.flush();
870 return Error(Message); 946 return Error(InvalidValue, Message);
871 } 947 }
872 case naclbitc::MODULE_CODE_VERSION: { // VERSION: [version#] 948 case naclbitc::MODULE_CODE_VERSION: { // VERSION: [version#]
873 if (Record.size() < 1) 949 if (Record.size() < 1)
874 return Error("Malformed MODULE_CODE_VERSION"); 950 return Error(InvalidRecord, "Malformed MODULE_CODE_VERSION");
875 // Only version #1 is supported for PNaCl. Version #0 is not supported. 951 // Only version #1 is supported for PNaCl. Version #0 is not supported.
876 unsigned module_version = Record[0]; 952 unsigned module_version = Record[0];
877 if (module_version != 1) 953 if (module_version != 1)
878 return Error("Unknown bitstream version!"); 954 return Error(InvalidValue, "Unknown bitstream version!");
879 break; 955 break;
880 } 956 }
881 // FUNCTION: [type, callingconv, isproto, linkage] 957 // FUNCTION: [type, callingconv, isproto, linkage]
882 case naclbitc::MODULE_CODE_FUNCTION: { 958 case naclbitc::MODULE_CODE_FUNCTION: {
883 if (Record.size() < 4) 959 if (Record.size() < 4)
884 return Error("Invalid MODULE_CODE_FUNCTION record"); 960 return Error(InvalidRecord, "Invalid MODULE_CODE_FUNCTION record");
885 Type *Ty = getTypeByID(Record[0]); 961 Type *Ty = getTypeByID(Record[0]);
886 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record"); 962 if (!Ty)
963 return Error(InvalidType, "Invalid MODULE_CODE_FUNCTION record");
887 FunctionType *FTy = dyn_cast<FunctionType>(Ty); 964 FunctionType *FTy = dyn_cast<FunctionType>(Ty);
888 if (!FTy) 965 if (!FTy)
889 return Error("Function not declared with a function type!"); 966 return Error(InvalidType,
967 "Function not declared with a function type!");
890 968
891 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 969 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
892 "", TheModule); 970 "", TheModule);
893 971
894 CallingConv::ID CallingConv; 972 CallingConv::ID CallingConv;
895 if (!naclbitc::DecodeCallingConv(Record[1], CallingConv)) 973 if (!naclbitc::DecodeCallingConv(Record[1], CallingConv))
896 return Error("PNaCl bitcode contains invalid calling conventions."); 974 return Error(InvalidValue,
975 "PNaCl bitcode contains invalid calling conventions.");
897 Func->setCallingConv(CallingConv); 976 Func->setCallingConv(CallingConv);
898 bool isProto = Record[2]; 977 bool isProto = Record[2];
899 GlobalValue::LinkageTypes Linkage; 978 GlobalValue::LinkageTypes Linkage;
900 if (!naclbitc::DecodeLinkage(Record[3], Linkage)) 979 if (!naclbitc::DecodeLinkage(Record[3], Linkage))
901 return Error("Unknown linkage type"); 980 return Error(InvalidValue, "Unknown linkage type");
902 Func->setLinkage(Linkage); 981 Func->setLinkage(Linkage);
903 ValueList.push_back(Func); 982 ValueList.push_back(Func);
904 983
905 // If this is a function with a body, remember the prototype we are 984 // If this is a function with a body, remember the prototype we are
906 // creating now, so that we can match up the body with them later. 985 // creating now, so that we can match up the body with them later.
907 if (!isProto) { 986 if (!isProto) {
908 FunctionsWithBodies.push_back(Func); 987 FunctionsWithBodies.push_back(Func);
909 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 988 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
910 } 989 }
911 break; 990 break;
912 } 991 }
913 } 992 }
914 Record.clear(); 993 Record.clear();
915 } 994 }
995 return std::error_code();
916 } 996 }
917 997
918 const char *llvm::PNaClDataLayout = 998 const char *llvm::PNaClDataLayout =
919 "e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-" 999 "e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"
920 "f32:32:32-f64:64:64-p:32:32:32-v128:32:32"; 1000 "f32:32:32-f64:64:64-p:32:32:32-v128:32:32";
921 1001
922 bool NaClBitcodeReader::ParseBitcodeInto(Module *M) { 1002 std::error_code NaClBitcodeReader::ParseBitcodeInto(Module *M) {
923 TheModule = 0; 1003 TheModule = 0;
924 1004
925 // PNaCl does not support different DataLayouts in pexes, so we 1005 // PNaCl does not support different DataLayouts in pexes, so we
926 // implicitly set the DataLayout to the following default. 1006 // implicitly set the DataLayout to the following default.
927 // 1007 //
928 // This is not usually needed by the backend, but it might be used 1008 // This is not usually needed by the backend, but it might be used
929 // by IR passes that the PNaCl translator runs. We set this in the 1009 // by IR passes that the PNaCl translator runs. We set this in the
930 // reader rather than in pnacl-llc so that 'opt' will also use the 1010 // reader rather than in pnacl-llc so that 'opt' will also use the
931 // correct DataLayout if it is run on a pexe. 1011 // correct DataLayout if it is run on a pexe.
932 M->setDataLayout(PNaClDataLayout); 1012 M->setDataLayout(PNaClDataLayout);
933 1013
934 if (InitStream()) return true; // InitSream will set the error string. 1014 if (std::error_code EC = InitStream())
1015 return EC;
935 1016
936 // We expect a number of well-defined blocks, though we don't necessarily 1017 // We expect a number of well-defined blocks, though we don't necessarily
937 // need to understand them all. 1018 // need to understand them all.
938 while (1) { 1019 while (1) {
939 if (Stream.AtEndOfStream()) 1020 if (Stream.AtEndOfStream())
940 return false; 1021 return std::error_code();
941 1022
942 NaClBitstreamEntry Entry = 1023 NaClBitstreamEntry Entry =
943 Stream.advance(NaClBitstreamCursor::AF_DontAutoprocessAbbrevs, 0); 1024 Stream.advance(NaClBitstreamCursor::AF_DontAutoprocessAbbrevs, 0);
944 1025
945 switch (Entry.Kind) { 1026 switch (Entry.Kind) {
946 case NaClBitstreamEntry::Error: 1027 case NaClBitstreamEntry::Error:
947 Error("malformed module file"); 1028 return Error(MalformedBlock, "malformed module file");
948 return true;
949 case NaClBitstreamEntry::EndBlock: 1029 case NaClBitstreamEntry::EndBlock:
950 return false; 1030 return std::error_code();
951 1031
952 case NaClBitstreamEntry::SubBlock: 1032 case NaClBitstreamEntry::SubBlock:
953 switch (Entry.ID) { 1033 switch (Entry.ID) {
954 case naclbitc::BLOCKINFO_BLOCK_ID: 1034 case naclbitc::BLOCKINFO_BLOCK_ID:
955 if (Stream.ReadBlockInfoBlock(0)) 1035 if (Stream.ReadBlockInfoBlock(0))
956 return Error("Malformed BlockInfoBlock"); 1036 return Error(MalformedBlock, "Malformed BlockInfoBlock");
957 break; 1037 break;
958 case naclbitc::MODULE_BLOCK_ID: 1038 case naclbitc::MODULE_BLOCK_ID:
959 // Reject multiple MODULE_BLOCK's in a single bitstream. 1039 // Reject multiple MODULE_BLOCK's in a single bitstream.
960 if (TheModule) 1040 if (TheModule)
961 return Error("Multiple MODULE_BLOCKs in same stream"); 1041 return Error(InvalidMultipleBlocks,
1042 "Multiple MODULE_BLOCKs in same stream");
962 TheModule = M; 1043 TheModule = M;
963 if (ParseModule(false)) 1044 if (std::error_code EC = ParseModule(false))
964 return true; 1045 return EC;
965 if (LazyStreamer) return false; 1046 if (LazyStreamer)
1047 return std::error_code();
966 break; 1048 break;
967 default: 1049 default:
968 if (Stream.SkipBlock()) 1050 if (Stream.SkipBlock())
969 return Error("Malformed block record"); 1051 return Error(InvalidRecord, "Malformed block record");
970 break; 1052 break;
971 } 1053 }
972 continue; 1054 continue;
973 case NaClBitstreamEntry::Record: 1055 case NaClBitstreamEntry::Record:
974 // There should be no records in the top-level of blocks. 1056 // There should be no records in the top-level of blocks.
975 return Error("Invalid record at top-level"); 1057 return Error(InvalidRecord, "Invalid record at top-level");
976 } 1058 }
977 } 1059 }
978 } 1060 }
979 1061
980 // Returns true if error occured installing I into BB. 1062 // Returns true if error occured installing I into BB.
981 bool NaClBitcodeReader::InstallInstruction( 1063 std::error_code NaClBitcodeReader::InstallInstruction(
982 BasicBlock *BB, Instruction *I) { 1064 BasicBlock *BB, Instruction *I) {
983 // Add instruction to end of current BB. If there is no current BB, reject 1065 // Add instruction to end of current BB. If there is no current BB, reject
984 // this file. 1066 // this file.
985 if (BB == 0) { 1067 if (BB == 0) {
986 delete I; 1068 delete I;
987 return Error("Invalid instruction with no BB"); 1069 return Error(InvalidBBForInstruction,
1070 "Instruction with no BB, can't install");
988 } 1071 }
989 BB->getInstList().push_back(I); 1072 BB->getInstList().push_back(I);
990 return false; 1073 return std::error_code();
991 } 1074 }
992 1075
993 CastInst * 1076 CastInst *
994 NaClBitcodeReader::CreateCast(unsigned BBIndex, Instruction::CastOps Op, 1077 NaClBitcodeReader::CreateCast(unsigned BBIndex, Instruction::CastOps Op,
995 Type *CT, Value *V, bool DeferInsertion) { 1078 Type *CT, Value *V, bool DeferInsertion) {
996 if (BBIndex >= FunctionBBs.size()) 1079 if (BBIndex >= FunctionBBs.size())
997 report_fatal_error("CreateCast on unknown basic block"); 1080 report_fatal_error("CreateCast on unknown basic block");
998 BasicBlockInfo &BBInfo = FunctionBBs[BBIndex]; 1081 BasicBlockInfo &BBInfo = FunctionBBs[BBIndex];
999 NaClBitcodeReaderCast ModeledCast(Op, CT, V); 1082 NaClBitcodeReaderCast ModeledCast(Op, CT, V);
1000 CastInst *Cast = BBInfo.CastMap[ModeledCast]; 1083 CastInst *Cast = BBInfo.CastMap[ModeledCast];
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1035 return CreateCast(BBIndex, Instruction::IntToPtr, T, Op); 1118 return CreateCast(BBIndex, Instruction::IntToPtr, T, Op);
1036 } 1119 }
1037 1120
1038 std::string Message; 1121 std::string Message;
1039 raw_string_ostream StrM(Message); 1122 raw_string_ostream StrM(Message);
1040 StrM << "Can't convert " << *Op << " to type " << *T << "\n"; 1123 StrM << "Can't convert " << *Op << " to type " << *T << "\n";
1041 report_fatal_error(StrM.str()); 1124 report_fatal_error(StrM.str());
1042 } 1125 }
1043 1126
1044 /// ParseFunctionBody - Lazily parse the specified function body block. 1127 /// ParseFunctionBody - Lazily parse the specified function body block.
1045 bool NaClBitcodeReader::ParseFunctionBody(Function *F) { 1128 std::error_code NaClBitcodeReader::ParseFunctionBody(Function *F) {
1046 DEBUG(dbgs() << "-> ParseFunctionBody\n"); 1129 DEBUG(dbgs() << "-> ParseFunctionBody\n");
1047 if (Stream.EnterSubBlock(naclbitc::FUNCTION_BLOCK_ID)) 1130 if (Stream.EnterSubBlock(naclbitc::FUNCTION_BLOCK_ID))
1048 return Error("Malformed block record"); 1131 return Error(InvalidRecord, "Malformed block record");
1049 1132
1050 unsigned ModuleValueListSize = ValueList.size(); 1133 unsigned ModuleValueListSize = ValueList.size();
1051 1134
1052 // Add all the function arguments to the value table. 1135 // Add all the function arguments to the value table.
1053 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1136 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1054 ValueList.push_back(I); 1137 ValueList.push_back(I);
1055 1138
1056 unsigned NextValueNo = ValueList.size(); 1139 unsigned NextValueNo = ValueList.size();
1057 BasicBlock *CurBB = 0; 1140 BasicBlock *CurBB = 0;
1058 unsigned CurBBNo = 0; 1141 unsigned CurBBNo = 0;
1059 1142
1060 // Read all the records. 1143 // Read all the records.
1061 SmallVector<uint64_t, 64> Record; 1144 SmallVector<uint64_t, 64> Record;
1062 while (1) { 1145 while (1) {
1063 NaClBitstreamEntry Entry = Stream.advance(0, 0); 1146 NaClBitstreamEntry Entry = Stream.advance(0, 0);
1064 1147
1065 switch (Entry.Kind) { 1148 switch (Entry.Kind) {
1066 case NaClBitstreamEntry::Error: 1149 case NaClBitstreamEntry::Error:
1067 return Error("Bitcode error in function block"); 1150 return Error(MalformedBlock, "Bitcode error in function block");
1068 case NaClBitstreamEntry::EndBlock: 1151 case NaClBitstreamEntry::EndBlock:
1069 goto OutOfRecordLoop; 1152 goto OutOfRecordLoop;
1070 1153
1071 case NaClBitstreamEntry::SubBlock: 1154 case NaClBitstreamEntry::SubBlock:
1072 switch (Entry.ID) { 1155 switch (Entry.ID) {
1073 default: // Skip unknown content. 1156 default: // Skip unknown content.
1074 dbgs() << "default skip block\n";
1075 if (Stream.SkipBlock()) 1157 if (Stream.SkipBlock())
1076 return Error("Malformed block record"); 1158 return Error(InvalidRecord, "Malformed block record");
jvoung (off chromium) 2014/12/01 23:23:49 If these are all InvalidRecord, maybe the verbose
Karl 2014/12/03 18:32:09 Upstream uses InvalidRecord if SkipBlock fails. Ad
1077 break; 1159 break;
1078 case naclbitc::CONSTANTS_BLOCK_ID: 1160 case naclbitc::CONSTANTS_BLOCK_ID:
1079 if (ParseConstants()) 1161 if (std::error_code EC = ParseConstants())
1080 return true; 1162 return EC;
1081 NextValueNo = ValueList.size(); 1163 NextValueNo = ValueList.size();
1082 break; 1164 break;
1083 case naclbitc::VALUE_SYMTAB_BLOCK_ID: 1165 case naclbitc::VALUE_SYMTAB_BLOCK_ID:
1084 if (PNaClAllowLocalSymbolTables) { 1166 if (PNaClAllowLocalSymbolTables) {
1085 if (ParseValueSymbolTable()) 1167 if (std::error_code EC = ParseValueSymbolTable())
1086 return true; 1168 return EC;
1087 } else { 1169 } else {
1088 return Error("Local value symbol tables not allowed"); 1170 return Error(InvalidRecord, "Local value symbol tables not allowed");
1089 } 1171 }
1090 break; 1172 break;
1091 } 1173 }
1092 continue; 1174 continue;
1093 1175
1094 case NaClBitstreamEntry::Record: 1176 case NaClBitstreamEntry::Record:
1095 // The interesting case. 1177 // The interesting case.
1096 break; 1178 break;
1097 } 1179 }
1098 1180
1099 // Read a record. 1181 // Read a record.
1100 Record.clear(); 1182 Record.clear();
1101 Instruction *I = 0; 1183 Instruction *I = 0;
1102 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1184 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1103 switch (BitCode) { 1185 switch (BitCode) {
1104 default: {// Default behavior: reject 1186 default: {// Default behavior: reject
1105 std::string Message; 1187 std::string Message;
1106 raw_string_ostream StrM(Message); 1188 raw_string_ostream StrM(Message);
1107 StrM << "Unknown instruction record: <" << BitCode; 1189 StrM << "Unknown instruction record: <" << BitCode;
1108 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 1190 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
1109 StrM << " " << Record[I]; 1191 StrM << " " << Record[I];
1110 } 1192 }
1111 StrM << ">"; 1193 StrM << ">";
1112 return Error(StrM.str()); 1194 return Error(InvalidRecord, StrM.str());
1113 } 1195 }
1114 1196
1115 case naclbitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 1197 case naclbitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1116 if (Record.size() != 1 || Record[0] == 0) 1198 if (Record.size() != 1 || Record[0] == 0)
1117 return Error("Invalid DECLAREBLOCKS record"); 1199 return Error(InvalidRecord, "Invalid DECLAREBLOCKS record");
1118 // Create all the basic blocks for the function. 1200 // Create all the basic blocks for the function.
1119 FunctionBBs.resize(Record[0]); 1201 FunctionBBs.resize(Record[0]);
1120 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) { 1202 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) {
1121 BasicBlockInfo &BBInfo = FunctionBBs[i]; 1203 BasicBlockInfo &BBInfo = FunctionBBs[i];
1122 BBInfo.BB = BasicBlock::Create(Context, "", F); 1204 BBInfo.BB = BasicBlock::Create(Context, "", F);
1123 } 1205 }
1124 CurBB = FunctionBBs.at(0).BB; 1206 CurBB = FunctionBBs.at(0).BB;
1125 continue; 1207 continue;
1126 1208
1127 case naclbitc::FUNC_CODE_INST_BINOP: { 1209 case naclbitc::FUNC_CODE_INST_BINOP: {
1128 // BINOP: [opval, opval, opcode[, flags]] 1210 // BINOP: [opval, opval, opcode[, flags]]
1129 // Note: Only old PNaCl bitcode files may contain flags. If 1211 // Note: Only old PNaCl bitcode files may contain flags. If
1130 // they are found, we ignore them. 1212 // they are found, we ignore them.
1131 unsigned OpNum = 0; 1213 unsigned OpNum = 0;
1132 Value *LHS, *RHS; 1214 Value *LHS, *RHS;
1133 if (popValue(Record, &OpNum, NextValueNo, &LHS) || 1215 if (popValue(Record, &OpNum, NextValueNo, &LHS) ||
1134 popValue(Record, &OpNum, NextValueNo, &RHS) || 1216 popValue(Record, &OpNum, NextValueNo, &RHS) ||
1135 OpNum+1 > Record.size()) 1217 OpNum+1 > Record.size())
1136 return Error("Invalid BINOP record"); 1218 return Error(InvalidRecord, "Invalid BINOP record");
1137 1219
1138 LHS = ConvertOpToScalar(LHS, CurBBNo); 1220 LHS = ConvertOpToScalar(LHS, CurBBNo);
1139 RHS = ConvertOpToScalar(RHS, CurBBNo); 1221 RHS = ConvertOpToScalar(RHS, CurBBNo);
1140 1222
1141 Instruction::BinaryOps Opc; 1223 Instruction::BinaryOps Opc;
1142 if (!naclbitc::DecodeBinaryOpcode(Record[OpNum++], LHS->getType(), Opc)) 1224 if (!naclbitc::DecodeBinaryOpcode(Record[OpNum++], LHS->getType(), Opc))
1143 return Error("Invalid binary opcode in BINOP record"); 1225 return Error(InvalidValue, "Invalid binary opcode in BINOP record");
1144 I = BinaryOperator::Create(Opc, LHS, RHS); 1226 I = BinaryOperator::Create(Opc, LHS, RHS);
1145 break; 1227 break;
1146 } 1228 }
1147 case naclbitc::FUNC_CODE_INST_CAST: { // CAST: [opval, destty, castopc] 1229 case naclbitc::FUNC_CODE_INST_CAST: { // CAST: [opval, destty, castopc]
1148 unsigned OpNum = 0; 1230 unsigned OpNum = 0;
1149 Value *Op; 1231 Value *Op;
1150 if (popValue(Record, &OpNum, NextValueNo, &Op) || 1232 if (popValue(Record, &OpNum, NextValueNo, &Op) ||
1151 OpNum+2 != Record.size()) 1233 OpNum+2 != Record.size())
1152 return Error("Invalid CAST record: bad record size"); 1234 return Error(InvalidRecord, "Invalid CAST record: bad record size");
1153 1235
1154 Type *ResTy = getTypeByID(Record[OpNum]); 1236 Type *ResTy = getTypeByID(Record[OpNum]);
1155 if (ResTy == 0) 1237 if (ResTy == 0)
1156 return Error("Invalid CAST record: bad type ID"); 1238 return Error(InvalidType, "Invalid CAST record: bad type ID");
1157 Instruction::CastOps Opc; 1239 Instruction::CastOps Opc;
1158 if (!naclbitc::DecodeCastOpcode(Record[OpNum+1], Opc)) { 1240 if (!naclbitc::DecodeCastOpcode(Record[OpNum+1], Opc)) {
1159 return Error("Invalid CAST record: bad opcode"); 1241 return Error(InvalidValue, "Invalid CAST record: bad opcode");
1160 } 1242 }
1161 1243
1162 // If a ptrtoint cast was elided on the argument of the cast, 1244 // If a ptrtoint cast was elided on the argument of the cast,
1163 // add it back. Note: The casts allowed here should match the 1245 // add it back. Note: The casts allowed here should match the
1164 // casts in NaClValueEnumerator::ExpectsScalarValue. 1246 // casts in NaClValueEnumerator::ExpectsScalarValue.
1165 switch (Opc) { 1247 switch (Opc) {
1166 case Instruction::Trunc: 1248 case Instruction::Trunc:
1167 case Instruction::ZExt: 1249 case Instruction::ZExt:
1168 case Instruction::SExt: 1250 case Instruction::SExt:
1169 case Instruction::UIToFP: 1251 case Instruction::UIToFP:
(...skipping 10 matching lines...) Expand all
1180 1262
1181 case naclbitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [opval, opval, pred] 1263 case naclbitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [opval, opval, pred]
1182 // new form of select 1264 // new form of select
1183 // handles select i1 or select [N x i1] 1265 // handles select i1 or select [N x i1]
1184 unsigned OpNum = 0; 1266 unsigned OpNum = 0;
1185 Value *TrueVal, *FalseVal, *Cond; 1267 Value *TrueVal, *FalseVal, *Cond;
1186 if (popValue(Record, &OpNum, NextValueNo, &TrueVal) || 1268 if (popValue(Record, &OpNum, NextValueNo, &TrueVal) ||
1187 popValue(Record, &OpNum, NextValueNo, &FalseVal) || 1269 popValue(Record, &OpNum, NextValueNo, &FalseVal) ||
1188 popValue(Record, &OpNum, NextValueNo, &Cond) || 1270 popValue(Record, &OpNum, NextValueNo, &Cond) ||
1189 OpNum != Record.size()) 1271 OpNum != Record.size())
1190 return Error("Invalid SELECT record"); 1272 return Error(InvalidRecord, "Invalid SELECT record");
1191 1273
1192 TrueVal = ConvertOpToScalar(TrueVal, CurBBNo); 1274 TrueVal = ConvertOpToScalar(TrueVal, CurBBNo);
1193 FalseVal = ConvertOpToScalar(FalseVal, CurBBNo); 1275 FalseVal = ConvertOpToScalar(FalseVal, CurBBNo);
1194 1276
1195 // select condition can be either i1 or [N x i1] 1277 // select condition can be either i1 or [N x i1]
1196 if (VectorType* vector_type = 1278 if (VectorType* vector_type =
1197 dyn_cast<VectorType>(Cond->getType())) { 1279 dyn_cast<VectorType>(Cond->getType())) {
1198 // expect <n x i1> 1280 // expect <n x i1>
1199 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 1281 if (vector_type->getElementType() != Type::getInt1Ty(Context))
1200 return Error("Invalid SELECT vector condition type"); 1282 return Error(InvalidTypeForValue,
1283 "Invalid SELECT vector condition type");
1201 } else { 1284 } else {
1202 // expect i1 1285 // expect i1
1203 if (Cond->getType() != Type::getInt1Ty(Context)) 1286 if (Cond->getType() != Type::getInt1Ty(Context))
1204 return Error("Invalid SELECT condition type"); 1287 return Error(InvalidTypeForValue, "Invalid SELECT condition type");
1205 } 1288 }
1206 1289
1207 I = SelectInst::Create(Cond, TrueVal, FalseVal); 1290 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1208 break; 1291 break;
1209 } 1292 }
1210 1293
1211 case naclbitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opval, opval] 1294 case naclbitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opval, opval]
1212 unsigned OpNum = 0; 1295 unsigned OpNum = 0;
1213 Value *Vec, *Idx; 1296 Value *Vec, *Idx;
1214 if (popValue(Record, &OpNum, NextValueNo, &Vec) || 1297 if (popValue(Record, &OpNum, NextValueNo, &Vec) ||
1215 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size()) 1298 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size())
1216 return Error("Invalid EXTRACTELEMENT record"); 1299 return Error(InvalidRecord, "Invalid EXTRACTELEMENT record");
1217 1300
1218 // expect i32 1301 // expect i32
1219 if (Idx->getType() != Type::getInt32Ty(Context)) 1302 if (Idx->getType() != Type::getInt32Ty(Context))
1220 return Error("Invalid EXTRACTELEMENT index type"); 1303 return Error(InvalidTypeForValue, "Invalid EXTRACTELEMENT index type");
1221 1304
1222 I = ExtractElementInst::Create(Vec, Idx); 1305 I = ExtractElementInst::Create(Vec, Idx);
1223 break; 1306 break;
1224 } 1307 }
1225 1308
1226 case naclbitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [opval,opval,opval] 1309 case naclbitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [opval,opval,opval]
1227 unsigned OpNum = 0; 1310 unsigned OpNum = 0;
1228 Value *Vec, *Elt, *Idx; 1311 Value *Vec, *Elt, *Idx;
1229 if (popValue(Record, &OpNum, NextValueNo, &Vec) || 1312 if (popValue(Record, &OpNum, NextValueNo, &Vec) ||
1230 popValue(Record, &OpNum, NextValueNo, &Elt) || 1313 popValue(Record, &OpNum, NextValueNo, &Elt) ||
1231 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size()) 1314 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size())
1232 return Error("Invalid INSERTELEMENT record"); 1315 return Error(InvalidRecord, "Invalid INSERTELEMENT record");
1233 1316
1234 // expect vector type 1317 // expect vector type
1235 if (!isa<VectorType>(Vec->getType())) 1318 if (!isa<VectorType>(Vec->getType()))
1236 return Error("Invalid INSERTELEMENT vector type"); 1319 return Error(InvalidTypeForValue, "Invalid INSERTELEMENT vector type");
1237 // match vector and element types 1320 // match vector and element types
1238 if (cast<VectorType>(Vec->getType())->getElementType() != Elt->getType()) 1321 if (cast<VectorType>(Vec->getType())->getElementType() != Elt->getType())
1239 return Error("Mismatched INSERTELEMENT vector and element type"); 1322 return Error(InvalidTypeForValue,
1323 "Mismatched INSERTELEMENT vector and element type");
1240 // expect i32 1324 // expect i32
1241 if (Idx->getType() != Type::getInt32Ty(Context)) 1325 if (Idx->getType() != Type::getInt32Ty(Context))
1242 return Error("Invalid INSERTELEMENT index type"); 1326 return Error(InvalidTypeForValue, "Invalid INSERTELEMENT index type");
1243 1327
1244 I = InsertElementInst::Create(Vec, Elt, Idx); 1328 I = InsertElementInst::Create(Vec, Elt, Idx);
1245 break; 1329 break;
1246 } 1330 }
1247 1331
1248 case naclbitc::FUNC_CODE_INST_CMP2: { // CMP2: [opval, opval, pred] 1332 case naclbitc::FUNC_CODE_INST_CMP2: { // CMP2: [opval, opval, pred]
1249 // FCmp/ICmp returning bool or vector of bool 1333 // FCmp/ICmp returning bool or vector of bool
1250 1334
1251 unsigned OpNum = 0; 1335 unsigned OpNum = 0;
1252 Value *LHS, *RHS; 1336 Value *LHS, *RHS;
1253 if (popValue(Record, &OpNum, NextValueNo, &LHS) || 1337 if (popValue(Record, &OpNum, NextValueNo, &LHS) ||
1254 popValue(Record, &OpNum, NextValueNo, &RHS) || 1338 popValue(Record, &OpNum, NextValueNo, &RHS) ||
1255 OpNum+1 != Record.size()) 1339 OpNum+1 != Record.size())
1256 return Error("Invalid CMP record"); 1340 return Error(InvalidRecord, "Invalid CMP record");
1257 1341
1258 LHS = ConvertOpToScalar(LHS, CurBBNo); 1342 LHS = ConvertOpToScalar(LHS, CurBBNo);
1259 RHS = ConvertOpToScalar(RHS, CurBBNo); 1343 RHS = ConvertOpToScalar(RHS, CurBBNo);
1260 1344
1261 CmpInst::Predicate Predicate; 1345 CmpInst::Predicate Predicate;
1262 if (LHS->getType()->isFPOrFPVectorTy()) { 1346 if (LHS->getType()->isFPOrFPVectorTy()) {
1263 if (!naclbitc::DecodeFcmpPredicate(Record[OpNum], Predicate)) 1347 if (!naclbitc::DecodeFcmpPredicate(Record[OpNum], Predicate))
1264 return Error( 1348 return Error(
1349 InvalidValue,
1265 "PNaCl bitcode contains invalid floating comparison predicate"); 1350 "PNaCl bitcode contains invalid floating comparison predicate");
1266 I = new FCmpInst(Predicate, LHS, RHS); 1351 I = new FCmpInst(Predicate, LHS, RHS);
1267 } else { 1352 } else {
1268 if (!naclbitc::DecodeIcmpPredicate(Record[OpNum], Predicate)) 1353 if (!naclbitc::DecodeIcmpPredicate(Record[OpNum], Predicate))
1269 return Error( 1354 return Error(
1355 InvalidValue,
1270 "PNaCl bitcode contains invalid integer comparison predicate"); 1356 "PNaCl bitcode contains invalid integer comparison predicate");
1271 I = new ICmpInst(Predicate, LHS, RHS); 1357 I = new ICmpInst(Predicate, LHS, RHS);
1272 } 1358 }
1273 break; 1359 break;
1274 } 1360 }
1275 1361
1276 case naclbitc::FUNC_CODE_INST_RET: // RET: [opval<optional>] 1362 case naclbitc::FUNC_CODE_INST_RET: // RET: [opval<optional>]
1277 { 1363 {
1278 unsigned Size = Record.size(); 1364 unsigned Size = Record.size();
1279 if (Size == 0) { 1365 if (Size == 0) {
1280 I = ReturnInst::Create(Context); 1366 I = ReturnInst::Create(Context);
1281 break; 1367 break;
1282 } 1368 }
1283 1369
1284 unsigned OpNum = 0; 1370 unsigned OpNum = 0;
1285 Value *Op = NULL; 1371 Value *Op = NULL;
1286 if (popValue(Record, &OpNum, NextValueNo, &Op)) 1372 if (popValue(Record, &OpNum, NextValueNo, &Op))
1287 return Error("Invalid RET record"); 1373 return Error(InvalidRecord, "Invalid RET record");
1288 if (OpNum != Record.size()) 1374 if (OpNum != Record.size())
1289 return Error("Invalid RET record"); 1375 return Error(InvalidRecord, "Invalid RET record");
1290 1376
1291 I = ReturnInst::Create(Context, ConvertOpToScalar(Op, CurBBNo)); 1377 I = ReturnInst::Create(Context, ConvertOpToScalar(Op, CurBBNo));
1292 break; 1378 break;
1293 } 1379 }
1294 case naclbitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 1380 case naclbitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1295 if (Record.size() != 1 && Record.size() != 3) 1381 if (Record.size() != 1 && Record.size() != 3)
1296 return Error("Invalid BR record"); 1382 return Error(InvalidRecord, "Invalid BR record");
1297 BasicBlock *TrueDest = getBasicBlock(Record[0]); 1383 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1298 if (TrueDest == 0) 1384 if (TrueDest == 0)
1299 return Error("Invalid BR record"); 1385 return Error(InvalidRecord, "Invalid BR record");
1300 1386
1301 if (Record.size() == 1) { 1387 if (Record.size() == 1) {
1302 I = BranchInst::Create(TrueDest); 1388 I = BranchInst::Create(TrueDest);
1303 } 1389 }
1304 else { 1390 else {
1305 BasicBlock *FalseDest = getBasicBlock(Record[1]); 1391 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1306 Value *Cond = getValue(Record, 2, NextValueNo); 1392 Value *Cond = getValue(Record, 2, NextValueNo);
1307 if (FalseDest == 0 || Cond == 0) 1393 if (FalseDest == 0 || Cond == 0)
1308 return Error("Invalid BR record"); 1394 return Error(InvalidValue, "Invalid BR record");
1309 I = BranchInst::Create(TrueDest, FalseDest, Cond); 1395 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1310 } 1396 }
1311 break; 1397 break;
1312 } 1398 }
1313 case naclbitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 1399 case naclbitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
1314 if (Record.size() < 4) 1400 if (Record.size() < 4)
1315 return Error("Invalid SWITCH record"); 1401 return Error(InvalidRecord, "Invalid SWITCH record");
1316 Type *OpTy = getTypeByID(Record[0]); 1402 Type *OpTy = getTypeByID(Record[0]);
1317 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 1403 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
1318 if (ValueBitWidth > 64) 1404 if (ValueBitWidth > 64)
1319 return Error("Wide integers are not supported in PNaCl bitcode"); 1405 return Error(InvalidValue,
1406 "Wide integers are not supported in PNaCl bitcode");
1320 1407
1321 Value *Cond = getValue(Record, 1, NextValueNo); 1408 Value *Cond = getValue(Record, 1, NextValueNo);
1322 BasicBlock *Default = getBasicBlock(Record[2]); 1409 BasicBlock *Default = getBasicBlock(Record[2]);
1323 if (OpTy == 0 || Cond == 0 || Default == 0) 1410 if (OpTy == 0 || Cond == 0 || Default == 0)
1324 return Error("Invalid SWITCH record"); 1411 return Error(InvalidRecord, "Invalid SWITCH record");
1325 1412
1326 unsigned NumCases = Record[3]; 1413 unsigned NumCases = Record[3];
1327 1414
1328 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 1415 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1329 1416
1330 unsigned CurIdx = 4; 1417 unsigned CurIdx = 4;
1331 for (unsigned i = 0; i != NumCases; ++i) { 1418 for (unsigned i = 0; i != NumCases; ++i) {
1332 // The PNaCl bitcode format has vestigial support for case 1419 // The PNaCl bitcode format has vestigial support for case
1333 // ranges, but we no longer support reading them because 1420 // ranges, but we no longer support reading them because
1334 // no-one produced them. 1421 // no-one produced them.
1335 // See https://code.google.com/p/nativeclient/issues/detail?id=3758 1422 // See https://code.google.com/p/nativeclient/issues/detail?id=3758
1336 unsigned NumItems = Record[CurIdx++]; 1423 unsigned NumItems = Record[CurIdx++];
1337 bool isSingleNumber = Record[CurIdx++]; 1424 bool isSingleNumber = Record[CurIdx++];
1338 if (NumItems != 1 || !isSingleNumber) 1425 if (NumItems != 1 || !isSingleNumber)
1339 return Error("Case ranges are not supported in PNaCl bitcode"); 1426 return Error(InvalidRecord,
1427 "Case ranges are not supported in PNaCl bitcode");
1340 1428
1341 APInt CaseValue(ValueBitWidth, 1429 APInt CaseValue(ValueBitWidth,
1342 NaClDecodeSignRotatedValue(Record[CurIdx++])); 1430 NaClDecodeSignRotatedValue(Record[CurIdx++]));
1343 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 1431 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
1344 SI->addCase(ConstantInt::get(Context, CaseValue), DestBB); 1432 SI->addCase(ConstantInt::get(Context, CaseValue), DestBB);
1345 } 1433 }
1346 I = SI; 1434 I = SI;
1347 break; 1435 break;
1348 } 1436 }
1349 case naclbitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 1437 case naclbitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1350 I = new UnreachableInst(Context); 1438 I = new UnreachableInst(Context);
1351 break; 1439 break;
1352 case naclbitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 1440 case naclbitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1353 if (Record.size() < 1 || ((Record.size()-1)&1)) 1441 if (Record.size() < 1 || ((Record.size()-1)&1))
1354 return Error("Invalid PHI record"); 1442 return Error(InvalidRecord, "Invalid PHI record");
1355 Type *Ty = getTypeByID(Record[0]); 1443 Type *Ty = getTypeByID(Record[0]);
1356 if (!Ty) return Error("Invalid PHI record"); 1444 if (!Ty) return Error(InvalidType, "Invalid PHI record");
1357 1445
1358 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 1446 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
1359 1447
1360 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 1448 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1361 Value *V; 1449 Value *V;
1362 // With relative value IDs, it is possible that operands have 1450 // With relative value IDs, it is possible that operands have
1363 // negative IDs (for forward references). Use a signed VBR 1451 // negative IDs (for forward references). Use a signed VBR
1364 // representation to keep the encoding small. 1452 // representation to keep the encoding small.
1365 V = getValueSigned(Record, 1+i, NextValueNo); 1453 V = getValueSigned(Record, 1+i, NextValueNo);
1366 unsigned BBIndex = Record[2+i]; 1454 unsigned BBIndex = Record[2+i];
1367 BasicBlock *BB = getBasicBlock(BBIndex); 1455 BasicBlock *BB = getBasicBlock(BBIndex);
1368 if (!V || !BB) return Error("Invalid PHI record"); 1456 if (!V || !BB)
1457 return Error(InvalidValue, "Invalid PHI record");
1369 if (Ty == IntPtrType) { 1458 if (Ty == IntPtrType) {
1370 // Delay installing scalar casts until all instructions of 1459 // Delay installing scalar casts until all instructions of
1371 // the function are rendered. This guarantees that we insert 1460 // the function are rendered. This guarantees that we insert
1372 // the conversion just before the incoming edge (or use an 1461 // the conversion just before the incoming edge (or use an
1373 // existing conversion if already installed). 1462 // existing conversion if already installed).
1374 V = ConvertOpToScalar(V, BBIndex, /* DeferInsertion = */ true); 1463 V = ConvertOpToScalar(V, BBIndex, /* DeferInsertion = */ true);
1375 } 1464 }
1376 PN->addIncoming(V, BB); 1465 PN->addIncoming(V, BB);
1377 } 1466 }
1378 I = PN; 1467 I = PN;
1379 break; 1468 break;
1380 } 1469 }
1381 1470
1382 case naclbitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [op, align] 1471 case naclbitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [op, align]
1383 if (Record.size() != 2) 1472 if (Record.size() != 2)
1384 return Error("Invalid ALLOCA record"); 1473 return Error(InvalidRecord, "Invalid ALLOCA record");
1385 Value *Size; 1474 Value *Size;
1386 unsigned OpNum = 0; 1475 unsigned OpNum = 0;
1387 if (popValue(Record, &OpNum, NextValueNo, &Size)) 1476 if (popValue(Record, &OpNum, NextValueNo, &Size))
1388 return Error("Invalid ALLOCA record"); 1477 return Error(InvalidRecord, "Invalid ALLOCA record");
1389 unsigned Align = Record[1]; 1478 unsigned Align = Record[1];
1390 I = new AllocaInst(Type::getInt8Ty(Context), Size, (1 << Align) >> 1); 1479 I = new AllocaInst(Type::getInt8Ty(Context), Size, (1 << Align) >> 1);
1391 break; 1480 break;
1392 } 1481 }
1393 case naclbitc::FUNC_CODE_INST_LOAD: { 1482 case naclbitc::FUNC_CODE_INST_LOAD: {
1394 // LOAD: [op, align, ty] 1483 // LOAD: [op, align, ty]
1395 unsigned OpNum = 0; 1484 unsigned OpNum = 0;
1396 Value *Op; 1485 Value *Op;
1397 if (popValue(Record, &OpNum, NextValueNo, &Op) || 1486 if (popValue(Record, &OpNum, NextValueNo, &Op) ||
1398 Record.size() != 3) 1487 Record.size() != 3)
1399 return Error("Invalid LOAD record"); 1488 return Error(InvalidRecord, "Invalid LOAD record");
1400 1489
1401 // Add pointer cast to op. 1490 // Add pointer cast to op.
1402 Type *T = getTypeByID(Record[2]); 1491 Type *T = getTypeByID(Record[2]);
1403 if (T == 0) 1492 if (T == 0)
1404 return Error("Invalid type for load instruction"); 1493 return Error(InvalidType, "Invalid type for load instruction");
1405 Op = ConvertOpToType(Op, T->getPointerTo(), CurBBNo); 1494 Op = ConvertOpToType(Op, T->getPointerTo(), CurBBNo);
1406 if (Op == 0) return true; 1495 if (Op == 0)
jvoung (off chromium) 2014/12/01 23:23:49 nullptr instead of 0. Actually, n/m. It may be be
Karl 2014/12/03 18:32:09 In general, I agree that we should delay. However,
1496 return Error(InvalidTypeForValue, "Can't convert cast to type");
1407 I = new LoadInst(Op, "", false, (1 << Record[OpNum]) >> 1); 1497 I = new LoadInst(Op, "", false, (1 << Record[OpNum]) >> 1);
1408 break; 1498 break;
1409 } 1499 }
1410 case naclbitc::FUNC_CODE_INST_STORE: { 1500 case naclbitc::FUNC_CODE_INST_STORE: {
1411 // STORE: [ptr, val, align] 1501 // STORE: [ptr, val, align]
1412 unsigned OpNum = 0; 1502 unsigned OpNum = 0;
1413 Value *Val, *Ptr; 1503 Value *Val, *Ptr;
1414 if (popValue(Record, &OpNum, NextValueNo, &Ptr) || 1504 if (popValue(Record, &OpNum, NextValueNo, &Ptr) ||
1415 popValue(Record, &OpNum, NextValueNo, &Val) || 1505 popValue(Record, &OpNum, NextValueNo, &Val) ||
1416 OpNum+1 != Record.size()) 1506 OpNum+1 != Record.size())
1417 return Error("Invalid STORE record"); 1507 return Error(InvalidRecord, "Invalid STORE record");
1418 Val = ConvertOpToScalar(Val, CurBBNo); 1508 Val = ConvertOpToScalar(Val, CurBBNo);
1419 Ptr = ConvertOpToType(Ptr, Val->getType()->getPointerTo(), CurBBNo); 1509 Ptr = ConvertOpToType(Ptr, Val->getType()->getPointerTo(), CurBBNo);
jvoung (off chromium) 2014/12/01 23:23:49 For loads, the code checks that ConvertOpToType re
Karl 2014/12/03 18:32:09 Good point. Adding test.
1420 I = new StoreInst(Val, Ptr, false, (1 << Record[OpNum]) >> 1); 1510 I = new StoreInst(Val, Ptr, false, (1 << Record[OpNum]) >> 1);
1421 break; 1511 break;
1422 } 1512 }
1423 case naclbitc::FUNC_CODE_INST_CALL: 1513 case naclbitc::FUNC_CODE_INST_CALL:
1424 case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: { 1514 case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: {
1425 // CALL: [cc, fnid, arg0, arg1...] 1515 // CALL: [cc, fnid, arg0, arg1...]
1426 // CALL_INDIRECT: [cc, fnid, returnty, args...] 1516 // CALL_INDIRECT: [cc, fnid, returnty, args...]
1427 if ((Record.size() < 2) || 1517 if ((Record.size() < 2) ||
1428 (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT && 1518 (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT &&
1429 Record.size() < 3)) 1519 Record.size() < 3))
1430 return Error("Invalid CALL record"); 1520 return Error(InvalidRecord, "Invalid CALL record");
1431 1521
1432 unsigned CCInfo = Record[0]; 1522 unsigned CCInfo = Record[0];
1433 1523
1434 unsigned OpNum = 1; 1524 unsigned OpNum = 1;
1435 Value *Callee; 1525 Value *Callee;
1436 if (popValue(Record, &OpNum, NextValueNo, &Callee)) 1526 if (popValue(Record, &OpNum, NextValueNo, &Callee))
1437 return Error("Invalid CALL record"); 1527 return Error(InvalidRecord, "Invalid CALL record");
1438 1528
1439 // Build function type for call. 1529 // Build function type for call.
1440 FunctionType *FTy = 0; 1530 FunctionType *FTy = 0;
1441 Type *ReturnType = 0; 1531 Type *ReturnType = 0;
1442 if (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT) { 1532 if (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT) {
1443 // Callee type has been elided, add back in. 1533 // Callee type has been elided, add back in.
1444 ReturnType = getTypeByID(Record[2]); 1534 ReturnType = getTypeByID(Record[2]);
1445 ++OpNum; 1535 ++OpNum;
1446 } else { 1536 } else {
1447 // Get type signature from callee. 1537 // Get type signature from callee.
1448 if (PointerType *OpTy = dyn_cast<PointerType>(Callee->getType())) { 1538 if (PointerType *OpTy = dyn_cast<PointerType>(Callee->getType())) {
1449 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 1539 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1450 } 1540 }
1451 if (FTy == 0) 1541 if (FTy == 0)
1452 return Error("Invalid type for CALL record"); 1542 return Error(InvalidType, "Invalid type for CALL record");
1453 } 1543 }
1454 1544
1455 unsigned NumParams = Record.size() - OpNum; 1545 unsigned NumParams = Record.size() - OpNum;
1456 if (FTy && NumParams != FTy->getNumParams()) 1546 if (FTy && NumParams != FTy->getNumParams())
1457 return Error("Invalid CALL record"); 1547 return Error(InvalidRecord, "Invalid CALL record");
1458 1548
1459 // Process call arguments. 1549 // Process call arguments.
1460 SmallVector<Value*, 6> Args; 1550 SmallVector<Value*, 6> Args;
1461 for (unsigned Index = 0; Index < NumParams; ++Index) { 1551 for (unsigned Index = 0; Index < NumParams; ++Index) {
1462 Value *Arg; 1552 Value *Arg;
1463 if (popValue(Record, &OpNum, NextValueNo, &Arg)) 1553 if (popValue(Record, &OpNum, NextValueNo, &Arg))
1464 Error("Invalid argument in CALL record"); 1554 Error(InvalidValue, "Invalid argument in CALL record");
1465 if (FTy) { 1555 if (FTy) {
1466 // Add a cast, to a pointer type if necessary, in case this 1556 // Add a cast, to a pointer type if necessary, in case this
1467 // is an intrinsic call that takes a pointer argument. 1557 // is an intrinsic call that takes a pointer argument.
1468 Arg = ConvertOpToType(Arg, FTy->getParamType(Index), CurBBNo); 1558 Arg = ConvertOpToType(Arg, FTy->getParamType(Index), CurBBNo);
1469 } else { 1559 } else {
1470 Arg = ConvertOpToScalar(Arg, CurBBNo); 1560 Arg = ConvertOpToScalar(Arg, CurBBNo);
1471 } 1561 }
1472 Args.push_back(Arg); 1562 Args.push_back(Arg);
1473 } 1563 }
1474 1564
1475 if (FTy == 0) { 1565 if (FTy == 0) {
1476 // Reconstruct the function type and cast the function pointer 1566 // Reconstruct the function type and cast the function pointer
1477 // to it. 1567 // to it.
1478 SmallVector<Type*, 6> ArgTypes; 1568 SmallVector<Type*, 6> ArgTypes;
1479 for (unsigned Index = 0; Index < NumParams; ++Index) 1569 for (unsigned Index = 0; Index < NumParams; ++Index)
1480 ArgTypes.push_back(Args[Index]->getType()); 1570 ArgTypes.push_back(Args[Index]->getType());
1481 FTy = FunctionType::get(ReturnType, ArgTypes, false); 1571 FTy = FunctionType::get(ReturnType, ArgTypes, false);
1482 Callee = ConvertOpToType(Callee, FTy->getPointerTo(), CurBBNo); 1572 Callee = ConvertOpToType(Callee, FTy->getPointerTo(), CurBBNo);
1483 } 1573 }
1484 1574
1485 // Construct call. 1575 // Construct call.
1486 I = CallInst::Create(Callee, Args); 1576 I = CallInst::Create(Callee, Args);
1487 CallingConv::ID CallingConv; 1577 CallingConv::ID CallingConv;
1488 if (!naclbitc::DecodeCallingConv(CCInfo>>1, CallingConv)) 1578 if (!naclbitc::DecodeCallingConv(CCInfo>>1, CallingConv))
1489 return Error("PNaCl bitcode contains invalid calling conventions."); 1579 return Error(InvalidValue,
1580 "PNaCl bitcode contains invalid calling conventions.");
1490 cast<CallInst>(I)->setCallingConv(CallingConv); 1581 cast<CallInst>(I)->setCallingConv(CallingConv);
1491 cast<CallInst>(I)->setTailCall(CCInfo & 1); 1582 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1492 break; 1583 break;
1493 } 1584 }
1494 case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF: 1585 case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF:
1495 // Build corresponding forward reference. 1586 // Build corresponding forward reference.
1496 if (Record.size() != 2 || 1587 if (Record.size() != 2 ||
1497 ValueList.createValueFwdRef(Record[0], getTypeByID(Record[1]))) 1588 ValueList.createValueFwdRef(Record[0], getTypeByID(Record[1])))
1498 return Error("Invalid FORWARDTYPEREF record"); 1589 return Error(InvalidRecord, "Invalid FORWARDTYPEREF record");
1499 continue; 1590 continue;
1500 } 1591 }
1501 1592
1502 if (InstallInstruction(CurBB, I)) 1593 if (std::error_code EC = InstallInstruction(CurBB, I))
1503 return true; 1594 return EC;
1504 1595
1505 // If this was a terminator instruction, move to the next block. 1596 // If this was a terminator instruction, move to the next block.
1506 if (isa<TerminatorInst>(I)) { 1597 if (isa<TerminatorInst>(I)) {
1507 ++CurBBNo; 1598 ++CurBBNo;
1508 CurBB = getBasicBlock(CurBBNo); 1599 CurBB = getBasicBlock(CurBBNo);
1509 } 1600 }
1510 1601
1511 // Non-void values get registered in the value table for future use. 1602 // Non-void values get registered in the value table for future use.
1512 if (I && !I->getType()->isVoidTy()) { 1603 if (I && !I->getType()->isVoidTy()) {
1513 Value *NewVal = I; 1604 Value *NewVal = I;
(...skipping 29 matching lines...) Expand all
1543 // Check the function list for unresolved values. 1634 // Check the function list for unresolved values.
1544 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 1635 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1545 if (A->getParent() == 0) { 1636 if (A->getParent() == 0) {
1546 // We found at least one unresolved value. Nuke them all to avoid leaks. 1637 // We found at least one unresolved value. Nuke them all to avoid leaks.
1547 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 1638 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1548 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) { 1639 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
1549 A->replaceAllUsesWith(UndefValue::get(A->getType())); 1640 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1550 delete A; 1641 delete A;
1551 } 1642 }
1552 } 1643 }
1553 return Error("Never resolved value found in function!"); 1644 return Error(InvalidValue, "Never resolved value found in function!");
1554 } 1645 }
1555 } 1646 }
1556 1647
1557 // Trim the value list down to the size it was before we parsed this function. 1648 // Trim the value list down to the size it was before we parsed this function.
1558 ValueList.shrinkTo(ModuleValueListSize); 1649 ValueList.shrinkTo(ModuleValueListSize);
1559 FunctionBBs.clear(); 1650 FunctionBBs.clear();
1560 DEBUG(dbgs() << "-> ParseFunctionBody\n"); 1651 DEBUG(dbgs() << "-> ParseFunctionBody\n");
1561 return false; 1652 return std::error_code();
1562 } 1653 }
1563 1654
1564 /// FindFunctionInStream - Find the function body in the bitcode stream 1655 /// FindFunctionInStream - Find the function body in the bitcode stream
1565 bool NaClBitcodeReader::FindFunctionInStream(Function *F, 1656 std::error_code NaClBitcodeReader::FindFunctionInStream(
1566 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 1657 Function *F,
1658 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
1567 while (DeferredFunctionInfoIterator->second == 0) { 1659 while (DeferredFunctionInfoIterator->second == 0) {
1568 if (Stream.AtEndOfStream()) 1660 if (Stream.AtEndOfStream())
1569 return Error("Could not find Function in stream"); 1661 return Error(NoFunctionInStream, "Could not find Function in stream");
1570 // ParseModule will parse the next body in the stream and set its 1662 // ParseModule will parse the next body in the stream and set its
1571 // position in the DeferredFunctionInfo map. 1663 // position in the DeferredFunctionInfo map.
1572 if (ParseModule(true)) return true; 1664 if (std::error_code EC = ParseModule(true))
1665 return EC;
1573 } 1666 }
1574 return false; 1667 return std::error_code();
1575 } 1668 }
1576 1669
1577 //===----------------------------------------------------------------------===// 1670 //===----------------------------------------------------------------------===//
1578 // GVMaterializer implementation 1671 // GVMaterializer implementation
1579 //===----------------------------------------------------------------------===// 1672 //===----------------------------------------------------------------------===//
1580 1673
1581 void NaClBitcodeReader::releaseBuffer() { Buffer.release(); } 1674 void NaClBitcodeReader::releaseBuffer() { Buffer.release(); }
1582 1675
1583 bool NaClBitcodeReader::isMaterializable(const GlobalValue *GV) const { 1676 bool NaClBitcodeReader::isMaterializable(const GlobalValue *GV) const {
1584 if (const Function *F = dyn_cast<Function>(GV)) { 1677 if (const Function *F = dyn_cast<Function>(GV)) {
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
1687 if (!I->first->use_empty()) 1780 if (!I->first->use_empty())
1688 I->first->replaceAllUsesWith(I->second); 1781 I->first->replaceAllUsesWith(I->second);
1689 I->first->eraseFromParent(); 1782 I->first->eraseFromParent();
1690 } 1783 }
1691 } 1784 }
1692 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 1785 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1693 1786
1694 return std::error_code(); 1787 return std::error_code();
1695 } 1788 }
1696 1789
1697 bool NaClBitcodeReader::InitStream() { 1790 std::error_code NaClBitcodeReader::InitStream() {
1698 if (LazyStreamer) return InitLazyStream(); 1791 if (LazyStreamer)
1792 return InitLazyStream();
1699 return InitStreamFromBuffer(); 1793 return InitStreamFromBuffer();
1700 } 1794 }
1701 1795
1702 bool NaClBitcodeReader::InitStreamFromBuffer() { 1796 std::error_code NaClBitcodeReader::InitStreamFromBuffer() {
1703 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 1797 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
1704 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 1798 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1705 1799
1706 if (Buffer->getBufferSize() & 3) 1800 if (Buffer->getBufferSize() & 3)
1707 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 1801 return Error(InvalidBitstream,
1802 "Bitcode stream should be a multiple of 4 bytes in length");
1708 1803
1709 if (Header.Read(BufPtr, BufEnd)) 1804 if (Header.Read(BufPtr, BufEnd))
1710 return Error(Header.Unsupported()); 1805 return Error(InvalidBitstream, Header.Unsupported());
1711 1806
1712 StreamFile.reset(new NaClBitstreamReader(BufPtr, BufEnd)); 1807 StreamFile.reset(new NaClBitstreamReader(BufPtr, BufEnd));
1713 Stream.init(*StreamFile); 1808 Stream.init(*StreamFile);
1714 1809
1715 if (AcceptHeader()) 1810 if (AcceptHeader())
1716 return Error(Header.Unsupported()); 1811 return Error(InvalidBitstream, Header.Unsupported());
1717 return false; 1812 return std::error_code();
1718 } 1813 }
1719 1814
1720 bool NaClBitcodeReader::InitLazyStream() { 1815 std::error_code NaClBitcodeReader::InitLazyStream() {
1721 if (Header.Read(LazyStreamer)) 1816 if (Header.Read(LazyStreamer))
1722 return Error(Header.Unsupported()); 1817 return Error(InvalidBitstream, Header.Unsupported());
1723 1818
1724 StreamFile.reset(new NaClBitstreamReader(LazyStreamer, 1819 StreamFile.reset(new NaClBitstreamReader(LazyStreamer,
1725 Header.getHeaderSize())); 1820 Header.getHeaderSize()));
1726 Stream.init(*StreamFile); 1821 Stream.init(*StreamFile);
1727 if (AcceptHeader()) 1822 if (AcceptHeader())
1728 return Error(Header.Unsupported()); 1823 return Error(InvalidBitstream, Header.Unsupported());
1729 return false; 1824 return std::error_code();
1730 } 1825 }
1731 1826
1732 //===----------------------------------------------------------------------===// 1827 //===----------------------------------------------------------------------===//
1733 // External interface 1828 // External interface
1734 //===----------------------------------------------------------------------===// 1829 //===----------------------------------------------------------------------===//
1735 1830
1736 /// getNaClLazyBitcodeModule - lazy function-at-a-time loading from a file. 1831 /// getNaClLazyBitcodeModule - lazy function-at-a-time loading from a file.
1737 /// 1832 ///
1738 Module *llvm::getNaClLazyBitcodeModule(MemoryBuffer *Buffer, 1833 ErrorOr<Module *> llvm::getNaClLazyBitcodeModule(
1739 LLVMContext& Context, 1834 MemoryBuffer *Buffer, LLVMContext& Context, bool VerboseErrors,
1740 std::string *ErrMsg, 1835 bool AcceptSupportedOnly) {
1741 bool AcceptSupportedOnly) {
1742 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 1836 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
1743 NaClBitcodeReader *R = 1837 NaClBitcodeReader *R =
1744 new NaClBitcodeReader(Buffer, Context, AcceptSupportedOnly); 1838 new NaClBitcodeReader(Buffer, Context, VerboseErrors, AcceptSupportedOnly) ;
1745 M->setMaterializer(R); 1839 M->setMaterializer(R);
1746 if (R->ParseBitcodeInto(M)) { 1840 if (std::error_code EC = R->ParseBitcodeInto(M)) {
1747 if (ErrMsg) 1841 R->releaseBuffer(); // Never take ownership on error.
1748 *ErrMsg = R->getErrorString();
1749
1750 delete M; // Also deletes R. 1842 delete M; // Also deletes R.
1751 return 0; 1843 return EC;
1752 } 1844 }
1753 1845
1754 return M; 1846 return M;
1755 } 1847 }
1756 1848
1757 1849
1758 Module *llvm::getNaClStreamedBitcodeModule(const std::string &name, 1850 Module *llvm::getNaClStreamedBitcodeModule(const std::string &name,
1759 StreamingMemoryObject *Streamer, 1851 StreamingMemoryObject *Streamer,
1760 LLVMContext &Context, 1852 LLVMContext &Context,
1853 bool VerboseErrors,
1761 std::string *ErrMsg, 1854 std::string *ErrMsg,
1762 bool AcceptSupportedOnly) { 1855 bool AcceptSupportedOnly) {
1763 Module *M = new Module(name, Context); 1856 Module *M = new Module(name, Context);
1764 NaClBitcodeReader *R = 1857 NaClBitcodeReader *R =
1765 new NaClBitcodeReader(Streamer, Context, AcceptSupportedOnly); 1858 new NaClBitcodeReader(Streamer, Context, VerboseErrors,
1859 AcceptSupportedOnly);
1766 M->setMaterializer(R); 1860 M->setMaterializer(R);
1767 if (R->ParseBitcodeInto(M)) { 1861 if (std::error_code EC = R->ParseBitcodeInto(M)) {
1768 if (ErrMsg) 1862 if (ErrMsg)
1769 *ErrMsg = R->getErrorString(); 1863 *ErrMsg = EC.message();
1770 delete M; // Also deletes R. 1864 delete M; // Also deletes R.
1771 return 0; 1865 return nullptr;
1772 } 1866 }
1773 1867
1774 return M; 1868 return M;
1775 } 1869 }
1776 1870
1777 /// NaClParseBitcodeFile - Read the specified bitcode file, returning the module . 1871 /// NaClParseBitcodeFile - Read the specified bitcode file, returning the module .
1778 /// If an error occurs, return null and fill in *ErrMsg if non-null. 1872 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1779 Module *llvm::NaClParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 1873 ErrorOr<Module *> llvm::NaClParseBitcodeFile(
1780 std::string *ErrMsg, 1874 MemoryBuffer *Buffer, LLVMContext& Context, bool VerboseErrors,
1781 bool AcceptSupportedOnly){ 1875 bool AcceptSupportedOnly){
1782 Module *M = getNaClLazyBitcodeModule(Buffer, Context, ErrMsg, 1876 ErrorOr<Module *> ModuleOrErr =
1783 AcceptSupportedOnly); 1877 getNaClLazyBitcodeModule(Buffer, Context, VerboseErrors,
1784 if (!M) return 0; 1878 AcceptSupportedOnly);
1785 1879 if (!ModuleOrErr)
1880 return ModuleOrErr;
1881 Module *M = ModuleOrErr.get();
1786 // Read in the entire module, and destroy the NaClBitcodeReader. 1882 // Read in the entire module, and destroy the NaClBitcodeReader.
1787 if (std::error_code EC = M->materializeAllPermanently()) { 1883 if (std::error_code EC = M->materializeAllPermanently()) {
1788 *ErrMsg = EC.message();
1789 delete M; 1884 delete M;
1790 return 0; 1885 return EC;
1791 } 1886 }
1792 1887
1793 // TODO: Restore the use-lists to the in-memory state when the bitcode was 1888 // TODO: Restore the use-lists to the in-memory state when the bitcode was
1794 // written. We must defer until the Module has been fully materialized. 1889 // written. We must defer until the Module has been fully materialized.
1795 1890
1796 return M; 1891 return M;
1797 } 1892 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698