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

Side by Side Diff: src/PNaClTranslator.cpp

Issue 624663002: Introduce model of global initializers in Subzero. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-subzero.git@master
Patch Set: add more tests. Created 6 years, 2 months 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 //===- subzero/src/PNaClTranslator.cpp - ICE from bitcode -----------------===// 1 //===- subzero/src/PNaClTranslator.cpp - ICE from bitcode -----------------===//
2 // 2 //
3 // The Subzero Code Generator 3 // The Subzero Code Generator
4 // 4 //
5 // This file is distributed under the University of Illinois Open Source 5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details. 6 // License. See LICENSE.TXT for details.
7 // 7 //
8 //===----------------------------------------------------------------------===// 8 //===----------------------------------------------------------------------===//
9 // 9 //
10 // This file implements the PNaCl bitcode file to Ice, to machine code 10 // This file implements the PNaCl bitcode file to Ice, to machine code
11 // translator. 11 // translator.
12 // 12 //
13 //===----------------------------------------------------------------------===// 13 //===----------------------------------------------------------------------===//
14 14
15 #include <cassert>
16 #include <memory>
17 #include <vector>
18
19 #include "llvm/Analysis/NaCl/PNaClABIProps.h" 15 #include "llvm/Analysis/NaCl/PNaClABIProps.h"
20 #include "llvm/Bitcode/NaCl/NaClBitcodeDecoders.h" 16 #include "llvm/Bitcode/NaCl/NaClBitcodeDecoders.h"
21 #include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h" 17 #include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
22 #include "llvm/Bitcode/NaCl/NaClBitcodeParser.h" 18 #include "llvm/Bitcode/NaCl/NaClBitcodeParser.h"
23 #include "llvm/Bitcode/NaCl/NaClReaderWriter.h" 19 #include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
24 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h" 23 #include "llvm/IR/Module.h"
28 #include "llvm/Support/Format.h" 24 #include "llvm/Support/Format.h"
29 #include "llvm/Support/MemoryBuffer.h" 25 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/ValueHandle.h" 27 #include "llvm/Support/ValueHandle.h"
32 28
33 #include "IceCfg.h" 29 #include "IceCfg.h"
34 #include "IceCfgNode.h" 30 #include "IceCfgNode.h"
35 #include "IceClFlags.h" 31 #include "IceClFlags.h"
36 #include "IceDefs.h" 32 #include "IceDefs.h"
33 #include "IceGlobalInits.h"
37 #include "IceInst.h" 34 #include "IceInst.h"
38 #include "IceOperand.h" 35 #include "IceOperand.h"
39 #include "IceTypeConverter.h" 36 #include "IceTypeConverter.h"
40 #include "PNaClTranslator.h" 37 #include "PNaClTranslator.h"
41 38
42 using namespace llvm; 39 using namespace llvm;
43 40
44 namespace { 41 namespace {
45 42
46 // TODO(kschimpf) Remove error recovery once implementation complete. 43 // TODO(kschimpf) Remove error recovery once implementation complete.
47 static cl::opt<bool> AllowErrorRecovery( 44 static cl::opt<bool> AllowErrorRecovery(
48 "allow-pnacl-reader-error-recovery", 45 "allow-pnacl-reader-error-recovery",
49 cl::desc("Allow error recovery when reading PNaCl bitcode."), 46 cl::desc("Allow error recovery when reading PNaCl bitcode."),
50 cl::init(false)); 47 cl::init(false));
51 48
52 // Top-level class to read PNaCl bitcode files, and translate to ICE. 49 // Top-level class to read PNaCl bitcode files, and translate to ICE.
53 class TopLevelParser : public NaClBitcodeParser { 50 class TopLevelParser : public NaClBitcodeParser {
54 TopLevelParser(const TopLevelParser &) = delete; 51 TopLevelParser(const TopLevelParser &) = delete;
55 TopLevelParser &operator=(const TopLevelParser &) = delete; 52 TopLevelParser &operator=(const TopLevelParser &) = delete;
56 53
57 public: 54 public:
58 TopLevelParser(Ice::Translator &Translator, const std::string &InputName, 55 TopLevelParser(Ice::Translator &Translator, const std::string &InputName,
59 NaClBitcodeHeader &Header, NaClBitstreamCursor &Cursor, 56 NaClBitcodeHeader &Header, NaClBitstreamCursor &Cursor,
60 bool &ErrorStatus) 57 bool &ErrorStatus)
61 : NaClBitcodeParser(Cursor), Translator(Translator), 58 : NaClBitcodeParser(Cursor), Translator(Translator),
62 Mod(new Module(InputName, getGlobalContext())), DL(PNaClDataLayout), 59 Mod(new Module(InputName, getGlobalContext())), DL(PNaClDataLayout),
63 Header(Header), TypeConverter(getLLVMContext()), 60 Header(Header), TypeConverter(getLLVMContext()),
64 ErrorStatus(ErrorStatus), NumErrors(0), NumFunctionIds(0), 61 ErrorStatus(ErrorStatus), NumErrors(0), NumFunctionIds(0),
65 NumFunctionBlocks(0), 62 NumFunctionBlocks(0) {
66 GlobalVarPlaceHolderType(convertToLLVMType(Ice::IceType_i8)) {
67 Mod->setDataLayout(PNaClDataLayout); 63 Mod->setDataLayout(PNaClDataLayout);
68 setErrStream(Translator.getContext()->getStrDump()); 64 setErrStream(Translator.getContext()->getStrDump());
69 } 65 }
70 66
71 ~TopLevelParser() override {} 67 ~TopLevelParser() override { DeleteContainerPointers(GlobalIDAddresses); }
72 68
73 Ice::Translator &getTranslator() { return Translator; } 69 Ice::Translator &getTranslator() { return Translator; }
74 70
75 // Generates error with given Message. Always returns true. 71 // Generates error with given Message. Always returns true.
76 bool Error(const std::string &Message) override { 72 bool Error(const std::string &Message) override {
77 ErrorStatus = true; 73 ErrorStatus = true;
78 ++NumErrors; 74 ++NumErrors;
79 NaClBitcodeParser::Error(Message); 75 NaClBitcodeParser::Error(Message);
80 if (!AllowErrorRecovery) 76 if (!AllowErrorRecovery)
81 report_fatal_error("Unable to continue"); 77 report_fatal_error("Unable to continue");
(...skipping 14 matching lines...) Expand all
96 92
97 /// Returns the llvm context to use. 93 /// Returns the llvm context to use.
98 LLVMContext &getLLVMContext() const { return Mod->getContext(); } 94 LLVMContext &getLLVMContext() const { return Mod->getContext(); }
99 95
100 /// Changes the size of the type list to the given size. 96 /// Changes the size of the type list to the given size.
101 void resizeTypeIDValues(unsigned NewSize) { TypeIDValues.resize(NewSize); } 97 void resizeTypeIDValues(unsigned NewSize) { TypeIDValues.resize(NewSize); }
102 98
103 /// Returns the type associated with the given index. 99 /// Returns the type associated with the given index.
104 Type *getTypeByID(unsigned ID) { 100 Type *getTypeByID(unsigned ID) {
105 // Note: method resizeTypeIDValues expands TypeIDValues 101 // Note: method resizeTypeIDValues expands TypeIDValues
106 // to the specified size, and fills elements with NULL. 102 // to the specified size, and fills elements with nullptr.
107 Type *Ty = ID < TypeIDValues.size() ? TypeIDValues[ID] : NULL; 103 Type *Ty = ID < TypeIDValues.size() ? TypeIDValues[ID] : nullptr;
108 if (Ty) 104 if (Ty)
109 return Ty; 105 return Ty;
110 return reportTypeIDAsUndefined(ID); 106 return reportTypeIDAsUndefined(ID);
111 } 107 }
112 108
113 /// Defines type for ID. 109 /// Defines type for ID.
114 void setTypeID(unsigned ID, Type *Ty) { 110 void setTypeID(unsigned ID, Type *Ty) {
115 if (ID < TypeIDValues.size() && TypeIDValues[ID] == NULL) { 111 if (ID < TypeIDValues.size() && TypeIDValues[ID] == nullptr) {
116 TypeIDValues[ID] = Ty; 112 TypeIDValues[ID] = Ty;
117 return; 113 return;
118 } 114 }
119 reportBadSetTypeID(ID, Ty); 115 reportBadSetTypeID(ID, Ty);
120 } 116 }
121 117
122 /// Sets the next function ID to the given LLVM function. 118 /// Sets the next function ID to the given LLVM function.
123 void setNextFunctionID(Function *Fcn) { 119 void setNextFunctionID(Function *Fcn) {
124 ++NumFunctionIds; 120 ++NumFunctionIds;
125 ValueIDValues.push_back(Fcn); 121 FunctionIDValues.push_back(Fcn);
126 } 122 }
127 123
128 /// Defines the next function ID as one that has an implementation 124 /// Defines the next function ID as one that has an implementation
129 /// (i.e a corresponding function block in the bitcode). 125 /// (i.e a corresponding function block in the bitcode).
130 void setNextValueIDAsImplementedFunction() { 126 void setNextValueIDAsImplementedFunction() {
131 DefiningFunctionsList.push_back(ValueIDValues.size()); 127 DefiningFunctionsList.push_back(FunctionIDValues.size());
132 } 128 }
133 129
134 /// Returns the value id that should be associated with the the 130 /// Returns the value id that should be associated with the the
135 /// current function block. Increments internal counters during call 131 /// current function block. Increments internal counters during call
136 /// so that it will be in correct position for next function block. 132 /// so that it will be in correct position for next function block.
137 unsigned getNextFunctionBlockValueID() { 133 unsigned getNextFunctionBlockValueID() {
138 if (NumFunctionBlocks >= DefiningFunctionsList.size()) 134 if (NumFunctionBlocks >= DefiningFunctionsList.size())
139 report_fatal_error( 135 report_fatal_error(
140 "More function blocks than defined function addresses"); 136 "More function blocks than defined function addresses");
141 return DefiningFunctionsList[NumFunctionBlocks++]; 137 return DefiningFunctionsList[NumFunctionBlocks++];
142 } 138 }
143 139
144 /// Returns the LLVM IR value associatd with the global value ID. 140 /// Returns the LLVM IR value associatd with the global value ID.
145 Value *getGlobalValueByID(unsigned ID) const { 141 Function *getFunctionByID(unsigned ID) const {
146 if (ID >= ValueIDValues.size()) 142 if (ID >= FunctionIDValues.size())
147 return NULL; 143 return nullptr;
148 return ValueIDValues[ID]; 144 Value *V = FunctionIDValues[ID];
145 return cast<Function>(V);
149 } 146 }
150 147
151 /// Returns the corresponding constant associated with a global value 148 /// Returns the corresponding constant associated with a global value
152 /// (i.e. relocatable). 149 /// (i.e. relocatable).
153 Ice::Constant *getOrCreateGlobalConstantByID(unsigned ID) { 150 Ice::Constant *getOrCreateGlobalConstantByID(unsigned ID) {
154 // TODO(kschimpf): Can this be built when creating global initializers? 151 // TODO(kschimpf): Can this be built when creating global initializers?
152 Ice::Constant *C;
155 if (ID >= ValueIDConstants.size()) { 153 if (ID >= ValueIDConstants.size()) {
156 if (ID >= ValueIDValues.size()) 154 C = nullptr;
157 return NULL; 155 unsigned ExpectedSize =
158 ValueIDConstants.resize(ValueIDValues.size()); 156 FunctionIDValues.size() + GlobalIDAddresses.size();
157 if (ID >= ExpectedSize)
158 ExpectedSize = ID;
159 ValueIDConstants.resize(ExpectedSize);
160 } else {
161 C = ValueIDConstants[ID];
159 } 162 }
160 Ice::Constant *C = ValueIDConstants[ID]; 163 if (C != nullptr)
161 if (C != NULL)
162 return C; 164 return C;
163 Value *V = ValueIDValues[ID]; 165
164 assert(isa<GlobalValue>(V)); 166 // If reached, no such constant exists, create one.
167 std::string Name;
168 unsigned FcnIDSize = FunctionIDValues.size();
169 if (ID < FcnIDSize) {
170 Name = FunctionIDValues[ID]->getName();
171 } else if ((ID - FcnIDSize) < GlobalIDAddresses.size()) {
172 Name = GlobalIDAddresses[ID - FcnIDSize]->getName();
173 } else {
174 std::string Buffer;
175 raw_string_ostream StrBuf(Buffer);
176 StrBuf << "Reference to global not defined: " << ID;
177 Error(StrBuf.str());
178 Name = "??";
179 }
165 C = getTranslator().getContext()->getConstantSym(getIcePointerType(), 0, 180 C = getTranslator().getContext()->getConstantSym(getIcePointerType(), 0,
Jim Stichnoth 2014/10/06 18:16:38 replace 0 with a local symbolic constant
Karl 2014/10/06 22:44:04 Done.
166 V->getName()); 181 Name);
167 ValueIDConstants[ID] = C; 182 ValueIDConstants[ID] = C;
168 return C; 183 return C;
169 } 184 }
170 185
171 /// Returns the number of function addresses (i.e. ID's) defined in 186 /// Returns the number of function addresses (i.e. ID's) defined in
172 /// the bitcode file. 187 /// the bitcode file.
173 unsigned getNumFunctionIDs() const { return NumFunctionIds; } 188 unsigned getNumFunctionIDs() const { return NumFunctionIds; }
174 189
175 /// Returns the number of global values defined in the bitcode 190 /// Returns the number of global IDs (function and global addresses)
176 /// file. 191 /// defined in the bitcode file.
177 unsigned getNumGlobalValueIDs() const { return ValueIDValues.size(); } 192 unsigned getNumGlobalIDs() const {
178 193 return FunctionIDValues.size() + GlobalIDAddresses.size();
179 /// Resizes the list of value IDs to include Count global variable
180 /// IDs.
181 void resizeValueIDsForGlobalVarCount(unsigned Count) {
182 ValueIDValues.resize(ValueIDValues.size() + Count);
183 } 194 }
184 195
185 /// Returns the global variable address associated with the given 196 /// Creates Count global addresses.
186 /// value ID. If the ID refers to a global variable address not yet 197 void CreateGlobalAddresses(size_t Count) {
187 /// defined, a placeholder is created so that we can fix it up 198 assert(GlobalIDAddresses.empty());
188 /// later. 199 for (size_t i = 0; i < Count; ++i) {
189 Constant *getOrCreateGlobalVarRef(unsigned ID) { 200 GlobalIDAddresses.push_back(new Ice::GlobalAddress());
190 if (ID >= ValueIDValues.size()) 201 }
191 return NULL;
192 if (Value *C = ValueIDValues[ID])
193 return dyn_cast<Constant>(C);
194 Constant *C = new GlobalVariable(*Mod, GlobalVarPlaceHolderType, false,
195 GlobalValue::ExternalLinkage, 0);
196 ValueIDValues[ID] = C;
197 return C;
198 } 202 }
199 203
200 /// Assigns the given global variable (address) to the given value 204 /// Returns the number of global addresses (i.e. ID's) defined in
201 /// ID. Returns true if ID is a valid global variable ID. Otherwise 205 /// the bitcode file.
202 /// returns false. 206 Ice::SizeT getNumGlobalAddresses() const { return GlobalIDAddresses.size(); }
203 bool assignGlobalVariable(GlobalVariable *GV, unsigned ID) {
204 if (ID < NumFunctionIds || ID >= ValueIDValues.size())
205 return false;
206 WeakVH &OldV = ValueIDValues[ID];
207 if (OldV == NULL) {
208 ValueIDValues[ID] = GV;
209 return true;
210 }
211 207
212 // If reached, there was a forward reference to this value. Replace it. 208 /// Returns the global address with the given index.
213 Value *PrevVal = OldV; 209 Ice::GlobalAddress *getGlobalAddress(size_t Index) {
214 GlobalVariable *Placeholder = cast<GlobalVariable>(PrevVal); 210 if (Index < GlobalIDAddresses.size())
215 Placeholder->replaceAllUsesWith( 211 return GlobalIDAddresses[Index];
216 ConstantExpr::getBitCast(GV, Placeholder->getType())); 212 std::string Buffer;
217 Placeholder->eraseFromParent(); 213 raw_string_ostream StrBuf(Buffer);
218 ValueIDValues[ID] = GV; 214 StrBuf << "Global index " << Index
219 return true; 215 << " not allowed. Out of range. Must be less than "
216 << GlobalIDAddresses.size();
217 Error(StrBuf.str());
218 // TODO(kschimpf) Remove error recovery once implementation complete.
219 if (!GlobalIDAddresses.empty())
220 return GlobalIDAddresses[0];
221 report_fatal_error("Unable to continue");
222 }
223
224 /// Returns the list of read global addresses.
225 const Ice::Translator::GlobalAddressList &getGlobalIDAddresses() {
226 return GlobalIDAddresses;
220 } 227 }
221 228
222 /// Returns the corresponding ICE type for LLVMTy. 229 /// Returns the corresponding ICE type for LLVMTy.
223 Ice::Type convertToIceType(Type *LLVMTy) { 230 Ice::Type convertToIceType(Type *LLVMTy) {
224 Ice::Type IceTy = TypeConverter.convertToIceType(LLVMTy); 231 Ice::Type IceTy = TypeConverter.convertToIceType(LLVMTy);
225 if (IceTy >= Ice::IceType_NUM) { 232 if (IceTy >= Ice::IceType_NUM) {
226 return convertToIceTypeError(LLVMTy); 233 return convertToIceTypeError(LLVMTy);
227 } 234 }
228 return IceTy; 235 return IceTy;
229 } 236 }
230 237
231 /// Returns the corresponding LLVM type for IceTy. 238 /// Returns the corresponding LLVM type for IceTy.
232 Type *convertToLLVMType(Ice::Type IceTy) const { 239 Type *convertToLLVMType(Ice::Type IceTy) const {
233 return TypeConverter.convertToLLVMType(IceTy); 240 return TypeConverter.convertToLLVMType(IceTy);
234 } 241 }
235 242
236 /// Returns the LLVM integer type with the given number of Bits. If 243 /// Returns the LLVM integer type with the given number of Bits. If
237 /// Bits is not a valid PNaCl type, returns NULL. 244 /// Bits is not a valid PNaCl type, returns nullptr.
238 Type *getLLVMIntegerType(unsigned Bits) const { 245 Type *getLLVMIntegerType(unsigned Bits) const {
239 return TypeConverter.getLLVMIntegerType(Bits); 246 return TypeConverter.getLLVMIntegerType(Bits);
240 } 247 }
241 248
242 /// Returns the LLVM vector with the given Size and Ty. If not a 249 /// Returns the LLVM vector with the given Size and Ty. If not a
243 /// valid PNaCl vector type, returns NULL. 250 /// valid PNaCl vector type, returns nullptr.
244 Type *getLLVMVectorType(unsigned Size, Ice::Type Ty) const { 251 Type *getLLVMVectorType(unsigned Size, Ice::Type Ty) const {
245 return TypeConverter.getLLVMVectorType(Size, Ty); 252 return TypeConverter.getLLVMVectorType(Size, Ty);
246 } 253 }
247 254
248 /// Returns the model for pointer types in ICE. 255 /// Returns the model for pointer types in ICE.
249 Ice::Type getIcePointerType() const { 256 Ice::Type getIcePointerType() const {
250 return TypeConverter.getIcePointerType(); 257 return TypeConverter.getIcePointerType();
251 } 258 }
252 259
253 private: 260 private:
254 // The translator associated with the parser. 261 // The translator associated with the parser.
255 Ice::Translator &Translator; 262 Ice::Translator &Translator;
256 // The parsed module. 263 // The parsed module.
257 std::unique_ptr<Module> Mod; 264 std::unique_ptr<Module> Mod;
258 // The data layout to use. 265 // The data layout to use.
259 DataLayout DL; 266 DataLayout DL;
260 // The bitcode header. 267 // The bitcode header.
261 NaClBitcodeHeader &Header; 268 NaClBitcodeHeader &Header;
262 // Converter between LLVM and ICE types. 269 // Converter between LLVM and ICE types.
263 Ice::TypeConverter TypeConverter; 270 Ice::TypeConverter TypeConverter;
264 // The exit status that should be set to true if an error occurs. 271 // The exit status that should be set to true if an error occurs.
265 bool &ErrorStatus; 272 bool &ErrorStatus;
266 // The number of errors reported. 273 // The number of errors reported.
267 unsigned NumErrors; 274 unsigned NumErrors;
268 // The types associated with each type ID. 275 // The types associated with each type ID.
269 std::vector<Type *> TypeIDValues; 276 std::vector<Type *> TypeIDValues;
270 // The (global) value IDs. 277 // The set of function value IDs.
271 std::vector<WeakVH> ValueIDValues; 278 std::vector<WeakVH> FunctionIDValues;
272 // Relocatable constants associated with ValueIDValues. 279 // The set of global addresses IDs.
280 Ice::Translator::GlobalAddressList GlobalIDAddresses;
281 // Relocatable constants associated with FunctionIDValues and
282 // GlobalIDAddresses.
273 std::vector<Ice::Constant *> ValueIDConstants; 283 std::vector<Ice::Constant *> ValueIDConstants;
274 // The number of function IDs. 284 // The number of function IDs.
275 unsigned NumFunctionIds; 285 unsigned NumFunctionIds;
276 // The number of function blocks (processed so far). 286 // The number of function blocks (processed so far).
277 unsigned NumFunctionBlocks; 287 unsigned NumFunctionBlocks;
278 // The list of value IDs (in the order found) of defining function 288 // The list of value IDs (in the order found) of defining function
279 // addresses. 289 // addresses.
280 std::vector<unsigned> DefiningFunctionsList; 290 std::vector<unsigned> DefiningFunctionsList;
281 // Cached global variable placeholder type. Used for all forward
282 // references to global variable addresses.
283 Type *GlobalVarPlaceHolderType;
284 291
285 bool ParseBlock(unsigned BlockID) override; 292 bool ParseBlock(unsigned BlockID) override;
286 293
287 /// Reports that type ID is undefined, and then returns 294 /// Reports that type ID is undefined, and then returns
288 /// the void type. 295 /// the void type.
289 Type *reportTypeIDAsUndefined(unsigned ID); 296 Type *reportTypeIDAsUndefined(unsigned ID);
290 297
291 /// Reports error about bad call to setTypeID. 298 /// Reports error about bad call to setTypeID.
292 void reportBadSetTypeID(unsigned ID, Type *Ty); 299 void reportBadSetTypeID(unsigned ID, Type *Ty);
293 300
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
373 // Default implementation. Reports that the record is not 380 // Default implementation. Reports that the record is not
374 // understood. 381 // understood.
375 void ProcessRecord() override; 382 void ProcessRecord() override;
376 383
377 // Checks if the size of the record is Size. Return true if valid. 384 // Checks if the size of the record is Size. Return true if valid.
378 // Otherwise generates an error and returns false. 385 // Otherwise generates an error and returns false.
379 bool isValidRecordSize(unsigned Size, const char *RecordName) { 386 bool isValidRecordSize(unsigned Size, const char *RecordName) {
380 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues(); 387 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
381 if (Values.size() == Size) 388 if (Values.size() == Size)
382 return true; 389 return true;
383 ReportRecordSizeError(Size, RecordName, NULL); 390 ReportRecordSizeError(Size, RecordName, nullptr);
384 return false; 391 return false;
385 } 392 }
386 393
387 // Checks if the size of the record is at least as large as the 394 // Checks if the size of the record is at least as large as the
388 // LowerLimit. Returns true if valid. Otherwise generates an error 395 // LowerLimit. Returns true if valid. Otherwise generates an error
389 // and returns false. 396 // and returns false.
390 bool isValidRecordSizeAtLeast(unsigned LowerLimit, const char *RecordName) { 397 bool isValidRecordSizeAtLeast(unsigned LowerLimit, const char *RecordName) {
391 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues(); 398 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
392 if (Values.size() >= LowerLimit) 399 if (Values.size() >= LowerLimit)
393 return true; 400 return true;
(...skipping 17 matching lines...) Expand all
411 // valid. Otherwise generates an error and returns false. 418 // valid. Otherwise generates an error and returns false.
412 bool isValidRecordSizeInRange(unsigned LowerLimit, unsigned UpperLimit, 419 bool isValidRecordSizeInRange(unsigned LowerLimit, unsigned UpperLimit,
413 const char *RecordName) { 420 const char *RecordName) {
414 return isValidRecordSizeAtLeast(LowerLimit, RecordName) || 421 return isValidRecordSizeAtLeast(LowerLimit, RecordName) ||
415 isValidRecordSizeAtMost(UpperLimit, RecordName); 422 isValidRecordSizeAtMost(UpperLimit, RecordName);
416 } 423 }
417 424
418 private: 425 private:
419 /// Generates a record size error. ExpectedSize is the number 426 /// Generates a record size error. ExpectedSize is the number
420 /// of elements expected. RecordName is the name of the kind of 427 /// of elements expected. RecordName is the name of the kind of
421 /// record that has incorrect size. ContextMessage (if not NULL) 428 /// record that has incorrect size. ContextMessage (if not nullptr)
422 /// is appended to "record expects" to describe how ExpectedSize 429 /// is appended to "record expects" to describe how ExpectedSize
423 /// should be interpreted. 430 /// should be interpreted.
424 void ReportRecordSizeError(unsigned ExpectedSize, const char *RecordName, 431 void ReportRecordSizeError(unsigned ExpectedSize, const char *RecordName,
425 const char *ContextMessage); 432 const char *ContextMessage);
426 }; 433 };
427 434
428 void BlockParserBaseClass::ReportRecordSizeError(unsigned ExpectedSize, 435 void BlockParserBaseClass::ReportRecordSizeError(unsigned ExpectedSize,
429 const char *RecordName, 436 const char *RecordName,
430 const char *ContextMessage) { 437 const char *ContextMessage) {
431 std::string Buffer; 438 std::string Buffer;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
470 477
471 private: 478 private:
472 // The type ID that will be associated with the next type defining 479 // The type ID that will be associated with the next type defining
473 // record in the types block. 480 // record in the types block.
474 unsigned NextTypeId; 481 unsigned NextTypeId;
475 482
476 void ProcessRecord() override; 483 void ProcessRecord() override;
477 }; 484 };
478 485
479 void TypesParser::ProcessRecord() { 486 void TypesParser::ProcessRecord() {
480 Type *Ty = NULL; 487 Type *Ty = nullptr;
481 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues(); 488 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
482 switch (Record.GetCode()) { 489 switch (Record.GetCode()) {
483 case naclbitc::TYPE_CODE_NUMENTRY: 490 case naclbitc::TYPE_CODE_NUMENTRY:
484 // NUMENTRY: [numentries] 491 // NUMENTRY: [numentries]
485 if (!isValidRecordSize(1, "Type count")) 492 if (!isValidRecordSize(1, "Type count"))
486 return; 493 return;
487 Context->resizeTypeIDValues(Values[0]); 494 Context->resizeTypeIDValues(Values[0]);
488 return; 495 return;
489 case naclbitc::TYPE_CODE_VOID: 496 case naclbitc::TYPE_CODE_VOID:
490 // VOID 497 // VOID
(...skipping 11 matching lines...) Expand all
502 // DOUBLE 509 // DOUBLE
503 if (!isValidRecordSize(0, "Type double")) 510 if (!isValidRecordSize(0, "Type double"))
504 return; 511 return;
505 Ty = Context->convertToLLVMType(Ice::IceType_f64); 512 Ty = Context->convertToLLVMType(Ice::IceType_f64);
506 break; 513 break;
507 case naclbitc::TYPE_CODE_INTEGER: 514 case naclbitc::TYPE_CODE_INTEGER:
508 // INTEGER: [width] 515 // INTEGER: [width]
509 if (!isValidRecordSize(1, "Type integer")) 516 if (!isValidRecordSize(1, "Type integer"))
510 return; 517 return;
511 Ty = Context->getLLVMIntegerType(Values[0]); 518 Ty = Context->getLLVMIntegerType(Values[0]);
512 if (Ty == NULL) { 519 if (Ty == nullptr) {
513 std::string Buffer; 520 std::string Buffer;
514 raw_string_ostream StrBuf(Buffer); 521 raw_string_ostream StrBuf(Buffer);
515 StrBuf << "Type integer record with invalid bitsize: " << Values[0]; 522 StrBuf << "Type integer record with invalid bitsize: " << Values[0];
516 Error(StrBuf.str()); 523 Error(StrBuf.str());
517 // TODO(kschimpf) Remove error recovery once implementation complete. 524 // TODO(kschimpf) Remove error recovery once implementation complete.
518 // Fix type so that we can continue. 525 // Fix type so that we can continue.
519 Ty = Context->convertToLLVMType(Ice::IceType_i32); 526 Ty = Context->convertToLLVMType(Ice::IceType_i32);
520 } 527 }
521 break; 528 break;
522 case naclbitc::TYPE_CODE_VECTOR: { 529 case naclbitc::TYPE_CODE_VECTOR: {
523 // VECTOR: [numelts, eltty] 530 // VECTOR: [numelts, eltty]
524 if (!isValidRecordSize(2, "Type vector")) 531 if (!isValidRecordSize(2, "Type vector"))
525 return; 532 return;
526 Type *BaseTy = Context->getTypeByID(Values[1]); 533 Type *BaseTy = Context->getTypeByID(Values[1]);
527 Ty = Context->getLLVMVectorType(Values[0], 534 Ty = Context->getLLVMVectorType(Values[0],
528 Context->convertToIceType(BaseTy)); 535 Context->convertToIceType(BaseTy));
529 if (Ty == NULL) { 536 if (Ty == nullptr) {
530 std::string Buffer; 537 std::string Buffer;
531 raw_string_ostream StrBuf(Buffer); 538 raw_string_ostream StrBuf(Buffer);
532 StrBuf << "Invalid type vector record: <" << Values[0] << " x " << *BaseTy 539 StrBuf << "Invalid type vector record: <" << Values[0] << " x " << *BaseTy
533 << ">"; 540 << ">";
534 Error(StrBuf.str()); 541 Error(StrBuf.str());
535 Ty = Context->convertToLLVMType(Ice::IceType_void); 542 Ty = Context->convertToLLVMType(Ice::IceType_void);
536 } 543 }
537 break; 544 break;
538 } 545 }
539 case naclbitc::TYPE_CODE_FUNCTION: { 546 case naclbitc::TYPE_CODE_FUNCTION: {
540 // FUNCTION: [vararg, retty, paramty x N] 547 // FUNCTION: [vararg, retty, paramty x N]
541 if (!isValidRecordSizeAtLeast(2, "Type signature")) 548 if (!isValidRecordSizeAtLeast(2, "Type signature"))
542 return; 549 return;
543 SmallVector<Type *, 8> ArgTys; 550 SmallVector<Type *, 8> ArgTys;
544 for (unsigned i = 2, e = Values.size(); i != e; ++i) { 551 for (unsigned i = 2, e = Values.size(); i != e; ++i) {
545 ArgTys.push_back(Context->getTypeByID(Values[i])); 552 ArgTys.push_back(Context->getTypeByID(Values[i]));
546 } 553 }
547 Ty = FunctionType::get(Context->getTypeByID(Values[1]), ArgTys, Values[0]); 554 Ty = FunctionType::get(Context->getTypeByID(Values[1]), ArgTys, Values[0]);
548 break; 555 break;
549 } 556 }
550 default: 557 default:
551 BlockParserBaseClass::ProcessRecord(); 558 BlockParserBaseClass::ProcessRecord();
552 return; 559 return;
553 } 560 }
554 // If Ty not defined, assume error. Use void as filler. 561 // If Ty not defined, assume error. Use void as filler.
555 if (Ty == NULL) 562 if (Ty == nullptr)
556 Ty = Context->convertToLLVMType(Ice::IceType_void); 563 Ty = Context->convertToLLVMType(Ice::IceType_void);
557 Context->setTypeID(NextTypeId++, Ty); 564 Context->setTypeID(NextTypeId++, Ty);
558 } 565 }
559 566
560 /// Parses the globals block (i.e. global variables). 567 /// Parses the globals block (i.e. global variables).
561 class GlobalsParser : public BlockParserBaseClass { 568 class GlobalsParser : public BlockParserBaseClass {
562 public: 569 public:
563 GlobalsParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser) 570 GlobalsParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser)
564 : BlockParserBaseClass(BlockID, EnclosingParser), InitializersNeeded(0), 571 : BlockParserBaseClass(BlockID, EnclosingParser), InitializersNeeded(0),
565 Alignment(1), IsConstant(false) { 572 NextGlobalID(0), CurrentAddress(&DummyAddress) {}
566 NextGlobalID = Context->getNumFunctionIDs();
567 }
568 573
569 ~GlobalsParser() override {} 574 ~GlobalsParser() override {}
570 575
571 private: 576 private:
572 // Holds the sequence of initializers for the global. 577 // Keeps track of how many initializers are expected for the global variable
573 SmallVector<Constant *, 10> Initializers; 578 // being built.
574
575 // Keeps track of how many initializers are expected for
576 // the global variable being built.
577 unsigned InitializersNeeded; 579 unsigned InitializersNeeded;
578 580
579 // The alignment assumed for the global variable being built.
580 unsigned Alignment;
581
582 // True if the global variable being built is a constant.
583 bool IsConstant;
584
585 // The index of the next global variable. 581 // The index of the next global variable.
586 unsigned NextGlobalID; 582 unsigned NextGlobalID;
587 583
584 // Holds the current global address whose initializer is being defined.
585 Ice::GlobalAddress *CurrentAddress;
586
587 // Dummy global address to guarantee CurrentAddress is always defined
588 // (allowing code to not need to check if CurrentAddress is nullptr).
589 Ice::GlobalAddress DummyAddress;
590
588 void ExitBlock() override { 591 void ExitBlock() override {
589 verifyNoMissingInitializers(); 592 verifyNoMissingInitializers();
590 unsigned NumIDs = Context->getNumGlobalValueIDs(); 593 unsigned NumIDs = Context->getNumGlobalAddresses();
591 if (NextGlobalID < NumIDs) { 594 if (NextGlobalID < NumIDs) {
592 unsigned NumFcnIDs = Context->getNumFunctionIDs();
593 std::string Buffer; 595 std::string Buffer;
594 raw_string_ostream StrBuf(Buffer); 596 raw_string_ostream StrBuf(Buffer);
595 StrBuf << "Globals block expects " << (NumIDs - NumFcnIDs) 597 StrBuf << "Globals block expects " << NumIDs
596 << " global definitions. Found: " << (NextGlobalID - NumFcnIDs); 598 << " global definitions. Found: " << NextGlobalID;
597 Error(StrBuf.str()); 599 Error(StrBuf.str());
598 } 600 }
599 BlockParserBaseClass::ExitBlock(); 601 BlockParserBaseClass::ExitBlock();
600 } 602 }
601 603
602 void ProcessRecord() override; 604 void ProcessRecord() override;
603 605
604 // Checks if the number of initializers needed is the same as the 606 // Checks if the number of initializers for the CurrentAddress is the same as
605 // number found in the bitcode file. If different, and error message 607 // the number found in the bitcode file. If different, and error message is
606 // is generated, and the internal state of the parser is fixed so 608 // generated, and the internal state of the parser is fixed so this condition
607 // this condition is no longer violated. 609 // is no longer violated.
608 void verifyNoMissingInitializers() { 610 void verifyNoMissingInitializers() {
609 if (InitializersNeeded != Initializers.size()) { 611 size_t NumInits = CurrentAddress->getInitializers().size();
612 if (InitializersNeeded != NumInits) {
610 std::string Buffer; 613 std::string Buffer;
611 raw_string_ostream StrBuf(Buffer); 614 raw_string_ostream StrBuf(Buffer);
612 StrBuf << "Global variable @g" 615 StrBuf << "Global variable @g" << NextGlobalID << " expected "
613 << (NextGlobalID - Context->getNumFunctionIDs()) << " expected "
614 << InitializersNeeded << " initializer"; 616 << InitializersNeeded << " initializer";
615 if (InitializersNeeded > 1) 617 if (InitializersNeeded > 1)
616 StrBuf << "s"; 618 StrBuf << "s";
617 StrBuf << ". Found: " << Initializers.size(); 619 StrBuf << ". Found: " << NumInits;
618 Error(StrBuf.str());
619 // TODO(kschimpf) Remove error recovery once implementation complete.
620 // Fix up state so that we can continue.
621 InitializersNeeded = Initializers.size();
622 installGlobalVar();
623 }
624 }
625
626 // Reserves a slot in the list of initializers being built. If there
627 // isn't room for the slot, an error message is generated.
628 void reserveInitializer(const char *RecordName) {
629 if (InitializersNeeded <= Initializers.size()) {
630 Error(std::string(RecordName) +
631 " record: Too many initializers, ignoring.");
632 }
633 }
634
635 // Takes the initializers (and other parser state values) and
636 // installs a global variable (with the initializers) into the list
637 // of ValueIDs.
638 void installGlobalVar() {
639 Constant *Init = NULL;
640 switch (Initializers.size()) {
641 case 0:
642 Error("No initializer for global variable in global vars block");
643 return;
644 case 1:
645 Init = Initializers[0];
646 break;
647 default:
648 Init = ConstantStruct::getAnon(Context->getLLVMContext(), Initializers,
649 true);
650 break;
651 }
652 GlobalVariable *GV =
653 new GlobalVariable(*Context->getModule(), Init->getType(), IsConstant,
654 GlobalValue::InternalLinkage, Init, "");
655 GV->setAlignment(Alignment);
656 if (!Context->assignGlobalVariable(GV, NextGlobalID)) {
657 std::string Buffer;
658 raw_string_ostream StrBuf(Buffer);
659 StrBuf << "Defining global V[" << NextGlobalID
660 << "] not allowed. Out of range.";
661 Error(StrBuf.str()); 620 Error(StrBuf.str());
662 } 621 }
663 ++NextGlobalID;
664 Initializers.clear();
665 InitializersNeeded = 0;
666 Alignment = 1;
667 IsConstant = false;
668 } 622 }
669 }; 623 };
670 624
671 void GlobalsParser::ProcessRecord() { 625 void GlobalsParser::ProcessRecord() {
672 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues(); 626 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
673 switch (Record.GetCode()) { 627 switch (Record.GetCode()) {
674 case naclbitc::GLOBALVAR_COUNT: 628 case naclbitc::GLOBALVAR_COUNT:
675 // COUNT: [n] 629 // COUNT: [n]
676 if (!isValidRecordSize(1, "Globals count")) 630 if (!isValidRecordSize(1, "Globals count"))
677 return; 631 return;
678 if (NextGlobalID != Context->getNumFunctionIDs()) { 632 if (NextGlobalID != Context->getNumGlobalAddresses()) {
679 Error("Globals count record not first in block."); 633 Error("Globals count record not first in block.");
680 return; 634 return;
681 } 635 }
682 verifyNoMissingInitializers(); 636 Context->CreateGlobalAddresses(Values[0]);
683 Context->resizeValueIDsForGlobalVarCount(Values[0]);
684 return; 637 return;
685 case naclbitc::GLOBALVAR_VAR: { 638 case naclbitc::GLOBALVAR_VAR: {
686 // VAR: [align, isconst] 639 // VAR: [align, isconst]
687 if (!isValidRecordSize(2, "Globals variable")) 640 if (!isValidRecordSize(2, "Globals variable"))
688 return; 641 return;
689 verifyNoMissingInitializers(); 642 verifyNoMissingInitializers();
690 InitializersNeeded = 1; 643 InitializersNeeded = 1;
691 Initializers.clear(); 644 CurrentAddress = Context->getGlobalAddress(NextGlobalID);
692 Alignment = (1 << Values[0]) >> 1; 645 CurrentAddress->setAlignment((1 << Values[0]) >> 1);
693 IsConstant = Values[1] != 0; 646 CurrentAddress->setIsConstant(Values[1] != 0);
647 ++NextGlobalID;
694 return; 648 return;
695 } 649 }
696 case naclbitc::GLOBALVAR_COMPOUND: 650 case naclbitc::GLOBALVAR_COMPOUND:
697 // COMPOUND: [size] 651 // COMPOUND: [size]
698 if (!isValidRecordSize(1, "globals compound")) 652 if (!isValidRecordSize(1, "globals compound"))
699 return; 653 return;
700 if (Initializers.size() > 0 || InitializersNeeded != 1) { 654 if (!CurrentAddress->getInitializers().empty()) {
701 Error("Globals compound record not first initializer"); 655 Error("Globals compound record not first initializer");
702 return; 656 return;
703 } 657 }
704 if (Values[0] < 2) { 658 if (Values[0] < 2) {
705 std::string Buffer; 659 std::string Buffer;
706 raw_string_ostream StrBuf(Buffer); 660 raw_string_ostream StrBuf(Buffer);
707 StrBuf << "Globals compound record size invalid. Found: " << Values[0]; 661 StrBuf << "Globals compound record size invalid. Found: " << Values[0];
708 Error(StrBuf.str()); 662 Error(StrBuf.str());
709 return; 663 return;
710 } 664 }
711 InitializersNeeded = Values[0]; 665 InitializersNeeded = Values[0];
712 return; 666 return;
713 case naclbitc::GLOBALVAR_ZEROFILL: { 667 case naclbitc::GLOBALVAR_ZEROFILL: {
714 // ZEROFILL: [size] 668 // ZEROFILL: [size]
715 if (!isValidRecordSize(1, "Globals zerofill")) 669 if (!isValidRecordSize(1, "Globals zerofill"))
716 return; 670 return;
717 reserveInitializer("Globals zerofill"); 671 CurrentAddress->addInitializer(
718 Type *Ty = 672 new Ice::GlobalAddress::ZeroInitializer(Values[0]));
719 ArrayType::get(Context->convertToLLVMType(Ice::IceType_i8), Values[0]);
720 Constant *Zero = ConstantAggregateZero::get(Ty);
721 Initializers.push_back(Zero);
722 break; 673 break;
723 } 674 }
724 case naclbitc::GLOBALVAR_DATA: { 675 case naclbitc::GLOBALVAR_DATA: {
725 // DATA: [b0, b1, ...] 676 // DATA: [b0, b1, ...]
726 if (!isValidRecordSizeAtLeast(1, "Globals data")) 677 if (!isValidRecordSizeAtLeast(1, "Globals data"))
727 return; 678 return;
728 reserveInitializer("Globals data"); 679 CurrentAddress->addInitializer(
729 unsigned Size = Values.size(); 680 new Ice::GlobalAddress::DataInitializer(Values));
730 SmallVector<uint8_t, 32> Buf;
731 for (unsigned i = 0; i < Size; ++i)
732 Buf.push_back(static_cast<uint8_t>(Values[i]));
733 Constant *Init = ConstantDataArray::get(
734 Context->getLLVMContext(), ArrayRef<uint8_t>(Buf.data(), Buf.size()));
735 Initializers.push_back(Init);
736 break; 681 break;
737 } 682 }
738 case naclbitc::GLOBALVAR_RELOC: { 683 case naclbitc::GLOBALVAR_RELOC: {
739 // RELOC: [val, [addend]] 684 // RELOC: [val, [addend]]
740 if (!isValidRecordSizeInRange(1, 2, "Globals reloc")) 685 if (!isValidRecordSizeInRange(1, 2, "Globals reloc"))
741 return; 686 return;
742 Constant *BaseVal = Context->getOrCreateGlobalVarRef(Values[0]); 687 unsigned Index = Values[0];
743 if (BaseVal == NULL) { 688 Ice::SizeT Offset = 0;
744 std::string Buffer; 689 if (Values.size() == 2)
745 raw_string_ostream StrBuf(Buffer); 690 Offset = Values[1];
746 StrBuf << "Can't find global relocation value: " << Values[0]; 691 unsigned NumFunctions = Context->getNumFunctionIDs();
747 Error(StrBuf.str()); 692 if (Index < NumFunctions) {
748 return; 693 llvm::Function *Fcn = Context->getFunctionByID(Index);
694 Ice::GlobalAddress::RelocationAddress Addr(Fcn);
695 CurrentAddress->addInitializer(
696 new Ice::GlobalAddress::RelocInitializer(Addr, Offset));
697 } else {
698 Ice::GlobalAddress::RelocationAddress Addr(
699 Context->getGlobalAddress(Index - NumFunctions));
700 CurrentAddress->addInitializer(
701 new Ice::GlobalAddress::RelocInitializer(Addr, Offset));
749 } 702 }
750 Type *IntPtrType = Context->convertToLLVMType(Context->getIcePointerType());
751 Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType);
752 if (Values.size() == 2) {
753 Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType, Values[1]));
754 }
755 Initializers.push_back(Val);
756 break; 703 break;
757 } 704 }
758 default: 705 default:
759 BlockParserBaseClass::ProcessRecord(); 706 BlockParserBaseClass::ProcessRecord();
760 return; 707 return;
761 } 708 }
762 // If reached, just processed another initializer. See if time
763 // to install global.
764 if (InitializersNeeded == Initializers.size())
765 installGlobalVar();
766 } 709 }
767 710
768 /// Base class for parsing a valuesymtab block in the bitcode file. 711 /// Base class for parsing a valuesymtab block in the bitcode file.
769 class ValuesymtabParser : public BlockParserBaseClass { 712 class ValuesymtabParser : public BlockParserBaseClass {
770 ValuesymtabParser(const ValuesymtabParser &) = delete; 713 ValuesymtabParser(const ValuesymtabParser &) = delete;
771 void operator=(const ValuesymtabParser &) = delete; 714 void operator=(const ValuesymtabParser &) = delete;
772 715
773 public: 716 public:
774 ValuesymtabParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser) 717 ValuesymtabParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser)
775 : BlockParserBaseClass(BlockID, EnclosingParser) {} 718 : BlockParserBaseClass(BlockID, EnclosingParser) {}
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
831 class FunctionParser : public BlockParserBaseClass { 774 class FunctionParser : public BlockParserBaseClass {
832 FunctionParser(const FunctionParser &) = delete; 775 FunctionParser(const FunctionParser &) = delete;
833 FunctionParser &operator=(const FunctionParser &) = delete; 776 FunctionParser &operator=(const FunctionParser &) = delete;
834 friend class FunctionValuesymtabParser; 777 friend class FunctionValuesymtabParser;
835 778
836 public: 779 public:
837 FunctionParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser) 780 FunctionParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser)
838 : BlockParserBaseClass(BlockID, EnclosingParser), 781 : BlockParserBaseClass(BlockID, EnclosingParser),
839 Func(new Ice::Cfg(getTranslator().getContext())), CurrentBbIndex(0), 782 Func(new Ice::Cfg(getTranslator().getContext())), CurrentBbIndex(0),
840 FcnId(Context->getNextFunctionBlockValueID()), 783 FcnId(Context->getNextFunctionBlockValueID()),
841 LLVMFunc(cast<Function>(Context->getGlobalValueByID(FcnId))), 784 LLVMFunc(Context->getFunctionByID(FcnId)),
842 CachedNumGlobalValueIDs(Context->getNumGlobalValueIDs()), 785 CachedNumGlobalValueIDs(Context->getNumGlobalIDs()),
843 NextLocalInstIndex(Context->getNumGlobalValueIDs()), 786 NextLocalInstIndex(Context->getNumGlobalIDs()),
844 InstIsTerminating(false) { 787 InstIsTerminating(false) {
845 Func->setFunctionName(LLVMFunc->getName()); 788 Func->setFunctionName(LLVMFunc->getName());
846 Func->setReturnType(Context->convertToIceType(LLVMFunc->getReturnType())); 789 Func->setReturnType(Context->convertToIceType(LLVMFunc->getReturnType()));
847 Func->setInternal(LLVMFunc->hasInternalLinkage()); 790 Func->setInternal(LLVMFunc->hasInternalLinkage());
848 CurrentNode = InstallNextBasicBlock(); 791 CurrentNode = InstallNextBasicBlock();
849 Func->setEntryNode(CurrentNode); 792 Func->setEntryNode(CurrentNode);
850 for (auto ArgI = LLVMFunc->arg_begin(), ArgE = LLVMFunc->arg_end(); 793 for (auto ArgI = LLVMFunc->arg_begin(), ArgE = LLVMFunc->arg_end();
851 ArgI != ArgE; ++ArgI) { 794 ArgI != ArgE; ++ArgI) {
852 Func->addArg(getNextInstVar(Context->convertToIceType(ArgI->getType()))); 795 Func->addArg(getNextInstVar(Context->convertToIceType(ArgI->getType())));
853 } 796 }
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
949 return Func->makeVariable(Ty); 892 return Func->makeVariable(Ty);
950 } 893 }
951 894
952 // Generates the next available local variable using the given type. 895 // Generates the next available local variable using the given type.
953 Ice::Variable *getNextInstVar(Ice::Type Ty) { 896 Ice::Variable *getNextInstVar(Ice::Type Ty) {
954 assert(NextLocalInstIndex >= CachedNumGlobalValueIDs); 897 assert(NextLocalInstIndex >= CachedNumGlobalValueIDs);
955 // Before creating one, see if a forwardtyperef has already defined it. 898 // Before creating one, see if a forwardtyperef has already defined it.
956 uint32_t LocalIndex = NextLocalInstIndex - CachedNumGlobalValueIDs; 899 uint32_t LocalIndex = NextLocalInstIndex - CachedNumGlobalValueIDs;
957 if (LocalIndex < LocalOperands.size()) { 900 if (LocalIndex < LocalOperands.size()) {
958 Ice::Operand *Op = LocalOperands[LocalIndex]; 901 Ice::Operand *Op = LocalOperands[LocalIndex];
959 if (Op != NULL) { 902 if (Op != nullptr) {
960 if (Ice::Variable *Var = dyn_cast<Ice::Variable>(Op)) { 903 if (Ice::Variable *Var = dyn_cast<Ice::Variable>(Op)) {
961 if (Var->getType() == Ty) { 904 if (Var->getType() == Ty) {
962 ++NextLocalInstIndex; 905 ++NextLocalInstIndex;
963 return Var; 906 return Var;
964 } 907 }
965 } 908 }
966 std::string Buffer; 909 std::string Buffer;
967 raw_string_ostream StrBuf(Buffer); 910 raw_string_ostream StrBuf(Buffer);
968 StrBuf << "Illegal forward referenced instruction (" 911 StrBuf << "Illegal forward referenced instruction ("
969 << NextLocalInstIndex << "): " << *Op; 912 << NextLocalInstIndex << "): " << *Op;
(...skipping 30 matching lines...) Expand all
1000 } 943 }
1001 uint32_t LocalIndex = Index - CachedNumGlobalValueIDs; 944 uint32_t LocalIndex = Index - CachedNumGlobalValueIDs;
1002 if (LocalIndex >= LocalOperands.size()) { 945 if (LocalIndex >= LocalOperands.size()) {
1003 std::string Buffer; 946 std::string Buffer;
1004 raw_string_ostream StrBuf(Buffer); 947 raw_string_ostream StrBuf(Buffer);
1005 StrBuf << "Value index " << Index << " not defined!"; 948 StrBuf << "Value index " << Index << " not defined!";
1006 Error(StrBuf.str()); 949 Error(StrBuf.str());
1007 report_fatal_error("Unable to continue"); 950 report_fatal_error("Unable to continue");
1008 } 951 }
1009 Ice::Operand *Op = LocalOperands[LocalIndex]; 952 Ice::Operand *Op = LocalOperands[LocalIndex];
1010 if (Op == NULL) { 953 if (Op == nullptr) {
1011 std::string Buffer; 954 std::string Buffer;
1012 raw_string_ostream StrBuf(Buffer); 955 raw_string_ostream StrBuf(Buffer);
1013 StrBuf << "Value index " << Index << " not defined!"; 956 StrBuf << "Value index " << Index << " not defined!";
1014 Error(StrBuf.str()); 957 Error(StrBuf.str());
1015 report_fatal_error("Unable to continue"); 958 report_fatal_error("Unable to continue");
1016 } 959 }
1017 return Op; 960 return Op;
1018 } 961 }
1019 962
1020 // Sets element Index (in the local operands list) to Op. 963 // Sets element Index (in the local operands list) to Op.
1021 void setOperand(uint32_t Index, Ice::Operand *Op) { 964 void setOperand(uint32_t Index, Ice::Operand *Op) {
1022 assert(Op); 965 assert(Op);
1023 // Check if simple push works. 966 // Check if simple push works.
1024 uint32_t LocalIndex = Index - CachedNumGlobalValueIDs; 967 uint32_t LocalIndex = Index - CachedNumGlobalValueIDs;
1025 if (LocalIndex == LocalOperands.size()) { 968 if (LocalIndex == LocalOperands.size()) {
1026 LocalOperands.push_back(Op); 969 LocalOperands.push_back(Op);
1027 return; 970 return;
1028 } 971 }
1029 972
1030 // Must be forward reference, expand vector to accommodate. 973 // Must be forward reference, expand vector to accommodate.
1031 if (LocalIndex >= LocalOperands.size()) 974 if (LocalIndex >= LocalOperands.size())
1032 LocalOperands.resize(LocalIndex + 1); 975 LocalOperands.resize(LocalIndex + 1);
1033 976
1034 // If element not defined, set it. 977 // If element not defined, set it.
1035 Ice::Operand *OldOp = LocalOperands[LocalIndex]; 978 Ice::Operand *OldOp = LocalOperands[LocalIndex];
1036 if (OldOp == NULL) { 979 if (OldOp == nullptr) {
1037 LocalOperands[LocalIndex] = Op; 980 LocalOperands[LocalIndex] = Op;
1038 return; 981 return;
1039 } 982 }
1040 983
1041 // See if forward reference matches. 984 // See if forward reference matches.
1042 if (OldOp == Op) 985 if (OldOp == Op)
1043 return; 986 return;
1044 987
1045 // Error has occurred. 988 // Error has occurred.
1046 std::string Buffer; 989 std::string Buffer;
(...skipping 624 matching lines...) Expand 10 before | Expand all | Expand 10 after
1671 CurrentNode->appendInst( 1614 CurrentNode->appendInst(
1672 Ice::InstRet::create(Func, getRelativeOperand(Values[0], BaseIndex))); 1615 Ice::InstRet::create(Func, getRelativeOperand(Values[0], BaseIndex)));
1673 } 1616 }
1674 InstIsTerminating = true; 1617 InstIsTerminating = true;
1675 break; 1618 break;
1676 } 1619 }
1677 case naclbitc::FUNC_CODE_INST_BR: { 1620 case naclbitc::FUNC_CODE_INST_BR: {
1678 if (Values.size() == 1) { 1621 if (Values.size() == 1) {
1679 // BR: [bb#] 1622 // BR: [bb#]
1680 Ice::CfgNode *Block = getBranchBasicBlock(Values[0]); 1623 Ice::CfgNode *Block = getBranchBasicBlock(Values[0]);
1681 if (Block == NULL) 1624 if (Block == nullptr)
1682 return; 1625 return;
1683 CurrentNode->appendInst(Ice::InstBr::create(Func, Block)); 1626 CurrentNode->appendInst(Ice::InstBr::create(Func, Block));
1684 } else { 1627 } else {
1685 // BR: [bb#, bb#, opval] 1628 // BR: [bb#, bb#, opval]
1686 if (!isValidRecordSize(3, "function block branch")) 1629 if (!isValidRecordSize(3, "function block branch"))
1687 return; 1630 return;
1688 Ice::Operand *Cond = getRelativeOperand(Values[2], BaseIndex); 1631 Ice::Operand *Cond = getRelativeOperand(Values[2], BaseIndex);
1689 if (Cond->getType() != Ice::IceType_i1) { 1632 if (Cond->getType() != Ice::IceType_i1) {
1690 std::string Buffer; 1633 std::string Buffer;
1691 raw_string_ostream StrBuf(Buffer); 1634 raw_string_ostream StrBuf(Buffer);
1692 StrBuf << "Branch condition " << *Cond << " not i1. Found: " 1635 StrBuf << "Branch condition " << *Cond << " not i1. Found: "
1693 << Cond->getType(); 1636 << Cond->getType();
1694 Error(StrBuf.str()); 1637 Error(StrBuf.str());
1695 return; 1638 return;
1696 } 1639 }
1697 Ice::CfgNode *ThenBlock = getBranchBasicBlock(Values[0]); 1640 Ice::CfgNode *ThenBlock = getBranchBasicBlock(Values[0]);
1698 Ice::CfgNode *ElseBlock = getBranchBasicBlock(Values[1]); 1641 Ice::CfgNode *ElseBlock = getBranchBasicBlock(Values[1]);
1699 if (ThenBlock == NULL || ElseBlock == NULL) 1642 if (ThenBlock == nullptr || ElseBlock == nullptr)
1700 return; 1643 return;
1701 CurrentNode->appendInst( 1644 CurrentNode->appendInst(
1702 Ice::InstBr::create(Func, Cond, ThenBlock, ElseBlock)); 1645 Ice::InstBr::create(Func, Cond, ThenBlock, ElseBlock));
1703 } 1646 }
1704 InstIsTerminating = true; 1647 InstIsTerminating = true;
1705 break; 1648 break;
1706 } 1649 }
1707 case naclbitc::FUNC_CODE_INST_SWITCH: { 1650 case naclbitc::FUNC_CODE_INST_SWITCH: {
1708 // SWITCH: [Condty, Cond, BbIndex, NumCases Case ...] 1651 // SWITCH: [Condty, Cond, BbIndex, NumCases Case ...]
1709 // where Case = [1, 1, Value, BbIndex]. 1652 // where Case = [1, 1, Value, BbIndex].
(...skipping 180 matching lines...) Expand 10 before | Expand all | Expand 10 after
1890 << " not understood."; 1833 << " not understood.";
1891 Error(StrBuf.str()); 1834 Error(StrBuf.str());
1892 return; 1835 return;
1893 } 1836 }
1894 bool IsTailCall = static_cast<bool>(CCInfo & 1); 1837 bool IsTailCall = static_cast<bool>(CCInfo & 1);
1895 1838
1896 // Extract out the called function and its return type. 1839 // Extract out the called function and its return type.
1897 uint32_t CalleeIndex = convertRelativeToAbsIndex(Values[1], BaseIndex); 1840 uint32_t CalleeIndex = convertRelativeToAbsIndex(Values[1], BaseIndex);
1898 Ice::Operand *Callee = getOperand(CalleeIndex); 1841 Ice::Operand *Callee = getOperand(CalleeIndex);
1899 Ice::Type ReturnType = Ice::IceType_void; 1842 Ice::Type ReturnType = Ice::IceType_void;
1900 const Ice::Intrinsics::FullIntrinsicInfo *IntrinsicInfo = NULL; 1843 const Ice::Intrinsics::FullIntrinsicInfo *IntrinsicInfo = nullptr;
1901 if (Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL) { 1844 if (Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL) {
1902 Function *Fcn = 1845 Function *Fcn = Context->getFunctionByID(CalleeIndex);
1903 dyn_cast<Function>(Context->getGlobalValueByID(CalleeIndex)); 1846 if (Fcn == nullptr) {
1904 if (Fcn == NULL) {
1905 std::string Buffer; 1847 std::string Buffer;
1906 raw_string_ostream StrBuf(Buffer); 1848 raw_string_ostream StrBuf(Buffer);
1907 StrBuf << "Function call to non-function: " << *Callee; 1849 StrBuf << "Function call to non-function: " << *Callee;
1908 Error(StrBuf.str()); 1850 Error(StrBuf.str());
1909 return; 1851 return;
1910 } 1852 }
1911 1853
1912 FunctionType *FcnTy = Fcn->getFunctionType(); 1854 FunctionType *FcnTy = Fcn->getFunctionType();
1913 ReturnType = Context->convertToIceType(FcnTy->getReturnType()); 1855 ReturnType = Context->convertToIceType(FcnTy->getReturnType());
1914 1856
(...skipping 10 matching lines...) Expand all
1925 StrBuf << "Invalid PNaCl intrinsic call to " << Name; 1867 StrBuf << "Invalid PNaCl intrinsic call to " << Name;
1926 Error(StrBuf.str()); 1868 Error(StrBuf.str());
1927 return; 1869 return;
1928 } 1870 }
1929 } 1871 }
1930 } else { 1872 } else {
1931 ReturnType = Context->convertToIceType(Context->getTypeByID(Values[2])); 1873 ReturnType = Context->convertToIceType(Context->getTypeByID(Values[2]));
1932 } 1874 }
1933 1875
1934 // Create the call instruction. 1876 // Create the call instruction.
1935 Ice::Variable *Dest = 1877 Ice::Variable *Dest = (ReturnType == Ice::IceType_void)
1936 (ReturnType == Ice::IceType_void) ? NULL : getNextInstVar(ReturnType); 1878 ? nullptr
1879 : getNextInstVar(ReturnType);
1937 Ice::SizeT NumParams = Values.size() - ParamsStartIndex; 1880 Ice::SizeT NumParams = Values.size() - ParamsStartIndex;
1938 Ice::InstCall *Inst = NULL; 1881 Ice::InstCall *Inst = nullptr;
1939 if (IntrinsicInfo) { 1882 if (IntrinsicInfo) {
1940 Inst = 1883 Inst =
1941 Ice::InstIntrinsicCall::create(Func, NumParams, Dest, Callee, 1884 Ice::InstIntrinsicCall::create(Func, NumParams, Dest, Callee,
1942 IntrinsicInfo->Info); 1885 IntrinsicInfo->Info);
1943 } else { 1886 } else {
1944 Inst = Ice::InstCall::create(Func, NumParams, Dest, Callee, IsTailCall); 1887 Inst = Ice::InstCall::create(Func, NumParams, Dest, Callee, IsTailCall);
1945 } 1888 }
1946 1889
1947 // Add parameters. 1890 // Add parameters.
1948 for (Ice::SizeT ParamIndex = 0; ParamIndex < NumParams; ++ParamIndex) { 1891 for (Ice::SizeT ParamIndex = 0; ParamIndex < NumParams; ++ParamIndex) {
(...skipping 259 matching lines...) Expand 10 before | Expand all | Expand 10 after
2208 : BlockParserBaseClass(BlockID, Context), 2151 : BlockParserBaseClass(BlockID, Context),
2209 GlobalAddressNamesAndInitializersInstalled(false) {} 2152 GlobalAddressNamesAndInitializersInstalled(false) {}
2210 2153
2211 ~ModuleParser() override {} 2154 ~ModuleParser() override {}
2212 2155
2213 private: 2156 private:
2214 // True if we have already instaledl names for unnamed global addresses, 2157 // True if we have already instaledl names for unnamed global addresses,
2215 // and generated global constant initializers. 2158 // and generated global constant initializers.
2216 bool GlobalAddressNamesAndInitializersInstalled; 2159 bool GlobalAddressNamesAndInitializersInstalled;
2217 2160
2218 // Temporary hack to generate names for unnamed global addresses, 2161 // Generates names for unnamed global addresses, and lowers global
2219 // and generate global constant initializers. May be called multiple 2162 // constant initializers to the target. May be called multiple
2220 // times. Only the first call will do the installation. 2163 // times. Only the first call will do the installation.
2221 // NOTE: Doesn't handle relocations for global constant initializers.
2222 void InstallGlobalAddressNamesAndInitializers() { 2164 void InstallGlobalAddressNamesAndInitializers() {
2223 if (!GlobalAddressNamesAndInitializersInstalled) { 2165 if (!GlobalAddressNamesAndInitializersInstalled) {
2224 getTranslator().nameUnnamedGlobalAddresses(Context->getModule()); 2166 Ice::Translator &Trans = getTranslator();
2167 const Ice::IceString &GlobalPrefix = getFlags().DefaultGlobalPrefix;
2168 if (!GlobalPrefix.empty()) {
2169 uint32_t NameIndex = 0;
2170 for (Ice::GlobalAddress *Address : Context->getGlobalIDAddresses()) {
2171 if (!Address->hasName()) {
2172 Address->setName(Trans.createUnnamedName(GlobalPrefix, NameIndex));
2173 ++NameIndex;
2174 } else {
2175 Trans.checkIfUnnamedNameSafe(Address->getName(), "global",
2176 GlobalPrefix,
2177 Trans.getContext()->getStrDump());
2178 }
2179 }
2180 }
2181 Trans.nameUnnamedFunctions(Context->getModule());
2225 if (!getFlags().DisableGlobals) 2182 if (!getFlags().DisableGlobals)
2226 getTranslator().convertGlobals(Context->getModule()); 2183 getTranslator().lowerIceGlobals(Context->getGlobalIDAddresses());
2227 GlobalAddressNamesAndInitializersInstalled = true; 2184 GlobalAddressNamesAndInitializersInstalled = true;
2228 } 2185 }
2229 } 2186 }
2230 2187
2231 bool ParseBlock(unsigned BlockID) override; 2188 bool ParseBlock(unsigned BlockID) override;
2232 2189
2233 void ExitBlock() override { 2190 void ExitBlock() override {
2234 InstallGlobalAddressNamesAndInitializers(); 2191 InstallGlobalAddressNamesAndInitializers();
2235 getTranslator().emitConstants(); 2192 getTranslator().emitConstants();
2236 } 2193 }
(...skipping 10 matching lines...) Expand all
2247 : ValuesymtabParser(BlockID, MP) {} 2204 : ValuesymtabParser(BlockID, MP) {}
2248 2205
2249 ~ModuleValuesymtabParser() override {} 2206 ~ModuleValuesymtabParser() override {}
2250 2207
2251 private: 2208 private:
2252 void setValueName(uint64_t Index, StringType &Name) override; 2209 void setValueName(uint64_t Index, StringType &Name) override;
2253 void setBbName(uint64_t Index, StringType &Name) override; 2210 void setBbName(uint64_t Index, StringType &Name) override;
2254 }; 2211 };
2255 2212
2256 void ModuleValuesymtabParser::setValueName(uint64_t Index, StringType &Name) { 2213 void ModuleValuesymtabParser::setValueName(uint64_t Index, StringType &Name) {
2257 Value *V = Context->getGlobalValueByID(Index); 2214 if (Index < Context->getNumFunctionIDs()) {
2258 if (V == NULL) { 2215 Function *Fcn = Context->getFunctionByID(Index);
2259 std::string Buffer; 2216 if (Fcn != nullptr) {
2260 raw_string_ostream StrBuf(Buffer); 2217 Fcn->setName(StringRef(Name.data(), Name.size()));
2261 StrBuf << "Invalid global address ID in valuesymtab: " << Index; 2218 return;
2262 Error(StrBuf.str()); 2219 }
2220 } else {
2221 unsigned NumFunctions = Context->getNumFunctionIDs();
2222 if (Index >= NumFunctions) {
2223 Context->getGlobalAddress(Index - NumFunctions)
2224 ->setName(StringRef(Name.data(), Name.size()));
2225 }
2263 return; 2226 return;
2264 } 2227 }
2265 V->setName(StringRef(Name.data(), Name.size())); 2228
2229 std::string Buffer;
2230 raw_string_ostream StrBuf(Buffer);
2231 StrBuf << "Invalid global address ID in valuesymtab: " << Index;
2232 Error(StrBuf.str());
2233 return;
2266 } 2234 }
2267 2235
2268 void ModuleValuesymtabParser::setBbName(uint64_t Index, StringType &Name) { 2236 void ModuleValuesymtabParser::setBbName(uint64_t Index, StringType &Name) {
2269 std::string Buffer; 2237 std::string Buffer;
2270 raw_string_ostream StrBuf(Buffer); 2238 raw_string_ostream StrBuf(Buffer);
2271 StrBuf << "Can't define basic block name at global level: '" << Name 2239 StrBuf << "Can't define basic block name at global level: '" << Name
2272 << "' -> " << Index; 2240 << "' -> " << Index;
2273 Error(StrBuf.str()); 2241 Error(StrBuf.str());
2274 } 2242 }
2275 2243
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
2314 Error(StrBuf.str()); 2282 Error(StrBuf.str());
2315 } 2283 }
2316 return; 2284 return;
2317 } 2285 }
2318 case naclbitc::MODULE_CODE_FUNCTION: { 2286 case naclbitc::MODULE_CODE_FUNCTION: {
2319 // FUNCTION: [type, callingconv, isproto, linkage] 2287 // FUNCTION: [type, callingconv, isproto, linkage]
2320 if (!isValidRecordSize(4, "Function heading")) 2288 if (!isValidRecordSize(4, "Function heading"))
2321 return; 2289 return;
2322 Type *Ty = Context->getTypeByID(Values[0]); 2290 Type *Ty = Context->getTypeByID(Values[0]);
2323 FunctionType *FTy = dyn_cast<FunctionType>(Ty); 2291 FunctionType *FTy = dyn_cast<FunctionType>(Ty);
2324 if (FTy == NULL) { 2292 if (FTy == nullptr) {
2325 std::string Buffer; 2293 std::string Buffer;
2326 raw_string_ostream StrBuf(Buffer); 2294 raw_string_ostream StrBuf(Buffer);
2327 StrBuf << "Function heading expects function type. Found: " << Ty; 2295 StrBuf << "Function heading expects function type. Found: " << Ty;
2328 Error(StrBuf.str()); 2296 Error(StrBuf.str());
2329 return; 2297 return;
2330 } 2298 }
2331 CallingConv::ID CallingConv; 2299 CallingConv::ID CallingConv;
2332 if (!naclbitc::DecodeCallingConv(Values[1], CallingConv)) { 2300 if (!naclbitc::DecodeCallingConv(Values[1], CallingConv)) {
2333 std::string Buffer; 2301 std::string Buffer;
2334 raw_string_ostream StrBuf(Buffer); 2302 raw_string_ostream StrBuf(Buffer);
(...skipping 82 matching lines...) Expand 10 before | Expand all | Expand 10 after
2417 2385
2418 if (TopLevelBlocks != 1) { 2386 if (TopLevelBlocks != 1) {
2419 errs() << IRFilename 2387 errs() << IRFilename
2420 << ": Contains more than one module. Found: " << TopLevelBlocks 2388 << ": Contains more than one module. Found: " << TopLevelBlocks
2421 << "\n"; 2389 << "\n";
2422 ErrorStatus = true; 2390 ErrorStatus = true;
2423 } 2391 }
2424 } 2392 }
2425 2393
2426 } // end of namespace Ice 2394 } // end of namespace Ice
OLDNEW
« src/IceTranslator.h ('K') | « src/IceTranslator.cpp ('k') | src/llvm2ice.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698