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

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

Powered by Google App Engine
This is Rietveld 408576698