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

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
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 &) LLVM_DELETED_FUNCTION; 51 TopLevelParser(const TopLevelParser &) LLVM_DELETED_FUNCTION;
55 TopLevelParser &operator=(const TopLevelParser &) LLVM_DELETED_FUNCTION; 52 TopLevelParser &operator=(const TopLevelParser &) LLVM_DELETED_FUNCTION;
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 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
115 if (ID < TypeIDValues.size() && TypeIDValues[ID] == NULL) { 111 if (ID < TypeIDValues.size() && TypeIDValues[ID] == NULL) {
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 NULL;
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;
Jim Stichnoth 2014/10/03 01:28:09 Either use NULL, or use nullptr below?
Karl 2014/10/04 16:28:34 Changed to use 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];
161 if (C != NULL) 163 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,
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 std::vector<Ice::GlobalAddress *> &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 }
(...skipping 30 matching lines...) Expand all
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 std::vector<Ice::GlobalAddress *> 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 261 matching lines...) Expand 10 before | Expand all | Expand 10 after
555 if (Ty == NULL) 562 if (Ty == NULL)
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.
573 SmallVector<Constant *, 10> Initializers;
574
575 // Keeps track of how many initializers are expected for 577 // Keeps track of how many initializers are expected for
576 // the global variable being built. 578 // 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
jvoung (off chromium) 2014/10/03 16:15:30 does "defined" fit on the previous line?
Karl 2014/10/04 16:28:34 Done.
585 // defined.
586 Ice::GlobalAddress *CurrentAddress;
587
588 // Dummy global address to guarantee CurrentAddress is always
589 // defined (allowing code to not need to check if CurrentAddress is
590 // NULL).
591 Ice::GlobalAddress DummyAddress;
592
588 void ExitBlock() override { 593 void ExitBlock() override {
589 verifyNoMissingInitializers(); 594 verifyNoMissingInitializers();
590 unsigned NumIDs = Context->getNumGlobalValueIDs(); 595 unsigned NumIDs = Context->getNumGlobalAddresses();
591 if (NextGlobalID < NumIDs) { 596 if (NextGlobalID < NumIDs) {
592 unsigned NumFcnIDs = Context->getNumFunctionIDs();
593 std::string Buffer; 597 std::string Buffer;
594 raw_string_ostream StrBuf(Buffer); 598 raw_string_ostream StrBuf(Buffer);
595 StrBuf << "Globals block expects " << (NumIDs - NumFcnIDs) 599 StrBuf << "Globals block expects " << NumIDs
596 << " global definitions. Found: " << (NextGlobalID - NumFcnIDs); 600 << " global definitions. Found: " << NextGlobalID;
597 Error(StrBuf.str()); 601 Error(StrBuf.str());
598 } 602 }
599 BlockParserBaseClass::ExitBlock(); 603 BlockParserBaseClass::ExitBlock();
600 } 604 }
601 605
602 void ProcessRecord() override; 606 void ProcessRecord() override;
603 607
604 // Checks if the number of initializers needed is the same as the 608 // Checks if the number of initializers for the CurrentAddress is
605 // number found in the bitcode file. If different, and error message 609 // the same as the number found in the bitcode file. If different,
606 // is generated, and the internal state of the parser is fixed so 610 // and error message is generated, and the internal state of the
607 // this condition is no longer violated. 611 // parser is fixed so this condition is no longer violated.
608 void verifyNoMissingInitializers() { 612 void verifyNoMissingInitializers() {
609 if (InitializersNeeded != Initializers.size()) { 613 size_t NumInits = CurrentAddress->getInitializers().size();
614 if (InitializersNeeded != NumInits) {
610 std::string Buffer; 615 std::string Buffer;
611 raw_string_ostream StrBuf(Buffer); 616 raw_string_ostream StrBuf(Buffer);
612 StrBuf << "Global variable @g" 617 StrBuf << "Global variable @g" << NextGlobalID << " expected "
613 << (NextGlobalID - Context->getNumFunctionIDs()) << " expected "
614 << InitializersNeeded << " initializer"; 618 << InitializersNeeded << " initializer";
615 if (InitializersNeeded > 1) 619 if (InitializersNeeded > 1)
616 StrBuf << "s"; 620 StrBuf << "s";
617 StrBuf << ". Found: " << Initializers.size(); 621 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()); 622 Error(StrBuf.str());
662 } 623 }
663 ++NextGlobalID;
664 Initializers.clear();
665 InitializersNeeded = 0;
666 Alignment = 1;
667 IsConstant = false;
668 } 624 }
669 }; 625 };
670 626
671 void GlobalsParser::ProcessRecord() { 627 void GlobalsParser::ProcessRecord() {
672 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues(); 628 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
673 switch (Record.GetCode()) { 629 switch (Record.GetCode()) {
674 case naclbitc::GLOBALVAR_COUNT: 630 case naclbitc::GLOBALVAR_COUNT:
675 // COUNT: [n] 631 // COUNT: [n]
676 if (!isValidRecordSize(1, "Globals count")) 632 if (!isValidRecordSize(1, "Globals count"))
677 return; 633 return;
678 if (NextGlobalID != Context->getNumFunctionIDs()) { 634 if (NextGlobalID != Context->getNumGlobalAddresses()) {
679 Error("Globals count record not first in block."); 635 Error("Globals count record not first in block.");
680 return; 636 return;
681 } 637 }
682 verifyNoMissingInitializers(); 638 Context->CreateGlobalAddresses(Values[0]);
683 Context->resizeValueIDsForGlobalVarCount(Values[0]);
684 return; 639 return;
685 case naclbitc::GLOBALVAR_VAR: { 640 case naclbitc::GLOBALVAR_VAR: {
686 // VAR: [align, isconst] 641 // VAR: [align, isconst]
687 if (!isValidRecordSize(2, "Globals variable")) 642 if (!isValidRecordSize(2, "Globals variable"))
688 return; 643 return;
689 verifyNoMissingInitializers(); 644 verifyNoMissingInitializers();
690 InitializersNeeded = 1; 645 InitializersNeeded = 1;
691 Initializers.clear(); 646 CurrentAddress = Context->getGlobalAddress(NextGlobalID);
692 Alignment = (1 << Values[0]) >> 1; 647 CurrentAddress->setAlignment((1 << Values[0]) >> 1);
693 IsConstant = Values[1] != 0; 648 CurrentAddress->setIsConstant(Values[1] != 0);
649 ++NextGlobalID;
694 return; 650 return;
695 } 651 }
696 case naclbitc::GLOBALVAR_COMPOUND: 652 case naclbitc::GLOBALVAR_COMPOUND:
697 // COMPOUND: [size] 653 // COMPOUND: [size]
698 if (!isValidRecordSize(1, "globals compound")) 654 if (!isValidRecordSize(1, "globals compound"))
699 return; 655 return;
700 if (Initializers.size() > 0 || InitializersNeeded != 1) { 656 if (!CurrentAddress->getInitializers().empty()) {
701 Error("Globals compound record not first initializer"); 657 Error("Globals compound record not first initializer");
702 return; 658 return;
703 } 659 }
704 if (Values[0] < 2) { 660 if (Values[0] < 2) {
705 std::string Buffer; 661 std::string Buffer;
706 raw_string_ostream StrBuf(Buffer); 662 raw_string_ostream StrBuf(Buffer);
707 StrBuf << "Globals compound record size invalid. Found: " << Values[0]; 663 StrBuf << "Globals compound record size invalid. Found: " << Values[0];
708 Error(StrBuf.str()); 664 Error(StrBuf.str());
709 return; 665 return;
710 } 666 }
711 InitializersNeeded = Values[0]; 667 InitializersNeeded = Values[0];
712 return; 668 return;
713 case naclbitc::GLOBALVAR_ZEROFILL: { 669 case naclbitc::GLOBALVAR_ZEROFILL: {
714 // ZEROFILL: [size] 670 // ZEROFILL: [size]
715 if (!isValidRecordSize(1, "Globals zerofill")) 671 if (!isValidRecordSize(1, "Globals zerofill"))
716 return; 672 return;
717 reserveInitializer("Globals zerofill"); 673 CurrentAddress->AddInitializer(
718 Type *Ty = 674 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; 675 break;
723 } 676 }
724 case naclbitc::GLOBALVAR_DATA: { 677 case naclbitc::GLOBALVAR_DATA: {
725 // DATA: [b0, b1, ...] 678 // DATA: [b0, b1, ...]
726 if (!isValidRecordSizeAtLeast(1, "Globals data")) 679 if (!isValidRecordSizeAtLeast(1, "Globals data"))
727 return; 680 return;
728 reserveInitializer("Globals data"); 681 CurrentAddress->AddInitializer(
729 unsigned Size = Values.size(); 682 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; 683 break;
737 } 684 }
738 case naclbitc::GLOBALVAR_RELOC: { 685 case naclbitc::GLOBALVAR_RELOC: {
739 // RELOC: [val, [addend]] 686 // RELOC: [val, [addend]]
740 if (!isValidRecordSizeInRange(1, 2, "Globals reloc")) 687 if (!isValidRecordSizeInRange(1, 2, "Globals reloc"))
741 return; 688 return;
742 Constant *BaseVal = Context->getOrCreateGlobalVarRef(Values[0]); 689 unsigned Index = Values[0];
743 if (BaseVal == NULL) { 690 Ice::SizeT Offset = 0;
744 std::string Buffer; 691 if (Values.size() == 2)
745 raw_string_ostream StrBuf(Buffer); 692 Offset = Values[1];
746 StrBuf << "Can't find global relocation value: " << Values[0]; 693 unsigned NumFunctions = Context->getNumFunctionIDs();
747 Error(StrBuf.str()); 694 if (Index < NumFunctions) {
748 return; 695 llvm::Function *Fcn = Context->getFunctionByID(Index);
696 Ice::GlobalAddress::RelocationAddress Addr(Fcn);
697 CurrentAddress->AddInitializer(
698 new Ice::GlobalAddress::RelocInitializer(Addr, Offset));
699 } else {
700 Ice::GlobalAddress::RelocationAddress Addr(
701 Context->getGlobalAddress(Index - NumFunctions));
702 CurrentAddress->AddInitializer(
703 new Ice::GlobalAddress::RelocInitializer(Addr, Offset));
749 } 704 }
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; 705 break;
757 } 706 }
758 default: 707 default:
759 BlockParserBaseClass::ProcessRecord(); 708 BlockParserBaseClass::ProcessRecord();
760 return; 709 return;
761 } 710 }
762 // If reached, just processed another initializer. See if time
763 // to install global.
764 if (InitializersNeeded == Initializers.size())
765 installGlobalVar();
766 } 711 }
767 712
768 /// Base class for parsing a valuesymtab block in the bitcode file. 713 /// Base class for parsing a valuesymtab block in the bitcode file.
769 class ValuesymtabParser : public BlockParserBaseClass { 714 class ValuesymtabParser : public BlockParserBaseClass {
770 ValuesymtabParser(const ValuesymtabParser &) LLVM_DELETED_FUNCTION; 715 ValuesymtabParser(const ValuesymtabParser &) LLVM_DELETED_FUNCTION;
771 void operator=(const ValuesymtabParser &) LLVM_DELETED_FUNCTION; 716 void operator=(const ValuesymtabParser &) LLVM_DELETED_FUNCTION;
772 717
773 public: 718 public:
774 ValuesymtabParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser) 719 ValuesymtabParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser)
775 : BlockParserBaseClass(BlockID, EnclosingParser) {} 720 : BlockParserBaseClass(BlockID, EnclosingParser) {}
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
831 class FunctionParser : public BlockParserBaseClass { 776 class FunctionParser : public BlockParserBaseClass {
832 FunctionParser(const FunctionParser &) LLVM_DELETED_FUNCTION; 777 FunctionParser(const FunctionParser &) LLVM_DELETED_FUNCTION;
833 FunctionParser &operator=(const FunctionParser &) LLVM_DELETED_FUNCTION; 778 FunctionParser &operator=(const FunctionParser &) LLVM_DELETED_FUNCTION;
834 friend class FunctionValuesymtabParser; 779 friend class FunctionValuesymtabParser;
835 780
836 public: 781 public:
837 FunctionParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser) 782 FunctionParser(unsigned BlockID, BlockParserBaseClass *EnclosingParser)
838 : BlockParserBaseClass(BlockID, EnclosingParser), 783 : BlockParserBaseClass(BlockID, EnclosingParser),
839 Func(new Ice::Cfg(getTranslator().getContext())), CurrentBbIndex(0), 784 Func(new Ice::Cfg(getTranslator().getContext())), CurrentBbIndex(0),
840 FcnId(Context->getNextFunctionBlockValueID()), 785 FcnId(Context->getNextFunctionBlockValueID()),
841 LLVMFunc(cast<Function>(Context->getGlobalValueByID(FcnId))), 786 LLVMFunc(Context->getFunctionByID(FcnId)),
842 CachedNumGlobalValueIDs(Context->getNumGlobalValueIDs()), 787 CachedNumGlobalValueIDs(Context->getNumGlobalIDs()),
843 NextLocalInstIndex(Context->getNumGlobalValueIDs()), 788 NextLocalInstIndex(Context->getNumGlobalIDs()),
844 InstIsTerminating(false) { 789 InstIsTerminating(false) {
845 Func->setFunctionName(LLVMFunc->getName()); 790 Func->setFunctionName(LLVMFunc->getName());
846 Func->setReturnType(Context->convertToIceType(LLVMFunc->getReturnType())); 791 Func->setReturnType(Context->convertToIceType(LLVMFunc->getReturnType()));
847 Func->setInternal(LLVMFunc->hasInternalLinkage()); 792 Func->setInternal(LLVMFunc->hasInternalLinkage());
848 CurrentNode = InstallNextBasicBlock(); 793 CurrentNode = InstallNextBasicBlock();
849 Func->setEntryNode(CurrentNode); 794 Func->setEntryNode(CurrentNode);
850 for (Function::const_arg_iterator ArgI = LLVMFunc->arg_begin(), 795 for (Function::const_arg_iterator ArgI = LLVMFunc->arg_begin(),
851 ArgE = LLVMFunc->arg_end(); 796 ArgE = LLVMFunc->arg_end();
852 ArgI != ArgE; ++ArgI) { 797 ArgI != ArgE; ++ArgI) {
853 Func->addArg(getNextInstVar(Context->convertToIceType(ArgI->getType()))); 798 Func->addArg(getNextInstVar(Context->convertToIceType(ArgI->getType())));
(...skipping 1042 matching lines...) Expand 10 before | Expand all | Expand 10 after
1896 return; 1841 return;
1897 } 1842 }
1898 bool IsTailCall = static_cast<bool>(CCInfo & 1); 1843 bool IsTailCall = static_cast<bool>(CCInfo & 1);
1899 1844
1900 // Extract out the called function and its return type. 1845 // Extract out the called function and its return type.
1901 uint32_t CalleeIndex = convertRelativeToAbsIndex(Values[1], BaseIndex); 1846 uint32_t CalleeIndex = convertRelativeToAbsIndex(Values[1], BaseIndex);
1902 Ice::Operand *Callee = getOperand(CalleeIndex); 1847 Ice::Operand *Callee = getOperand(CalleeIndex);
1903 Ice::Type ReturnType = Ice::IceType_void; 1848 Ice::Type ReturnType = Ice::IceType_void;
1904 const Ice::Intrinsics::FullIntrinsicInfo *IntrinsicInfo = NULL; 1849 const Ice::Intrinsics::FullIntrinsicInfo *IntrinsicInfo = NULL;
1905 if (Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL) { 1850 if (Record.GetCode() == naclbitc::FUNC_CODE_INST_CALL) {
1906 Function *Fcn = 1851 Function *Fcn = Context->getFunctionByID(CalleeIndex);
1907 dyn_cast<Function>(Context->getGlobalValueByID(CalleeIndex));
1908 if (Fcn == NULL) { 1852 if (Fcn == NULL) {
1909 std::string Buffer; 1853 std::string Buffer;
1910 raw_string_ostream StrBuf(Buffer); 1854 raw_string_ostream StrBuf(Buffer);
1911 StrBuf << "Function call to non-function: " << *Callee; 1855 StrBuf << "Function call to non-function: " << *Callee;
1912 Error(StrBuf.str()); 1856 Error(StrBuf.str());
1913 return; 1857 return;
1914 } 1858 }
1915 1859
1916 FunctionType *FcnTy = Fcn->getFunctionType(); 1860 FunctionType *FcnTy = Fcn->getFunctionType();
1917 ReturnType = Context->convertToIceType(FcnTy->getReturnType()); 1861 ReturnType = Context->convertToIceType(FcnTy->getReturnType());
(...skipping 295 matching lines...) Expand 10 before | Expand all | Expand 10 after
2213 : BlockParserBaseClass(BlockID, Context), 2157 : BlockParserBaseClass(BlockID, Context),
2214 GlobalAddressNamesAndInitializersInstalled(false) {} 2158 GlobalAddressNamesAndInitializersInstalled(false) {}
2215 2159
2216 ~ModuleParser() override {} 2160 ~ModuleParser() override {}
2217 2161
2218 private: 2162 private:
2219 // True if we have already instaledl names for unnamed global addresses, 2163 // True if we have already instaledl names for unnamed global addresses,
2220 // and generated global constant initializers. 2164 // and generated global constant initializers.
2221 bool GlobalAddressNamesAndInitializersInstalled; 2165 bool GlobalAddressNamesAndInitializersInstalled;
2222 2166
2223 // Temporary hack to generate names for unnamed global addresses, 2167 // Generate names for unnamed global addresses, and lowers global
Jim Stichnoth 2014/10/03 01:28:08 either Generates, or lower for agreement
Karl 2014/10/04 16:28:34 Done.
2224 // and generate global constant initializers. May be called multiple 2168 // constant initializers to the target. May be called multiple
2225 // times. Only the first call will do the installation. 2169 // times. Only the first call will do the installation.
2226 // NOTE: Doesn't handle relocations for global constant initializers.
2227 void InstallGlobalAddressNamesAndInitializers() { 2170 void InstallGlobalAddressNamesAndInitializers() {
2228 if (!GlobalAddressNamesAndInitializersInstalled) { 2171 if (!GlobalAddressNamesAndInitializersInstalled) {
2229 getTranslator().nameUnnamedGlobalAddresses(Context->getModule()); 2172 Ice::Translator &Trans = getTranslator();
2173 const Ice::IceString &GlobalPrefix = getFlags().DefaultGlobalPrefix;
2174 if (!GlobalPrefix.empty()) {
2175 uint32_t NameIndex = 0;
2176 for (Ice::GlobalAddress *Address : Context->getGlobalIDAddresses()) {
2177 if (!Address->hasName()) {
2178 Address->setName(Trans.createUnnamedName(GlobalPrefix, NameIndex));
2179 ++NameIndex;
2180 } else {
2181 Trans.checkIfUnnamedNameSafe(Address->getName(), "global",
2182 GlobalPrefix,
2183 Trans.getContext()->getStrDump());
2184 }
2185 }
2186 }
2187 Trans.nameUnnamedFunctions(Context->getModule());
2230 if (!getFlags().DisableGlobals) 2188 if (!getFlags().DisableGlobals)
2231 getTranslator().convertGlobals(Context->getModule()); 2189 getTranslator().lowerIceGlobals(Context->getGlobalIDAddresses());
2232 GlobalAddressNamesAndInitializersInstalled = true; 2190 GlobalAddressNamesAndInitializersInstalled = true;
2233 } 2191 }
2234 } 2192 }
2235 2193
2236 bool ParseBlock(unsigned BlockID) override; 2194 bool ParseBlock(unsigned BlockID) override;
2237 2195
2238 void ExitBlock() override { 2196 void ExitBlock() override {
2239 InstallGlobalAddressNamesAndInitializers(); 2197 InstallGlobalAddressNamesAndInitializers();
2240 getTranslator().emitConstants(); 2198 getTranslator().emitConstants();
2241 } 2199 }
(...skipping 11 matching lines...) Expand all
2253 : ValuesymtabParser(BlockID, MP) {} 2211 : ValuesymtabParser(BlockID, MP) {}
2254 2212
2255 ~ModuleValuesymtabParser() override {} 2213 ~ModuleValuesymtabParser() override {}
2256 2214
2257 private: 2215 private:
2258 void setValueName(uint64_t Index, StringType &Name) override; 2216 void setValueName(uint64_t Index, StringType &Name) override;
2259 void setBbName(uint64_t Index, StringType &Name) override; 2217 void setBbName(uint64_t Index, StringType &Name) override;
2260 }; 2218 };
2261 2219
2262 void ModuleValuesymtabParser::setValueName(uint64_t Index, StringType &Name) { 2220 void ModuleValuesymtabParser::setValueName(uint64_t Index, StringType &Name) {
2263 Value *V = Context->getGlobalValueByID(Index); 2221 if (Index < Context->getNumFunctionIDs()) {
2264 if (V == NULL) { 2222 Function *Fcn = Context->getFunctionByID(Index);
2265 std::string Buffer; 2223 if (Fcn != NULL) {
2266 raw_string_ostream StrBuf(Buffer); 2224 Fcn->setName(StringRef(Name.data(), Name.size()));
2267 StrBuf << "Invalid global address ID in valuesymtab: " << Index; 2225 return;
2268 Error(StrBuf.str()); 2226 }
2227 } else {
2228 unsigned NumFunctions = Context->getNumFunctionIDs();
2229 if (Index >= NumFunctions) {
2230 Context->getGlobalAddress(Index - NumFunctions)
2231 ->setName(StringRef(Name.data(), Name.size()));
2232 }
2269 return; 2233 return;
2270 } 2234 }
2271 V->setName(StringRef(Name.data(), Name.size())); 2235
2236 std::string Buffer;
2237 raw_string_ostream StrBuf(Buffer);
2238 StrBuf << "Invalid global address ID in valuesymtab: " << Index;
2239 Error(StrBuf.str());
2240 return;
2272 } 2241 }
2273 2242
2274 void ModuleValuesymtabParser::setBbName(uint64_t Index, StringType &Name) { 2243 void ModuleValuesymtabParser::setBbName(uint64_t Index, StringType &Name) {
2275 std::string Buffer; 2244 std::string Buffer;
2276 raw_string_ostream StrBuf(Buffer); 2245 raw_string_ostream StrBuf(Buffer);
2277 StrBuf << "Can't define basic block name at global level: '" << Name 2246 StrBuf << "Can't define basic block name at global level: '" << Name
2278 << "' -> " << Index; 2247 << "' -> " << Index;
2279 Error(StrBuf.str()); 2248 Error(StrBuf.str());
2280 } 2249 }
2281 2250
(...skipping 141 matching lines...) Expand 10 before | Expand all | Expand 10 after
2423 2392
2424 if (TopLevelBlocks != 1) { 2393 if (TopLevelBlocks != 1) {
2425 errs() << IRFilename 2394 errs() << IRFilename
2426 << ": Contains more than one module. Found: " << TopLevelBlocks 2395 << ": Contains more than one module. Found: " << TopLevelBlocks
2427 << "\n"; 2396 << "\n";
2428 ErrorStatus = true; 2397 ErrorStatus = true;
2429 } 2398 }
2430 } 2399 }
2431 2400
2432 } // end of namespace Ice 2401 } // end of namespace Ice
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698