comparison lib/TableGen/TGParser.cpp @ 148:63bd29f05246

merged
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Wed, 14 Aug 2019 19:46:37 +0900
parents c2174574ed3a
children
comparison
equal deleted inserted replaced
146:3fc4d5c3e21e 148:63bd29f05246
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===// 1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 // 2 //
3 // The LLVM Compiler Infrastructure 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // 4 // See https://llvm.org/LICENSE.txt for license information.
5 // This file is distributed under the University of Illinois Open Source 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 // License. See LICENSE.TXT for details.
7 // 6 //
8 //===----------------------------------------------------------------------===// 7 //===----------------------------------------------------------------------===//
9 // 8 //
10 // Implement the Parser for TableGen. 9 // Implement the Parser for TableGen.
11 // 10 //
14 #include "TGParser.h" 13 #include "TGParser.h"
15 #include "llvm/ADT/None.h" 14 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h" 17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Casting.h" 19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h" 20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h" 21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h" 22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/TableGen/Record.h" 23 #include "llvm/TableGen/Record.h"
65 TA->dump(); 65 TA->dump();
66 } 66 }
67 #endif 67 #endif
68 68
69 } // end namespace llvm 69 } // end namespace llvm
70
71 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
72 BitsInit *BV = cast<BitsInit>(RV.getValue());
73 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
74 Init *Bit = BV->getBit(i);
75 bool IsReference = false;
76 if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
77 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
78 if (R.getValue(VI->getName()))
79 IsReference = true;
80 }
81 } else if (isa<VarInit>(Bit)) {
82 IsReference = true;
83 }
84 if (!(IsReference || Bit->isConcrete()))
85 return false;
86 }
87 return true;
88 }
89
90 static void checkConcrete(Record &R) {
91 for (const RecordVal &RV : R.getValues()) {
92 // HACK: Disable this check for variables declared with 'field'. This is
93 // done merely because existing targets have legitimate cases of
94 // non-concrete variables in helper defs. Ideally, we'd introduce a
95 // 'maybe' or 'optional' modifier instead of this.
96 if (RV.getPrefix())
97 continue;
98
99 if (Init *V = RV.getValue()) {
100 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
101 if (!Ok) {
102 PrintError(R.getLoc(),
103 Twine("Initializer of '") + RV.getNameInitAsString() +
104 "' in '" + R.getNameInitAsString() +
105 "' could not be fully resolved: " +
106 RV.getValue()->getAsString());
107 }
108 }
109 }
110 }
111
112 /// Return an Init with a qualifier prefix referring
113 /// to CurRec's name.
114 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
115 Init *Name, StringRef Scoper) {
116 Init *NewName =
117 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
118 NewName = BinOpInit::getStrConcat(NewName, Name);
119 if (CurMultiClass && Scoper != "::") {
120 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
121 StringInit::get("::"));
122 NewName = BinOpInit::getStrConcat(Prefix, NewName);
123 }
124
125 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
126 NewName = BinOp->Fold(&CurRec);
127 return NewName;
128 }
129
130 /// Return the qualified version of the implicit 'NAME' template argument.
131 static Init *QualifiedNameOfImplicitName(Record &Rec,
132 MultiClass *MC = nullptr) {
133 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
134 }
135
136 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
137 return QualifiedNameOfImplicitName(MC->Rec, MC);
138 }
70 139
71 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) { 140 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
72 if (!CurRec) 141 if (!CurRec)
73 CurRec = &CurMultiClass->Rec; 142 CurRec = &CurMultiClass->Rec;
74 143
102 // Do not allow assignments like 'X = X'. This will just cause infinite loops 171 // Do not allow assignments like 'X = X'. This will just cause infinite loops
103 // in the resolution machinery. 172 // in the resolution machinery.
104 if (BitList.empty()) 173 if (BitList.empty())
105 if (VarInit *VI = dyn_cast<VarInit>(V)) 174 if (VarInit *VI = dyn_cast<VarInit>(V))
106 if (VI->getNameInit() == ValName && !AllowSelfAssignment) 175 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
107 return true; 176 return Error(Loc, "Recursion / self-assignment forbidden");
108 177
109 // If we are assigning to a subset of the bits in the value... then we must be 178 // If we are assigning to a subset of the bits in the value... then we must be
110 // assigning to a field of BitsRecTy, which must have a BitsInit 179 // assigning to a field of BitsRecTy, which must have a BitsInit
111 // initializer. 180 // initializer.
112 // 181 //
115 if (!CurVal) 184 if (!CurVal)
116 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 185 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
117 "' is not a bits type"); 186 "' is not a bits type");
118 187
119 // Convert the incoming value to a bits type of the appropriate size... 188 // Convert the incoming value to a bits type of the appropriate size...
120 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size())); 189 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
121 if (!BI) 190 if (!BI)
122 return Error(Loc, "Initializer is not compatible with bit range"); 191 return Error(Loc, "Initializer is not compatible with bit range");
123
124 // We should have a BitsInit type now.
125 BitsInit *BInit = cast<BitsInit>(BI);
126 192
127 SmallVector<Init *, 16> NewBits(CurVal->getNumBits()); 193 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
128 194
129 // Loop over bits, assigning values as appropriate. 195 // Loop over bits, assigning values as appropriate.
130 for (unsigned i = 0, e = BitList.size(); i != e; ++i) { 196 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
131 unsigned Bit = BitList[i]; 197 unsigned Bit = BitList[i];
132 if (NewBits[Bit]) 198 if (NewBits[Bit])
133 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" + 199 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
134 ValName->getAsUnquotedString() + "' more than once"); 200 ValName->getAsUnquotedString() + "' more than once");
135 NewBits[Bit] = BInit->getBit(i); 201 NewBits[Bit] = BI->getBit(i);
136 } 202 }
137 203
138 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i) 204 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
139 if (!NewBits[i]) 205 if (!NewBits[i])
140 NewBits[i] = CurVal->getBit(i); 206 NewBits[i] = CurVal->getBit(i);
145 if (RV->setValue(V)) { 211 if (RV->setValue(V)) {
146 std::string InitType; 212 std::string InitType;
147 if (BitsInit *BI = dyn_cast<BitsInit>(V)) 213 if (BitsInit *BI = dyn_cast<BitsInit>(V))
148 InitType = (Twine("' of type bit initializer with length ") + 214 InitType = (Twine("' of type bit initializer with length ") +
149 Twine(BI->getNumBits())).str(); 215 Twine(BI->getNumBits())).str();
216 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
217 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
150 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 218 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
151 "' of type '" + RV->getType()->getAsString() + 219 "' of type '" + RV->getType()->getAsString() +
152 "' is incompatible with initializer '" + V->getAsString() + 220 "' is incompatible with initializer '" +
153 InitType + "'"); 221 V->getAsString() + InitType + "'");
154 } 222 }
155 return false; 223 return false;
156 } 224 }
157 225
158 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template 226 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
171 return Error(SubClass.RefRange.Start, 239 return Error(SubClass.RefRange.Start,
172 "More template args specified than expected"); 240 "More template args specified than expected");
173 241
174 // Loop over all of the template arguments, setting them to the specified 242 // Loop over all of the template arguments, setting them to the specified
175 // value or leaving them as the default if necessary. 243 // value or leaving them as the default if necessary.
244 MapResolver R(CurRec);
245
176 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 246 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
177 if (i < SubClass.TemplateArgs.size()) { 247 if (i < SubClass.TemplateArgs.size()) {
178 // If a value is specified for this template arg, set it now. 248 // If a value is specified for this template arg, set it now.
179 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i], 249 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
180 None, SubClass.TemplateArgs[i])) 250 None, SubClass.TemplateArgs[i]))
181 return true; 251 return true;
182
183 // Resolve it next.
184 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
185
186 // Now remove it.
187 CurRec->removeValue(TArgs[i]);
188
189 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) { 252 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
190 return Error(SubClass.RefRange.Start, 253 return Error(SubClass.RefRange.Start,
191 "Value not specified for template argument #" + 254 "Value not specified for template argument #" +
192 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 255 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
193 ") of subclass '" + SC->getNameInitAsString() + "'!"); 256 ") of subclass '" + SC->getNameInitAsString() + "'!");
194 } 257 }
195 } 258
259 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
260
261 CurRec->removeValue(TArgs[i]);
262 }
263
264 Init *Name;
265 if (CurRec->isClass())
266 Name =
267 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
268 else
269 Name = CurRec->getNameInit();
270 R.set(QualifiedNameOfImplicitName(*SC), Name);
271
272 CurRec->resolveReferences(R);
196 273
197 // Since everything went well, we can now set the "superclass" list for the 274 // Since everything went well, we can now set the "superclass" list for the
198 // current record. 275 // current record.
199 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses(); 276 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
200 for (const auto &SCPair : SCs) { 277 for (const auto &SCPair : SCs) {
209 "Already subclass of '" + SC->getName() + "'!\n"); 286 "Already subclass of '" + SC->getName() + "'!\n");
210 CurRec->addSuperClass(SC, SubClass.RefRange); 287 CurRec->addSuperClass(SC, SubClass.RefRange);
211 return false; 288 return false;
212 } 289 }
213 290
291 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
292 if (Entry.Rec)
293 return AddSubClass(Entry.Rec.get(), SubClass);
294
295 for (auto &E : Entry.Loop->Entries) {
296 if (AddSubClass(E, SubClass))
297 return true;
298 }
299
300 return false;
301 }
302
214 /// AddSubMultiClass - Add SubMultiClass as a subclass to 303 /// AddSubMultiClass - Add SubMultiClass as a subclass to
215 /// CurMC, resolving its template args as SubMultiClass's 304 /// CurMC, resolving its template args as SubMultiClass's
216 /// template arguments. 305 /// template arguments.
217 bool TGParser::AddSubMultiClass(MultiClass *CurMC, 306 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
218 SubMultiClassReference &SubMultiClass) { 307 SubMultiClassReference &SubMultiClass) {
219 MultiClass *SMC = SubMultiClass.MC; 308 MultiClass *SMC = SubMultiClass.MC;
220 Record *CurRec = &CurMC->Rec;
221
222 // Add all of the values in the subclass into the current class.
223 for (const auto &SMCVal : SMC->Rec.getValues())
224 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
225 return true;
226
227 unsigned newDefStart = CurMC->DefPrototypes.size();
228
229 // Add all of the defs in the subclass into the current multiclass.
230 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
231 // Clone the def and add it to the current multiclass
232 auto NewDef = make_unique<Record>(*R);
233
234 // Add all of the values in the superclass into the current def.
235 for (const auto &MCVal : CurRec->getValues())
236 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
237 return true;
238
239 CurMC->DefPrototypes.push_back(std::move(NewDef));
240 }
241 309
242 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs(); 310 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
243
244 // Ensure that an appropriate number of template arguments are
245 // specified.
246 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size()) 311 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
247 return Error(SubMultiClass.RefRange.Start, 312 return Error(SubMultiClass.RefRange.Start,
248 "More template args specified than expected"); 313 "More template args specified than expected");
249 314
250 // Loop over all of the template arguments, setting them to the specified 315 // Prepare the mapping of template argument name to value, filling in default
251 // value or leaving them as the default if necessary. 316 // values if necessary.
317 SubstStack TemplateArgs;
252 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) { 318 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
253 if (i < SubMultiClass.TemplateArgs.size()) { 319 if (i < SubMultiClass.TemplateArgs.size()) {
254 // If a value is specified for this template arg, set it in the 320 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
255 // superclass now. 321 } else {
256 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i], 322 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
257 None, SubMultiClass.TemplateArgs[i])) 323 if (!Default->isComplete()) {
258 return true; 324 return Error(SubMultiClass.RefRange.Start,
259 325 "value not specified for template argument #" + Twine(i) +
260 // Resolve it next. 326 " (" + SMCTArgs[i]->getAsUnquotedString() +
261 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i])); 327 ") of multiclass '" + SMC->Rec.getNameInitAsString() +
262 328 "'");
263 // Now remove it. 329 }
264 CurRec->removeValue(SMCTArgs[i]); 330 TemplateArgs.emplace_back(SMCTArgs[i], Default);
265 331 }
266 // If a value is specified for this template arg, set it in the 332 }
267 // new defs now. 333
268 for (const auto &Def : 334 TemplateArgs.emplace_back(
269 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) { 335 QualifiedNameOfImplicitName(SMC),
270 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i], 336 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
271 None, SubMultiClass.TemplateArgs[i])) 337
272 return true; 338 // Add all of the defs in the subclass into the current multiclass.
273 339 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
274 // Resolve it next. 340 }
275 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i])); 341
276 342 /// Add a record or foreach loop to the current context (global record keeper,
277 // Now remove it 343 /// current inner-most foreach loop, or multiclass).
278 Def->removeValue(SMCTArgs[i]); 344 bool TGParser::addEntry(RecordsEntry E) {
279 } 345 assert(!E.Rec || !E.Loop);
280 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) { 346
281 return Error(SubMultiClass.RefRange.Start, 347 if (!Loops.empty()) {
282 "Value not specified for template argument #" + 348 Loops.back()->Entries.push_back(std::move(E));
283 Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
284 ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
285 }
286 }
287
288 return false;
289 }
290
291 /// ProcessForeachDefs - Given a record, apply all of the variable
292 /// values in all surrounding foreach loops, creating new records for
293 /// each combination of values.
294 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
295 if (Loops.empty())
296 return false; 349 return false;
297 350 }
298 // We want to instantiate a new copy of CurRec for each combination 351
299 // of nested loop iterator values. We don't want top instantiate 352 if (E.Loop) {
300 // any copies until we have values for each loop iterator. 353 SubstStack Stack;
301 IterSet IterVals; 354 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
302 return ProcessForeachDefs(CurRec, Loc, IterVals); 355 CurMultiClass ? &CurMultiClass->Entries : nullptr);
303 } 356 }
304 357
305 /// ProcessForeachDefs - Given a record, a loop and a loop iterator, 358 if (CurMultiClass) {
306 /// apply each of the variable values in this loop and then process 359 CurMultiClass->Entries.push_back(std::move(E));
307 /// subloops. 360 return false;
308 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){ 361 }
309 // Recursively build a tuple of iterator values. 362
310 if (IterVals.size() != Loops.size()) { 363 return addDefOne(std::move(E.Rec));
311 assert(IterVals.size() < Loops.size()); 364 }
312 ForeachLoop &CurLoop = Loops[IterVals.size()]; 365
313 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue); 366 /// Resolve the entries in \p Loop, going over inner loops recursively
314 if (!List) { 367 /// and making the given subsitutions of (name, value) pairs.
315 Error(Loc, "Loop list is not a list"); 368 ///
369 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
370 /// are added to the global record keeper.
371 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
372 bool Final, std::vector<RecordsEntry> *Dest,
373 SMLoc *Loc) {
374 MapResolver R;
375 for (const auto &S : Substs)
376 R.set(S.first, S.second);
377 Init *List = Loop.ListValue->resolveReferences(R);
378 auto LI = dyn_cast<ListInit>(List);
379 if (!LI) {
380 if (!Final) {
381 Dest->emplace_back(make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
382 List));
383 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
384 Loc);
385 }
386
387 PrintError(Loop.Loc, Twine("attempting to loop over '") +
388 List->getAsString() + "', expected a list");
389 return true;
390 }
391
392 bool Error = false;
393 for (auto Elt : *LI) {
394 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
395 Error = resolve(Loop.Entries, Substs, Final, Dest);
396 Substs.pop_back();
397 if (Error)
398 break;
399 }
400 return Error;
401 }
402
403 /// Resolve the entries in \p Source, going over loops recursively and
404 /// making the given substitutions of (name, value) pairs.
405 ///
406 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
407 /// are added to the global record keeper.
408 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
409 SubstStack &Substs, bool Final,
410 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
411 bool Error = false;
412 for (auto &E : Source) {
413 if (E.Loop) {
414 Error = resolve(*E.Loop, Substs, Final, Dest);
415 } else {
416 auto Rec = make_unique<Record>(*E.Rec);
417 if (Loc)
418 Rec->appendLoc(*Loc);
419
420 MapResolver R(Rec.get());
421 for (const auto &S : Substs)
422 R.set(S.first, S.second);
423 Rec->resolveReferences(R);
424
425 if (Dest)
426 Dest->push_back(std::move(Rec));
427 else
428 Error = addDefOne(std::move(Rec));
429 }
430 if (Error)
431 break;
432 }
433 return Error;
434 }
435
436 /// Resolve the record fully and add it to the record keeper.
437 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
438 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
439 if (!Rec->isAnonymous()) {
440 PrintError(Rec->getLoc(),
441 "def already exists: " + Rec->getNameInitAsString());
442 PrintNote(Prev->getLoc(), "location of previous definition");
316 return true; 443 return true;
317 } 444 }
318 445 Rec->setName(Records.getNewAnonymousName());
319 // Process each value. 446 }
320 for (unsigned i = 0; i < List->size(); ++i) { 447
321 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i); 448 Rec->resolveReferences();
322 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal)); 449 checkConcrete(*Rec);
323 if (ProcessForeachDefs(CurRec, Loc, IterVals)) 450
324 return true; 451 if (!isa<StringInit>(Rec->getNameInit())) {
325 IterVals.pop_back(); 452 PrintError(Rec->getLoc(), Twine("record name '") +
326 } 453 Rec->getNameInit()->getAsString() +
327 return false; 454 "' could not be fully resolved");
328 } 455 return true;
329 456 }
330 // This is the bottom of the recursion. We have all of the iterator values 457
331 // for this point in the iteration space. Instantiate a new record to 458 // If ObjectBody has template arguments, it's an error.
332 // reflect this combination of values. 459 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
333 auto IterRec = make_unique<Record>(*CurRec); 460
334 461 for (DefsetRecord *Defset : Defsets) {
335 // Set the iterator values now. 462 DefInit *I = Rec->getDefInit();
336 for (IterRecord &IR : IterVals) { 463 if (!I->getType()->typeIsA(Defset->EltTy)) {
337 VarInit *IterVar = IR.IterVar; 464 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
338 TypedInit *IVal = dyn_cast<TypedInit>(IR.IterValue); 465 I->getType()->getAsString() +
339 if (!IVal) 466 "' to defset");
340 return Error(Loc, "foreach iterator value is untyped"); 467 PrintNote(Defset->Loc, "location of defset declaration");
341 468 return true;
342 IterRec->addValue(RecordVal(IterVar->getNameInit(), IVal->getType(), false)); 469 }
343 470 Defset->Elements.push_back(I);
344 if (SetValue(IterRec.get(), Loc, IterVar->getNameInit(), None, IVal)) 471 }
345 return Error(Loc, "when instantiating this def"); 472
346 473 Records.addDef(std::move(Rec));
347 // Resolve it next.
348 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getNameInit()));
349
350 // Remove it.
351 IterRec->removeValue(IterVar->getNameInit());
352 }
353
354 if (Records.getDef(IterRec->getNameInitAsString())) {
355 // If this record is anonymous, it's no problem, just generate a new name
356 if (!IterRec->isAnonymous())
357 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
358
359 IterRec->setName(GetNewAnonymousName());
360 }
361
362 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
363 Records.addDef(std::move(IterRec));
364 IterRecSave->resolveReferences();
365 return false; 474 return false;
366 } 475 }
367 476
368 //===----------------------------------------------------------------------===// 477 //===----------------------------------------------------------------------===//
369 // Parser Code 478 // Parser Code
370 //===----------------------------------------------------------------------===// 479 //===----------------------------------------------------------------------===//
371 480
372 /// isObjectStart - Return true if this is a valid first token for an Object. 481 /// isObjectStart - Return true if this is a valid first token for an Object.
373 static bool isObjectStart(tgtok::TokKind K) { 482 static bool isObjectStart(tgtok::TokKind K) {
374 return K == tgtok::Class || K == tgtok::Def || 483 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
375 K == tgtok::Defm || K == tgtok::Let || 484 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
376 K == tgtok::MultiClass || K == tgtok::Foreach; 485 K == tgtok::Defset;
377 } 486 }
378 487
379 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as 488 /// ParseObjectName - If a valid object name is specified, return it. If no
380 /// an identifier. 489 /// name is specified, return the unset initializer. Return nullptr on parse
381 Init *TGParser::GetNewAnonymousName() { 490 /// error.
382 return StringInit::get("anonymous_" + utostr(AnonCounter++));
383 }
384
385 /// ParseObjectName - If an object name is specified, return it. Otherwise,
386 /// return 0.
387 /// ObjectName ::= Value [ '#' Value ]* 491 /// ObjectName ::= Value [ '#' Value ]*
388 /// ObjectName ::= /*empty*/ 492 /// ObjectName ::= /*empty*/
389 /// 493 ///
390 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) { 494 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
391 switch (Lex.getCode()) { 495 switch (Lex.getCode()) {
393 case tgtok::semi: 497 case tgtok::semi:
394 case tgtok::l_brace: 498 case tgtok::l_brace:
395 // These are all of the tokens that can begin an object body. 499 // These are all of the tokens that can begin an object body.
396 // Some of these can also begin values but we disallow those cases 500 // Some of these can also begin values but we disallow those cases
397 // because they are unlikely to be useful. 501 // because they are unlikely to be useful.
398 return nullptr; 502 return UnsetInit::get();
399 default: 503 default:
400 break; 504 break;
401 } 505 }
402 506
403 Record *CurRec = nullptr; 507 Record *CurRec = nullptr;
404 if (CurMultiClass) 508 if (CurMultiClass)
405 CurRec = &CurMultiClass->Rec; 509 CurRec = &CurMultiClass->Rec;
406 510
407 RecTy *Type = nullptr; 511 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
408 if (CurRec) { 512 if (!Name)
409 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit()); 513 return nullptr;
410 if (!CurRecName) { 514
411 TokError("Record name is not typed!"); 515 if (CurMultiClass) {
412 return nullptr; 516 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
413 } 517 HasReferenceResolver R(NameStr);
414 Type = CurRecName->getType(); 518 Name->resolveReferences(R);
415 } 519 if (!R.found())
416 520 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
417 return ParseValue(CurRec, Type, ParseNameMode); 521 Name);
522 }
523
524 return Name;
418 } 525 }
419 526
420 /// ParseClassID - Parse and resolve a reference to a class name. This returns 527 /// ParseClassID - Parse and resolve a reference to a class name. This returns
421 /// null on error. 528 /// null on error.
422 /// 529 ///
427 TokError("expected name for ClassID"); 534 TokError("expected name for ClassID");
428 return nullptr; 535 return nullptr;
429 } 536 }
430 537
431 Record *Result = Records.getClass(Lex.getCurStrVal()); 538 Record *Result = Records.getClass(Lex.getCurStrVal());
432 if (!Result) 539 if (!Result) {
433 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'"); 540 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
541 if (MultiClasses[Lex.getCurStrVal()].get())
542 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
543 Lex.getCurStrVal() + "'");
544 else
545 TokError(Msg);
546 }
434 547
435 Lex.Lex(); 548 Lex.Lex();
436 return Result; 549 return Result;
437 } 550 }
438 551
551 664
552 /// ParseRangePiece - Parse a bit/value range. 665 /// ParseRangePiece - Parse a bit/value range.
553 /// RangePiece ::= INTVAL 666 /// RangePiece ::= INTVAL
554 /// RangePiece ::= INTVAL '-' INTVAL 667 /// RangePiece ::= INTVAL '-' INTVAL
555 /// RangePiece ::= INTVAL INTVAL 668 /// RangePiece ::= INTVAL INTVAL
556 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges) { 669 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
557 if (Lex.getCode() != tgtok::IntVal) { 670 TypedInit *FirstItem) {
558 TokError("expected integer or bitrange"); 671 Init *CurVal = FirstItem;
559 return true; 672 if (!CurVal)
560 } 673 CurVal = ParseValue(nullptr);
561 int64_t Start = Lex.getCurIntVal(); 674
675 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
676 if (!II)
677 return TokError("expected integer or bitrange");
678
679 int64_t Start = II->getValue();
562 int64_t End; 680 int64_t End;
563 681
564 if (Start < 0) 682 if (Start < 0)
565 return TokError("invalid range, cannot be negative"); 683 return TokError("invalid range, cannot be negative");
566 684
567 switch (Lex.Lex()) { // eat first character. 685 switch (Lex.getCode()) {
568 default: 686 default:
569 Ranges.push_back(Start); 687 Ranges.push_back(Start);
570 return false; 688 return false;
571 case tgtok::minus: 689 case tgtok::minus: {
572 if (Lex.Lex() != tgtok::IntVal) { 690 Lex.Lex(); // eat
691
692 Init *I_End = ParseValue(nullptr);
693 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
694 if (!II_End) {
573 TokError("expected integer value as end of range"); 695 TokError("expected integer value as end of range");
574 return true; 696 return true;
575 } 697 }
576 End = Lex.getCurIntVal(); 698
699 End = II_End->getValue();
577 break; 700 break;
578 case tgtok::IntVal: 701 }
702 case tgtok::IntVal: {
579 End = -Lex.getCurIntVal(); 703 End = -Lex.getCurIntVal();
704 Lex.Lex();
580 break; 705 break;
706 }
581 } 707 }
582 if (End < 0) 708 if (End < 0)
583 return TokError("invalid range, cannot be negative"); 709 return TokError("invalid range, cannot be negative");
584 Lex.Lex();
585 710
586 // Add to the range. 711 // Add to the range.
587 if (Start < End) 712 if (Start < End)
588 for (; Start <= End; ++Start) 713 for (; Start <= End; ++Start)
589 Ranges.push_back(Start); 714 Ranges.push_back(Start);
677 case tgtok::Bit: Lex.Lex(); return BitRecTy::get(); 802 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
678 case tgtok::Int: Lex.Lex(); return IntRecTy::get(); 803 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
679 case tgtok::Dag: Lex.Lex(); return DagRecTy::get(); 804 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
680 case tgtok::Id: 805 case tgtok::Id:
681 if (Record *R = ParseClassID()) return RecordRecTy::get(R); 806 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
807 TokError("unknown class name");
682 return nullptr; 808 return nullptr;
683 case tgtok::Bits: { 809 case tgtok::Bits: {
684 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 810 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
685 TokError("expected '<' after bits type"); 811 TokError("expected '<' after bits type");
686 return nullptr; 812 return nullptr;
721 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc, 847 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
722 IDParseMode Mode) { 848 IDParseMode Mode) {
723 if (CurRec) { 849 if (CurRec) {
724 if (const RecordVal *RV = CurRec->getValue(Name)) 850 if (const RecordVal *RV = CurRec->getValue(Name))
725 return VarInit::get(Name, RV->getType()); 851 return VarInit::get(Name, RV->getType());
726 852 }
727 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":"); 853
728 854 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
729 if (CurMultiClass) 855 Init *TemplateArgName;
730 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, 856 if (CurMultiClass) {
731 "::"); 857 TemplateArgName =
732 858 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
733 if (CurRec->isTemplateArg(TemplateArgName)) { 859 } else
734 const RecordVal *RV = CurRec->getValue(TemplateArgName); 860 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
861
862 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
863 if (TemplateRec->isTemplateArg(TemplateArgName)) {
864 const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
735 assert(RV && "Template arg doesn't exist??"); 865 assert(RV && "Template arg doesn't exist??");
736 return VarInit::get(TemplateArgName, RV->getType()); 866 return VarInit::get(TemplateArgName, RV->getType());
737 } 867 } else if (Name->getValue() == "NAME") {
738 } 868 return VarInit::get(TemplateArgName, StringRecTy::get());
739
740 if (CurMultiClass) {
741 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
742
743 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
744 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
745 assert(RV && "Template arg doesn't exist??");
746 return VarInit::get(MCName, RV->getType());
747 } 869 }
748 } 870 }
749 871
750 // If this is in a foreach loop, make sure it's not a loop iterator 872 // If this is in a foreach loop, make sure it's not a loop iterator
751 for (const auto &L : Loops) { 873 for (const auto &L : Loops) {
752 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar); 874 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
753 if (IterVar && IterVar->getNameInit() == Name) 875 if (IterVar && IterVar->getNameInit() == Name)
754 return IterVar; 876 return IterVar;
755 } 877 }
756 878
757 if (Mode == ParseNameMode) 879 if (Mode == ParseNameMode)
758 return Name; 880 return Name;
759 881
760 if (Record *D = Records.getDef(Name->getValue())) 882 if (Init *I = Records.getGlobal(Name->getValue()))
761 return DefInit::get(D); 883 return I;
762 884
763 if (Mode == ParseValueMode) { 885 // Allow self-references of concrete defs, but delay the lookup so that we
764 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'"); 886 // get the correct type.
765 return nullptr; 887 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
766 } 888 CurRec->getNameInit() == Name)
767 889 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
768 return Name; 890
891 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
892 return nullptr;
769 } 893 }
770 894
771 /// ParseOperation - Parse an operator. This returns null on error. 895 /// ParseOperation - Parse an operator. This returns null on error.
772 /// 896 ///
773 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')' 897 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
777 default: 901 default:
778 TokError("unknown operation"); 902 TokError("unknown operation");
779 return nullptr; 903 return nullptr;
780 case tgtok::XHead: 904 case tgtok::XHead:
781 case tgtok::XTail: 905 case tgtok::XTail:
906 case tgtok::XSize:
782 case tgtok::XEmpty: 907 case tgtok::XEmpty:
783 case tgtok::XCast: { // Value ::= !unop '(' Value ')' 908 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
784 UnOpInit::UnaryOp Code; 909 UnOpInit::UnaryOp Code;
785 RecTy *Type = nullptr; 910 RecTy *Type = nullptr;
786 911
804 break; 929 break;
805 case tgtok::XTail: 930 case tgtok::XTail:
806 Lex.Lex(); // eat the operation 931 Lex.Lex(); // eat the operation
807 Code = UnOpInit::TAIL; 932 Code = UnOpInit::TAIL;
808 break; 933 break;
934 case tgtok::XSize:
935 Lex.Lex();
936 Code = UnOpInit::SIZE;
937 Type = IntRecTy::get();
938 break;
809 case tgtok::XEmpty: 939 case tgtok::XEmpty:
810 Lex.Lex(); // eat the operation 940 Lex.Lex(); // eat the operation
811 Code = UnOpInit::EMPTY; 941 Code = UnOpInit::EMPTY;
812 Type = IntRecTy::get(); 942 Type = IntRecTy::get();
813 break; 943 break;
838 TokError("expected list or string type argument in unary operator"); 968 TokError("expected list or string type argument in unary operator");
839 return nullptr; 969 return nullptr;
840 } 970 }
841 } 971 }
842 972
843 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) { 973 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
974 Code == UnOpInit::SIZE) {
844 if (!LHSl && !LHSt) { 975 if (!LHSl && !LHSt) {
845 TokError("expected list type argument in unary operator"); 976 TokError("expected list type argument in unary operator");
846 return nullptr; 977 return nullptr;
847 } 978 }
848 979 }
980
981 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
849 if (LHSl && LHSl->empty()) { 982 if (LHSl && LHSl->empty()) {
850 TokError("empty list argument in unary operator"); 983 TokError("empty list argument in unary operator");
851 return nullptr; 984 return nullptr;
852 } 985 }
853 if (LHSl) { 986 if (LHSl) {
874 if (Lex.getCode() != tgtok::r_paren) { 1007 if (Lex.getCode() != tgtok::r_paren) {
875 TokError("expected ')' in unary operator"); 1008 TokError("expected ')' in unary operator");
876 return nullptr; 1009 return nullptr;
877 } 1010 }
878 Lex.Lex(); // eat the ')' 1011 Lex.Lex(); // eat the ')'
879 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass); 1012 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1013 }
1014
1015 case tgtok::XIsA: {
1016 // Value ::= !isa '<' Type '>' '(' Value ')'
1017 Lex.Lex(); // eat the operation
1018
1019 RecTy *Type = ParseOperatorType();
1020 if (!Type)
1021 return nullptr;
1022
1023 if (Lex.getCode() != tgtok::l_paren) {
1024 TokError("expected '(' after type of !isa");
1025 return nullptr;
1026 }
1027 Lex.Lex(); // eat the '('
1028
1029 Init *LHS = ParseValue(CurRec);
1030 if (!LHS)
1031 return nullptr;
1032
1033 if (Lex.getCode() != tgtok::r_paren) {
1034 TokError("expected ')' in !isa");
1035 return nullptr;
1036 }
1037 Lex.Lex(); // eat the ')'
1038
1039 return (IsAOpInit::get(Type, LHS))->Fold();
880 } 1040 }
881 1041
882 case tgtok::XConcat: 1042 case tgtok::XConcat:
883 case tgtok::XADD: 1043 case tgtok::XADD:
1044 case tgtok::XMUL:
884 case tgtok::XAND: 1045 case tgtok::XAND:
885 case tgtok::XOR: 1046 case tgtok::XOR:
886 case tgtok::XSRA: 1047 case tgtok::XSRA:
887 case tgtok::XSRL: 1048 case tgtok::XSRL:
888 case tgtok::XSHL: 1049 case tgtok::XSHL:
889 case tgtok::XEq: 1050 case tgtok::XEq:
1051 case tgtok::XNe:
1052 case tgtok::XLe:
1053 case tgtok::XLt:
1054 case tgtok::XGe:
1055 case tgtok::XGt:
890 case tgtok::XListConcat: 1056 case tgtok::XListConcat:
1057 case tgtok::XListSplat:
891 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')' 1058 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
892 tgtok::TokKind OpTok = Lex.getCode(); 1059 tgtok::TokKind OpTok = Lex.getCode();
893 SMLoc OpLoc = Lex.getLoc(); 1060 SMLoc OpLoc = Lex.getLoc();
894 Lex.Lex(); // eat the operation 1061 Lex.Lex(); // eat the operation
895 1062
896 BinOpInit::BinaryOp Code; 1063 BinOpInit::BinaryOp Code;
897 RecTy *Type = nullptr;
898
899 switch (OpTok) { 1064 switch (OpTok) {
900 default: llvm_unreachable("Unhandled code!"); 1065 default: llvm_unreachable("Unhandled code!");
901 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break; 1066 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
902 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break; 1067 case tgtok::XADD: Code = BinOpInit::ADD; break;
903 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break; 1068 case tgtok::XMUL: Code = BinOpInit::MUL; break;
904 case tgtok::XOR: Code = BinOpInit::OR; Type = IntRecTy::get(); break; 1069 case tgtok::XAND: Code = BinOpInit::AND; break;
905 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break; 1070 case tgtok::XOR: Code = BinOpInit::OR; break;
906 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break; 1071 case tgtok::XSRA: Code = BinOpInit::SRA; break;
907 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break; 1072 case tgtok::XSRL: Code = BinOpInit::SRL; break;
908 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break; 1073 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1074 case tgtok::XEq: Code = BinOpInit::EQ; break;
1075 case tgtok::XNe: Code = BinOpInit::NE; break;
1076 case tgtok::XLe: Code = BinOpInit::LE; break;
1077 case tgtok::XLt: Code = BinOpInit::LT; break;
1078 case tgtok::XGe: Code = BinOpInit::GE; break;
1079 case tgtok::XGt: Code = BinOpInit::GT; break;
1080 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1081 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1082 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1083 }
1084
1085 RecTy *Type = nullptr;
1086 RecTy *ArgType = nullptr;
1087 switch (OpTok) {
1088 default:
1089 llvm_unreachable("Unhandled code!");
1090 case tgtok::XConcat:
1091 Type = DagRecTy::get();
1092 ArgType = DagRecTy::get();
1093 break;
1094 case tgtok::XAND:
1095 case tgtok::XOR:
1096 case tgtok::XSRA:
1097 case tgtok::XSRL:
1098 case tgtok::XSHL:
1099 case tgtok::XADD:
1100 case tgtok::XMUL:
1101 Type = IntRecTy::get();
1102 ArgType = IntRecTy::get();
1103 break;
1104 case tgtok::XEq:
1105 case tgtok::XNe:
1106 Type = BitRecTy::get();
1107 // ArgType for Eq / Ne is not known at this point
1108 break;
1109 case tgtok::XLe:
1110 case tgtok::XLt:
1111 case tgtok::XGe:
1112 case tgtok::XGt:
1113 Type = BitRecTy::get();
1114 ArgType = IntRecTy::get();
1115 break;
909 case tgtok::XListConcat: 1116 case tgtok::XListConcat:
910 Code = BinOpInit::LISTCONCAT;
911 // We don't know the list type until we parse the first argument 1117 // We don't know the list type until we parse the first argument
1118 ArgType = ItemType;
1119 break;
1120 case tgtok::XListSplat:
1121 // Can't do any typechecking until we parse the first argument.
912 break; 1122 break;
913 case tgtok::XStrConcat: 1123 case tgtok::XStrConcat:
914 Code = BinOpInit::STRCONCAT;
915 Type = StringRecTy::get(); 1124 Type = StringRecTy::get();
1125 ArgType = StringRecTy::get();
916 break; 1126 break;
1127 }
1128
1129 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1130 Error(OpLoc, Twine("expected value of type '") +
1131 ItemType->getAsString() + "', got '" +
1132 Type->getAsString() + "'");
1133 return nullptr;
917 } 1134 }
918 1135
919 if (Lex.getCode() != tgtok::l_paren) { 1136 if (Lex.getCode() != tgtok::l_paren) {
920 TokError("expected '(' after binary operator"); 1137 TokError("expected '(' after binary operator");
921 return nullptr; 1138 return nullptr;
922 } 1139 }
923 Lex.Lex(); // eat the '(' 1140 Lex.Lex(); // eat the '('
924 1141
925 SmallVector<Init*, 2> InitList; 1142 SmallVector<Init*, 2> InitList;
926 1143
927 InitList.push_back(ParseValue(CurRec)); 1144 for (;;) {
928 if (!InitList.back()) return nullptr; 1145 SMLoc InitLoc = Lex.getLoc();
929 1146 InitList.push_back(ParseValue(CurRec, ArgType));
930 while (Lex.getCode() == tgtok::comma) { 1147 if (!InitList.back()) return nullptr;
1148
1149 // All BinOps require their arguments to be of compatible types.
1150 TypedInit *TI = dyn_cast<TypedInit>(InitList.back());
1151 if (!ArgType) {
1152 ArgType = TI->getType();
1153
1154 switch (Code) {
1155 case BinOpInit::LISTCONCAT:
1156 if (!isa<ListRecTy>(ArgType)) {
1157 Error(InitLoc, Twine("expected a list, got value of type '") +
1158 ArgType->getAsString() + "'");
1159 return nullptr;
1160 }
1161 break;
1162 case BinOpInit::LISTSPLAT:
1163 if (ItemType && InitList.size() == 1) {
1164 if (!isa<ListRecTy>(ItemType)) {
1165 Error(OpLoc,
1166 Twine("expected output type to be a list, got type '") +
1167 ItemType->getAsString() + "'");
1168 return nullptr;
1169 }
1170 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1171 Error(OpLoc, Twine("expected first arg type to be '") +
1172 ArgType->getAsString() +
1173 "', got value of type '" +
1174 cast<ListRecTy>(ItemType)
1175 ->getElementType()
1176 ->getAsString() +
1177 "'");
1178 return nullptr;
1179 }
1180 }
1181 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1182 Error(InitLoc, Twine("expected second parameter to be an int, got "
1183 "value of type '") +
1184 ArgType->getAsString() + "'");
1185 return nullptr;
1186 }
1187 ArgType = nullptr; // Broken invariant: types not identical.
1188 break;
1189 case BinOpInit::EQ:
1190 case BinOpInit::NE:
1191 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1192 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1193 Error(InitLoc, Twine("expected int, bits, or string; got value of "
1194 "type '") + ArgType->getAsString() + "'");
1195 return nullptr;
1196 }
1197 break;
1198 default: llvm_unreachable("other ops have fixed argument types");
1199 }
1200 } else {
1201 RecTy *Resolved = resolveTypes(ArgType, TI->getType());
1202 if (!Resolved) {
1203 Error(InitLoc, Twine("expected value of type '") +
1204 ArgType->getAsString() + "', got '" +
1205 TI->getType()->getAsString() + "'");
1206 return nullptr;
1207 }
1208 if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1209 Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1210 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1211 Code != BinOpInit::MUL)
1212 ArgType = Resolved;
1213 }
1214
1215 if (Lex.getCode() != tgtok::comma)
1216 break;
931 Lex.Lex(); // eat the ',' 1217 Lex.Lex(); // eat the ','
932
933 InitList.push_back(ParseValue(CurRec));
934 if (!InitList.back()) return nullptr;
935 } 1218 }
936 1219
937 if (Lex.getCode() != tgtok::r_paren) { 1220 if (Lex.getCode() != tgtok::r_paren) {
938 TokError("expected ')' in operator"); 1221 TokError("expected ')' in operator");
939 return nullptr; 1222 return nullptr;
940 } 1223 }
941 Lex.Lex(); // eat the ')' 1224 Lex.Lex(); // eat the ')'
942 1225
943 // If we are doing !listconcat, we should know the type by now 1226 // listconcat returns a list with type of the argument.
944 if (OpTok == tgtok::XListConcat) { 1227 if (Code == BinOpInit::LISTCONCAT)
945 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0])) 1228 Type = ArgType;
946 Type = Arg0->getType(); 1229 // listsplat returns a list of type of the *first* argument.
947 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0])) 1230 if (Code == BinOpInit::LISTSPLAT)
948 Type = Arg0->getType(); 1231 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
949 else {
950 InitList[0]->print(errs());
951 Error(OpLoc, "expected a list");
952 return nullptr;
953 }
954 }
955 1232
956 // We allow multiple operands to associative operators like !strconcat as 1233 // We allow multiple operands to associative operators like !strconcat as
957 // shorthand for nesting them. 1234 // shorthand for nesting them.
958 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) { 1235 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1236 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1237 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1238 Code == BinOpInit::MUL) {
959 while (InitList.size() > 2) { 1239 while (InitList.size() > 2) {
960 Init *RHS = InitList.pop_back_val(); 1240 Init *RHS = InitList.pop_back_val();
961 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type)) 1241 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
962 ->Fold(CurRec, CurMultiClass);
963 InitList.back() = RHS; 1242 InitList.back() = RHS;
964 } 1243 }
965 } 1244 }
966 1245
967 if (InitList.size() == 2) 1246 if (InitList.size() == 2)
968 return (BinOpInit::get(Code, InitList[0], InitList[1], Type)) 1247 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
969 ->Fold(CurRec, CurMultiClass); 1248 ->Fold(CurRec);
970 1249
971 Error(OpLoc, "expected two operands to operator"); 1250 Error(OpLoc, "expected two operands to operator");
972 return nullptr; 1251 return nullptr;
973 } 1252 }
974 1253
1254 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1255 SMLoc OpLoc = Lex.getLoc();
1256 Lex.Lex(); // eat the operation
1257 if (Lex.getCode() != tgtok::l_paren) {
1258 TokError("expected '(' after !foreach");
1259 return nullptr;
1260 }
1261
1262 if (Lex.Lex() != tgtok::Id) { // eat the '('
1263 TokError("first argument of !foreach must be an identifier");
1264 return nullptr;
1265 }
1266
1267 Init *LHS = StringInit::get(Lex.getCurStrVal());
1268
1269 if (CurRec && CurRec->getValue(LHS)) {
1270 TokError((Twine("iteration variable '") + LHS->getAsString() +
1271 "' already defined")
1272 .str());
1273 return nullptr;
1274 }
1275
1276 if (Lex.Lex() != tgtok::comma) { // eat the id
1277 TokError("expected ',' in ternary operator");
1278 return nullptr;
1279 }
1280 Lex.Lex(); // eat the ','
1281
1282 Init *MHS = ParseValue(CurRec);
1283 if (!MHS)
1284 return nullptr;
1285
1286 if (Lex.getCode() != tgtok::comma) {
1287 TokError("expected ',' in ternary operator");
1288 return nullptr;
1289 }
1290 Lex.Lex(); // eat the ','
1291
1292 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1293 if (!MHSt) {
1294 TokError("could not get type of !foreach input");
1295 return nullptr;
1296 }
1297
1298 RecTy *InEltType = nullptr;
1299 RecTy *OutEltType = nullptr;
1300 bool IsDAG = false;
1301
1302 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1303 InEltType = InListTy->getElementType();
1304 if (ItemType) {
1305 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1306 OutEltType = OutListTy->getElementType();
1307 } else {
1308 Error(OpLoc,
1309 "expected value of type '" + Twine(ItemType->getAsString()) +
1310 "', but got !foreach of list type");
1311 return nullptr;
1312 }
1313 }
1314 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1315 InEltType = InDagTy;
1316 if (ItemType && !isa<DagRecTy>(ItemType)) {
1317 Error(OpLoc,
1318 "expected value of type '" + Twine(ItemType->getAsString()) +
1319 "', but got !foreach of dag type");
1320 return nullptr;
1321 }
1322 IsDAG = true;
1323 } else {
1324 TokError("!foreach must have list or dag input");
1325 return nullptr;
1326 }
1327
1328 // We need to create a temporary record to provide a scope for the iteration
1329 // variable while parsing top-level foreach's.
1330 std::unique_ptr<Record> ParseRecTmp;
1331 Record *ParseRec = CurRec;
1332 if (!ParseRec) {
1333 ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1334 ParseRec = ParseRecTmp.get();
1335 }
1336
1337 ParseRec->addValue(RecordVal(LHS, InEltType, false));
1338 Init *RHS = ParseValue(ParseRec, OutEltType);
1339 ParseRec->removeValue(LHS);
1340 if (!RHS)
1341 return nullptr;
1342
1343 if (Lex.getCode() != tgtok::r_paren) {
1344 TokError("expected ')' in binary operator");
1345 return nullptr;
1346 }
1347 Lex.Lex(); // eat the ')'
1348
1349 RecTy *OutType;
1350 if (IsDAG) {
1351 OutType = InEltType;
1352 } else {
1353 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1354 if (!RHSt) {
1355 TokError("could not get type of !foreach result");
1356 return nullptr;
1357 }
1358 OutType = RHSt->getType()->getListTy();
1359 }
1360
1361 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1362 ->Fold(CurRec);
1363 }
1364
1365 case tgtok::XDag:
975 case tgtok::XIf: 1366 case tgtok::XIf:
976 case tgtok::XForEach:
977 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1367 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
978 TernOpInit::TernaryOp Code; 1368 TernOpInit::TernaryOp Code;
979 RecTy *Type = nullptr; 1369 RecTy *Type = nullptr;
980 1370
981 tgtok::TokKind LexCode = Lex.getCode(); 1371 tgtok::TokKind LexCode = Lex.getCode();
982 Lex.Lex(); // eat the operation 1372 Lex.Lex(); // eat the operation
983 switch (LexCode) { 1373 switch (LexCode) {
984 default: llvm_unreachable("Unhandled code!"); 1374 default: llvm_unreachable("Unhandled code!");
1375 case tgtok::XDag:
1376 Code = TernOpInit::DAG;
1377 Type = DagRecTy::get();
1378 ItemType = nullptr;
1379 break;
985 case tgtok::XIf: 1380 case tgtok::XIf:
986 Code = TernOpInit::IF; 1381 Code = TernOpInit::IF;
987 break;
988 case tgtok::XForEach:
989 Code = TernOpInit::FOREACH;
990 break; 1382 break;
991 case tgtok::XSubst: 1383 case tgtok::XSubst:
992 Code = TernOpInit::SUBST; 1384 Code = TernOpInit::SUBST;
993 break; 1385 break;
994 } 1386 }
1005 TokError("expected ',' in ternary operator"); 1397 TokError("expected ',' in ternary operator");
1006 return nullptr; 1398 return nullptr;
1007 } 1399 }
1008 Lex.Lex(); // eat the ',' 1400 Lex.Lex(); // eat the ','
1009 1401
1402 SMLoc MHSLoc = Lex.getLoc();
1010 Init *MHS = ParseValue(CurRec, ItemType); 1403 Init *MHS = ParseValue(CurRec, ItemType);
1011 if (!MHS) 1404 if (!MHS)
1012 return nullptr; 1405 return nullptr;
1013 1406
1014 if (Lex.getCode() != tgtok::comma) { 1407 if (Lex.getCode() != tgtok::comma) {
1015 TokError("expected ',' in ternary operator"); 1408 TokError("expected ',' in ternary operator");
1016 return nullptr; 1409 return nullptr;
1017 } 1410 }
1018 Lex.Lex(); // eat the ',' 1411 Lex.Lex(); // eat the ','
1019 1412
1413 SMLoc RHSLoc = Lex.getLoc();
1020 Init *RHS = ParseValue(CurRec, ItemType); 1414 Init *RHS = ParseValue(CurRec, ItemType);
1021 if (!RHS) 1415 if (!RHS)
1022 return nullptr; 1416 return nullptr;
1023 1417
1024 if (Lex.getCode() != tgtok::r_paren) { 1418 if (Lex.getCode() != tgtok::r_paren) {
1027 } 1421 }
1028 Lex.Lex(); // eat the ')' 1422 Lex.Lex(); // eat the ')'
1029 1423
1030 switch (LexCode) { 1424 switch (LexCode) {
1031 default: llvm_unreachable("Unhandled code!"); 1425 default: llvm_unreachable("Unhandled code!");
1426 case tgtok::XDag: {
1427 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1428 if (!MHSt && !isa<UnsetInit>(MHS)) {
1429 Error(MHSLoc, "could not determine type of the child list in !dag");
1430 return nullptr;
1431 }
1432 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1433 Error(MHSLoc, Twine("expected list of children, got type '") +
1434 MHSt->getType()->getAsString() + "'");
1435 return nullptr;
1436 }
1437
1438 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1439 if (!RHSt && !isa<UnsetInit>(RHS)) {
1440 Error(RHSLoc, "could not determine type of the name list in !dag");
1441 return nullptr;
1442 }
1443 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1444 Error(RHSLoc, Twine("expected list<string>, got type '") +
1445 RHSt->getType()->getAsString() + "'");
1446 return nullptr;
1447 }
1448
1449 if (!MHSt && !RHSt) {
1450 Error(MHSLoc,
1451 "cannot have both unset children and unset names in !dag");
1452 return nullptr;
1453 }
1454 break;
1455 }
1032 case tgtok::XIf: { 1456 case tgtok::XIf: {
1033 RecTy *MHSTy = nullptr; 1457 RecTy *MHSTy = nullptr;
1034 RecTy *RHSTy = nullptr; 1458 RecTy *RHSTy = nullptr;
1035 1459
1036 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS)) 1460 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1056 if (!MHSTy || !RHSTy) { 1480 if (!MHSTy || !RHSTy) {
1057 TokError("could not get type for !if"); 1481 TokError("could not get type for !if");
1058 return nullptr; 1482 return nullptr;
1059 } 1483 }
1060 1484
1061 if (MHSTy->typeIsConvertibleTo(RHSTy)) { 1485 Type = resolveTypes(MHSTy, RHSTy);
1062 Type = RHSTy; 1486 if (!Type) {
1063 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) { 1487 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1064 Type = MHSTy; 1488 "' and '" + RHSTy->getAsString() + "' for !if");
1065 } else {
1066 TokError("inconsistent types for !if");
1067 return nullptr; 1489 return nullptr;
1068 } 1490 }
1069 break;
1070 }
1071 case tgtok::XForEach: {
1072 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1073 if (!MHSt) {
1074 TokError("could not get type for !foreach");
1075 return nullptr;
1076 }
1077 Type = MHSt->getType();
1078 break; 1491 break;
1079 } 1492 }
1080 case tgtok::XSubst: { 1493 case tgtok::XSubst: {
1081 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1494 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1082 if (!RHSt) { 1495 if (!RHSt) {
1085 } 1498 }
1086 Type = RHSt->getType(); 1499 Type = RHSt->getType();
1087 break; 1500 break;
1088 } 1501 }
1089 } 1502 }
1090 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec, 1503 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1091 CurMultiClass); 1504 }
1505
1506 case tgtok::XCond:
1507 return ParseOperationCond(CurRec, ItemType);
1508
1509 case tgtok::XFoldl: {
1510 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1511 Lex.Lex(); // eat the operation
1512 if (Lex.getCode() != tgtok::l_paren) {
1513 TokError("expected '(' after !foldl");
1514 return nullptr;
1515 }
1516 Lex.Lex(); // eat the '('
1517
1518 Init *StartUntyped = ParseValue(CurRec);
1519 if (!StartUntyped)
1520 return nullptr;
1521
1522 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1523 if (!Start) {
1524 TokError(Twine("could not get type of !foldl start: '") +
1525 StartUntyped->getAsString() + "'");
1526 return nullptr;
1527 }
1528
1529 if (Lex.getCode() != tgtok::comma) {
1530 TokError("expected ',' in !foldl");
1531 return nullptr;
1532 }
1533 Lex.Lex(); // eat the ','
1534
1535 Init *ListUntyped = ParseValue(CurRec);
1536 if (!ListUntyped)
1537 return nullptr;
1538
1539 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1540 if (!List) {
1541 TokError(Twine("could not get type of !foldl list: '") +
1542 ListUntyped->getAsString() + "'");
1543 return nullptr;
1544 }
1545
1546 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1547 if (!ListType) {
1548 TokError(Twine("!foldl list must be a list, but is of type '") +
1549 List->getType()->getAsString());
1550 return nullptr;
1551 }
1552
1553 if (Lex.getCode() != tgtok::comma) {
1554 TokError("expected ',' in !foldl");
1555 return nullptr;
1556 }
1557
1558 if (Lex.Lex() != tgtok::Id) { // eat the ','
1559 TokError("third argument of !foldl must be an identifier");
1560 return nullptr;
1561 }
1562
1563 Init *A = StringInit::get(Lex.getCurStrVal());
1564 if (CurRec && CurRec->getValue(A)) {
1565 TokError((Twine("left !foldl variable '") + A->getAsString() +
1566 "' already defined")
1567 .str());
1568 return nullptr;
1569 }
1570
1571 if (Lex.Lex() != tgtok::comma) { // eat the id
1572 TokError("expected ',' in !foldl");
1573 return nullptr;
1574 }
1575
1576 if (Lex.Lex() != tgtok::Id) { // eat the ','
1577 TokError("fourth argument of !foldl must be an identifier");
1578 return nullptr;
1579 }
1580
1581 Init *B = StringInit::get(Lex.getCurStrVal());
1582 if (CurRec && CurRec->getValue(B)) {
1583 TokError((Twine("right !foldl variable '") + B->getAsString() +
1584 "' already defined")
1585 .str());
1586 return nullptr;
1587 }
1588
1589 if (Lex.Lex() != tgtok::comma) { // eat the id
1590 TokError("expected ',' in !foldl");
1591 return nullptr;
1592 }
1593 Lex.Lex(); // eat the ','
1594
1595 // We need to create a temporary record to provide a scope for the iteration
1596 // variable while parsing top-level foreach's.
1597 std::unique_ptr<Record> ParseRecTmp;
1598 Record *ParseRec = CurRec;
1599 if (!ParseRec) {
1600 ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1601 ParseRec = ParseRecTmp.get();
1602 }
1603
1604 ParseRec->addValue(RecordVal(A, Start->getType(), false));
1605 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1606 Init *ExprUntyped = ParseValue(ParseRec);
1607 ParseRec->removeValue(A);
1608 ParseRec->removeValue(B);
1609 if (!ExprUntyped)
1610 return nullptr;
1611
1612 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1613 if (!Expr) {
1614 TokError("could not get type of !foldl expression");
1615 return nullptr;
1616 }
1617
1618 if (Expr->getType() != Start->getType()) {
1619 TokError(Twine("!foldl expression must be of same type as start (") +
1620 Start->getType()->getAsString() + "), but is of type " +
1621 Expr->getType()->getAsString());
1622 return nullptr;
1623 }
1624
1625 if (Lex.getCode() != tgtok::r_paren) {
1626 TokError("expected ')' in fold operator");
1627 return nullptr;
1628 }
1629 Lex.Lex(); // eat the ')'
1630
1631 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1632 ->Fold(CurRec);
1092 } 1633 }
1093 } 1634 }
1094 } 1635 }
1095 1636
1096 /// ParseOperatorType - Parse a type for an operator. This returns 1637 /// ParseOperatorType - Parse a type for an operator. This returns
1119 return nullptr; 1660 return nullptr;
1120 } 1661 }
1121 Lex.Lex(); // eat the > 1662 Lex.Lex(); // eat the >
1122 1663
1123 return Type; 1664 return Type;
1665 }
1666
1667 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1668 Lex.Lex(); // eat the operation 'cond'
1669
1670 if (Lex.getCode() != tgtok::l_paren) {
1671 TokError("expected '(' after !cond operator");
1672 return nullptr;
1673 }
1674 Lex.Lex(); // eat the '('
1675
1676 // Parse through '[Case: Val,]+'
1677 SmallVector<Init *, 4> Case;
1678 SmallVector<Init *, 4> Val;
1679 while (true) {
1680 if (Lex.getCode() == tgtok::r_paren) {
1681 Lex.Lex(); // eat the ')'
1682 break;
1683 }
1684
1685 Init *V = ParseValue(CurRec);
1686 if (!V)
1687 return nullptr;
1688 Case.push_back(V);
1689
1690 if (Lex.getCode() != tgtok::colon) {
1691 TokError("expected ':' following a condition in !cond operator");
1692 return nullptr;
1693 }
1694 Lex.Lex(); // eat the ':'
1695
1696 V = ParseValue(CurRec, ItemType);
1697 if (!V)
1698 return nullptr;
1699 Val.push_back(V);
1700
1701 if (Lex.getCode() == tgtok::r_paren) {
1702 Lex.Lex(); // eat the ')'
1703 break;
1704 }
1705
1706 if (Lex.getCode() != tgtok::comma) {
1707 TokError("expected ',' or ')' following a value in !cond operator");
1708 return nullptr;
1709 }
1710 Lex.Lex(); // eat the ','
1711 }
1712
1713 if (Case.size() < 1) {
1714 TokError("there should be at least 1 'condition : value' in the !cond operator");
1715 return nullptr;
1716 }
1717
1718 // resolve type
1719 RecTy *Type = nullptr;
1720 for (Init *V : Val) {
1721 RecTy *VTy = nullptr;
1722 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1723 VTy = Vt->getType();
1724 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1725 VTy = BitsRecTy::get(Vbits->getNumBits());
1726 if (isa<BitInit>(V))
1727 VTy = BitRecTy::get();
1728
1729 if (Type == nullptr) {
1730 if (!isa<UnsetInit>(V))
1731 Type = VTy;
1732 } else {
1733 if (!isa<UnsetInit>(V)) {
1734 RecTy *RType = resolveTypes(Type, VTy);
1735 if (!RType) {
1736 TokError(Twine("inconsistent types '") + Type->getAsString() +
1737 "' and '" + VTy->getAsString() + "' for !cond");
1738 return nullptr;
1739 }
1740 Type = RType;
1741 }
1742 }
1743 }
1744
1745 if (!Type) {
1746 TokError("could not determine type for !cond from its arguments");
1747 return nullptr;
1748 }
1749 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1124 } 1750 }
1125 1751
1126 /// ParseSimpleValue - Parse a tblgen value. This returns null on error. 1752 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1127 /// 1753 ///
1128 /// SimpleValue ::= IDValue 1754 /// SimpleValue ::= IDValue
1138 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')' 1764 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1139 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')' 1765 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1140 /// SimpleValue ::= SRATOK '(' Value ',' Value ')' 1766 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1141 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')' 1767 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1142 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')' 1768 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1769 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1143 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')' 1770 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1771 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1144 /// 1772 ///
1145 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType, 1773 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1146 IDParseMode Mode) { 1774 IDParseMode Mode) {
1147 Init *R = nullptr; 1775 Init *R = nullptr;
1148 switch (Lex.getCode()) { 1776 switch (Lex.getCode()) {
1174 1802
1175 R = StringInit::get(Val); 1803 R = StringInit::get(Val);
1176 break; 1804 break;
1177 } 1805 }
1178 case tgtok::CodeFragment: 1806 case tgtok::CodeFragment:
1179 R = CodeInit::get(Lex.getCurStrVal()); 1807 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1180 Lex.Lex(); 1808 Lex.Lex();
1181 break; 1809 break;
1182 case tgtok::question: 1810 case tgtok::question:
1183 R = UnsetInit::get(); 1811 R = UnsetInit::get();
1184 Lex.Lex(); 1812 Lex.Lex();
1202 if (!Class) { 1830 if (!Class) {
1203 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'"); 1831 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1204 return nullptr; 1832 return nullptr;
1205 } 1833 }
1206 1834
1207 SubClassReference SCRef; 1835 SmallVector<Init *, 8> Args;
1208 ParseValueList(SCRef.TemplateArgs, CurRec, Class); 1836 ParseValueList(Args, CurRec, Class);
1209 if (SCRef.TemplateArgs.empty()) return nullptr; 1837 if (Args.empty()) return nullptr;
1210 1838
1211 if (Lex.getCode() != tgtok::greater) { 1839 if (Lex.getCode() != tgtok::greater) {
1212 TokError("expected '>' at end of value list"); 1840 TokError("expected '>' at end of value list");
1213 return nullptr; 1841 return nullptr;
1214 } 1842 }
1215 Lex.Lex(); // eat the '>' 1843 Lex.Lex(); // eat the '>'
1216 SMLoc EndLoc = Lex.getLoc(); 1844
1217 1845 // Typecheck the template arguments list
1218 // Create the new record, set it as CurRec temporarily. 1846 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1219 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc, 1847 if (ExpectedArgs.size() < Args.size()) {
1220 Records, /*IsAnonymous=*/true); 1848 Error(NameLoc,
1221 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release. 1849 "More template args specified than expected");
1222 SCRef.RefRange = SMRange(NameLoc, EndLoc); 1850 return nullptr;
1223 SCRef.Rec = Class; 1851 }
1224 // Add info about the subclass to NewRec. 1852
1225 if (AddSubClass(NewRec, SCRef)) 1853 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1226 return nullptr; 1854 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1227 1855 if (i < Args.size()) {
1228 if (!CurMultiClass) { 1856 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1229 NewRec->resolveReferences(); 1857 RecTy *ExpectedType = ExpectedArg->getType();
1230 Records.addDef(std::move(NewRecOwner)); 1858 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1231 } else { 1859 Error(NameLoc,
1232 // This needs to get resolved once the multiclass template arguments are 1860 "Value specified for template argument #" + Twine(i) + " (" +
1233 // known before any use. 1861 ExpectedArg->getNameInitAsString() + ") is of type '" +
1234 NewRec->setResolveFirst(true); 1862 TI->getType()->getAsString() + "', expected '" +
1235 // Otherwise, we're inside a multiclass, add it to the multiclass. 1863 ExpectedType->getAsString() + "': " + TI->getAsString());
1236 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner)); 1864 return nullptr;
1237 1865 }
1238 // Copy the template arguments for the multiclass into the def. 1866 continue;
1239 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) { 1867 }
1240 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg); 1868 } else if (ExpectedArg->getValue()->isComplete())
1241 assert(RV && "Template arg doesn't exist?"); 1869 continue;
1242 NewRec->addValue(*RV); 1870
1243 } 1871 Error(NameLoc,
1244 1872 "Value not specified for template argument #" + Twine(i) + " (" +
1245 // We can't return the prototype def here, instead return: 1873 ExpectedArgs[i]->getAsUnquotedString() + ")");
1246 // !cast<ItemType>(!strconcat(NAME, AnonName)). 1874 return nullptr;
1247 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME"); 1875 }
1248 assert(MCNameRV && "multiclass record must have a NAME"); 1876
1249 1877 return VarDefInit::get(Class, Args)->Fold();
1250 return UnOpInit::get(UnOpInit::CAST,
1251 BinOpInit::get(BinOpInit::STRCONCAT,
1252 VarInit::get(MCNameRV->getName(),
1253 MCNameRV->getType()),
1254 NewRec->getNameInit(),
1255 StringRecTy::get()),
1256 Class->getDefInit()->getType());
1257 }
1258
1259 // The result of the expression is a reference to the new record.
1260 return DefInit::get(NewRec);
1261 } 1878 }
1262 case tgtok::l_brace: { // Value ::= '{' ValueList '}' 1879 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1263 SMLoc BraceLoc = Lex.getLoc(); 1880 SMLoc BraceLoc = Lex.getLoc();
1264 Lex.Lex(); // eat the '{' 1881 Lex.Lex(); // eat the '{'
1265 SmallVector<Init*, 16> Vals; 1882 SmallVector<Init*, 16> Vals;
1297 continue; 1914 continue;
1298 } 1915 }
1299 // Fallthrough to try convert this to a bit. 1916 // Fallthrough to try convert this to a bit.
1300 } 1917 }
1301 // All other values must be convertible to just a single bit. 1918 // All other values must be convertible to just a single bit.
1302 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get()); 1919 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1303 if (!Bit) { 1920 if (!Bit) {
1304 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() + 1921 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1305 ") is not convertable to a bit"); 1922 ") is not convertable to a bit");
1306 return nullptr; 1923 return nullptr;
1307 } 1924 }
1358 1975
1359 // Check elements 1976 // Check elements
1360 RecTy *EltTy = nullptr; 1977 RecTy *EltTy = nullptr;
1361 for (Init *V : Vals) { 1978 for (Init *V : Vals) {
1362 TypedInit *TArg = dyn_cast<TypedInit>(V); 1979 TypedInit *TArg = dyn_cast<TypedInit>(V);
1363 if (!TArg) { 1980 if (TArg) {
1364 TokError("Untyped list element"); 1981 if (EltTy) {
1365 return nullptr; 1982 EltTy = resolveTypes(EltTy, TArg->getType());
1366 } 1983 if (!EltTy) {
1367 if (EltTy) { 1984 TokError("Incompatible types in list elements");
1368 EltTy = resolveTypes(EltTy, TArg->getType()); 1985 return nullptr;
1369 if (!EltTy) { 1986 }
1370 TokError("Incompatible types in list elements"); 1987 } else {
1371 return nullptr; 1988 EltTy = TArg->getType();
1372 } 1989 }
1373 } else {
1374 EltTy = TArg->getType();
1375 } 1990 }
1376 } 1991 }
1377 1992
1378 if (GivenEltTy) { 1993 if (GivenEltTy) {
1379 if (EltTy) { 1994 if (EltTy) {
1394 DeducedEltTy = GivenListTy->getElementType(); 2009 DeducedEltTy = GivenListTy->getElementType();
1395 } else { 2010 } else {
1396 // Make sure the deduced type is compatible with the given type 2011 // Make sure the deduced type is compatible with the given type
1397 if (GivenListTy) { 2012 if (GivenListTy) {
1398 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) { 2013 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1399 TokError("Element type mismatch for list"); 2014 TokError(Twine("Element type mismatch for list: element type '") +
2015 EltTy->getAsString() + "' not convertible to '" +
2016 GivenListTy->getElementType()->getAsString());
1400 return nullptr; 2017 return nullptr;
1401 } 2018 }
1402 } 2019 }
1403 DeducedEltTy = EltTy; 2020 DeducedEltTy = EltTy;
1404 } 2021 }
1441 return DagInit::get(Operator, OperatorName, DagArgs); 2058 return DagInit::get(Operator, OperatorName, DagArgs);
1442 } 2059 }
1443 2060
1444 case tgtok::XHead: 2061 case tgtok::XHead:
1445 case tgtok::XTail: 2062 case tgtok::XTail:
2063 case tgtok::XSize:
1446 case tgtok::XEmpty: 2064 case tgtok::XEmpty:
1447 case tgtok::XCast: // Value ::= !unop '(' Value ')' 2065 case tgtok::XCast: // Value ::= !unop '(' Value ')'
2066 case tgtok::XIsA:
1448 case tgtok::XConcat: 2067 case tgtok::XConcat:
2068 case tgtok::XDag:
1449 case tgtok::XADD: 2069 case tgtok::XADD:
2070 case tgtok::XMUL:
1450 case tgtok::XAND: 2071 case tgtok::XAND:
1451 case tgtok::XOR: 2072 case tgtok::XOR:
1452 case tgtok::XSRA: 2073 case tgtok::XSRA:
1453 case tgtok::XSRL: 2074 case tgtok::XSRL:
1454 case tgtok::XSHL: 2075 case tgtok::XSHL:
1455 case tgtok::XEq: 2076 case tgtok::XEq:
2077 case tgtok::XNe:
2078 case tgtok::XLe:
2079 case tgtok::XLt:
2080 case tgtok::XGe:
2081 case tgtok::XGt:
1456 case tgtok::XListConcat: 2082 case tgtok::XListConcat:
2083 case tgtok::XListSplat:
1457 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')' 2084 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1458 case tgtok::XIf: 2085 case tgtok::XIf:
2086 case tgtok::XCond:
2087 case tgtok::XFoldl:
1459 case tgtok::XForEach: 2088 case tgtok::XForEach:
1460 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 2089 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1461 return ParseOperation(CurRec, ItemType); 2090 return ParseOperation(CurRec, ItemType);
1462 } 2091 }
1463 } 2092 }
1479 // Parse the suffixes now if present. 2108 // Parse the suffixes now if present.
1480 while (true) { 2109 while (true) {
1481 switch (Lex.getCode()) { 2110 switch (Lex.getCode()) {
1482 default: return Result; 2111 default: return Result;
1483 case tgtok::l_brace: { 2112 case tgtok::l_brace: {
1484 if (Mode == ParseNameMode || Mode == ParseForeachMode) 2113 if (Mode == ParseNameMode)
1485 // This is the beginning of the object body. 2114 // This is the beginning of the object body.
1486 return Result; 2115 return Result;
1487 2116
1488 SMLoc CurlyLoc = Lex.getLoc(); 2117 SMLoc CurlyLoc = Lex.getLoc();
1489 Lex.Lex(); // eat the '{' 2118 Lex.Lex(); // eat the '{'
1537 if (!Result->getFieldType(FieldName)) { 2166 if (!Result->getFieldType(FieldName)) {
1538 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" + 2167 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1539 Result->getAsString() + "'"); 2168 Result->getAsString() + "'");
1540 return nullptr; 2169 return nullptr;
1541 } 2170 }
1542 Result = FieldInit::get(Result, FieldName); 2171 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
1543 Lex.Lex(); // eat field name 2172 Lex.Lex(); // eat field name
1544 break; 2173 break;
1545 } 2174 }
1546 2175
1547 case tgtok::paste: 2176 case tgtok::paste:
1548 SMLoc PasteLoc = Lex.getLoc(); 2177 SMLoc PasteLoc = Lex.getLoc();
1549
1550 // Create a !strconcat() operation, first casting each operand to
1551 // a string if necessary.
1552
1553 TypedInit *LHS = dyn_cast<TypedInit>(Result); 2178 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1554 if (!LHS) { 2179 if (!LHS) {
1555 Error(PasteLoc, "LHS of paste is not typed!"); 2180 Error(PasteLoc, "LHS of paste is not typed!");
1556 return nullptr; 2181 return nullptr;
1557 } 2182 }
1558 2183
2184 // Check if it's a 'listA # listB'
2185 if (isa<ListRecTy>(LHS->getType())) {
2186 Lex.Lex(); // Eat the '#'.
2187
2188 switch (Lex.getCode()) {
2189 case tgtok::colon:
2190 case tgtok::semi:
2191 case tgtok::l_brace:
2192 Result = LHS; // trailing paste, ignore.
2193 break;
2194 default:
2195 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2196 Result = BinOpInit::getListConcat(LHS, RHSResult);
2197 }
2198 break;
2199 }
2200
2201 // Create a !strconcat() operation, first casting each operand to
2202 // a string if necessary.
1559 if (LHS->getType() != StringRecTy::get()) { 2203 if (LHS->getType() != StringRecTy::get()) {
1560 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get()); 2204 auto CastLHS = dyn_cast<TypedInit>(
2205 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2206 ->Fold(CurRec));
2207 if (!CastLHS) {
2208 Error(PasteLoc,
2209 Twine("can't cast '") + LHS->getAsString() + "' to string");
2210 return nullptr;
2211 }
2212 LHS = CastLHS;
1561 } 2213 }
1562 2214
1563 TypedInit *RHS = nullptr; 2215 TypedInit *RHS = nullptr;
1564 2216
1565 Lex.Lex(); // Eat the '#'. 2217 Lex.Lex(); // Eat the '#'.
1566 switch (Lex.getCode()) { 2218 switch (Lex.getCode()) {
1567 case tgtok::colon: 2219 case tgtok::colon:
1568 case tgtok::semi: 2220 case tgtok::semi:
1569 case tgtok::l_brace: 2221 case tgtok::l_brace:
1570 // These are all of the tokens that can begin an object body. 2222 // These are all of the tokens that can begin an object body.
1571 // Some of these can also begin values but we disallow those cases 2223 // Some of these can also begin values but we disallow those cases
1574 // Trailing paste, concat with an empty string. 2226 // Trailing paste, concat with an empty string.
1575 RHS = StringInit::get(""); 2227 RHS = StringInit::get("");
1576 break; 2228 break;
1577 2229
1578 default: 2230 default:
1579 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode); 2231 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
1580 RHS = dyn_cast<TypedInit>(RHSResult); 2232 RHS = dyn_cast<TypedInit>(RHSResult);
1581 if (!RHS) { 2233 if (!RHS) {
1582 Error(PasteLoc, "RHS of paste is not typed!"); 2234 Error(PasteLoc, "RHS of paste is not typed!");
1583 return nullptr; 2235 return nullptr;
1584 } 2236 }
1585 2237
1586 if (RHS->getType() != StringRecTy::get()) { 2238 if (RHS->getType() != StringRecTy::get()) {
1587 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get()); 2239 auto CastRHS = dyn_cast<TypedInit>(
2240 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2241 ->Fold(CurRec));
2242 if (!CastRHS) {
2243 Error(PasteLoc,
2244 Twine("can't cast '") + RHS->getAsString() + "' to string");
2245 return nullptr;
2246 }
2247 RHS = CastRHS;
1588 } 2248 }
1589 2249
1590 break; 2250 break;
1591 } 2251 }
1592 2252
1593 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS, 2253 Result = BinOpInit::getStrConcat(LHS, RHS);
1594 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1595 break; 2254 break;
1596 } 2255 }
1597 } 2256 }
1598 } 2257 }
1599 2258
1674 } 2333 }
1675 2334
1676 while (Lex.getCode() == tgtok::comma) { 2335 while (Lex.getCode() == tgtok::comma) {
1677 Lex.Lex(); // Eat the comma 2336 Lex.Lex(); // Eat the comma
1678 2337
2338 // ignore trailing comma for lists
2339 if (Lex.getCode() == tgtok::r_square)
2340 return;
2341
1679 if (ArgsRec && !EltTy) { 2342 if (ArgsRec && !EltTy) {
1680 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2343 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
1681 if (ArgN >= TArgs.size()) { 2344 if (ArgN >= TArgs.size()) {
1682 TokError("too many template arguments"); 2345 TokError("too many template arguments");
1683 Result.clear(); 2346 Result.clear();
1718 if (Lex.getCode() != tgtok::Id) { 2381 if (Lex.getCode() != tgtok::Id) {
1719 TokError("Expected identifier in declaration"); 2382 TokError("Expected identifier in declaration");
1720 return nullptr; 2383 return nullptr;
1721 } 2384 }
1722 2385
2386 std::string Str = Lex.getCurStrVal();
2387 if (Str == "NAME") {
2388 TokError("'" + Str + "' is a reserved variable name");
2389 return nullptr;
2390 }
2391
1723 SMLoc IdLoc = Lex.getLoc(); 2392 SMLoc IdLoc = Lex.getLoc();
1724 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 2393 Init *DeclName = StringInit::get(Str);
1725 Lex.Lex(); 2394 Lex.Lex();
1726 2395
1727 if (ParsingTemplateArgs) { 2396 if (ParsingTemplateArgs) {
1728 if (CurRec) 2397 if (CurRec)
1729 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":"); 2398 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1756 2425
1757 /// ParseForeachDeclaration - Read a foreach declaration, returning 2426 /// ParseForeachDeclaration - Read a foreach declaration, returning
1758 /// the name of the declared object or a NULL Init on error. Return 2427 /// the name of the declared object or a NULL Init on error. Return
1759 /// the name of the parsed initializer list through ForeachListName. 2428 /// the name of the parsed initializer list through ForeachListName.
1760 /// 2429 ///
1761 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1762 /// ForeachDeclaration ::= ID '=' '{' RangeList '}' 2430 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1763 /// ForeachDeclaration ::= ID '=' RangePiece 2431 /// ForeachDeclaration ::= ID '=' RangePiece
1764 /// 2432 /// ForeachDeclaration ::= ID '=' Value
1765 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) { 2433 ///
2434 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
1766 if (Lex.getCode() != tgtok::Id) { 2435 if (Lex.getCode() != tgtok::Id) {
1767 TokError("Expected identifier in foreach declaration"); 2436 TokError("Expected identifier in foreach declaration");
1768 return nullptr; 2437 return nullptr;
1769 } 2438 }
1770 2439
1780 2449
1781 RecTy *IterType = nullptr; 2450 RecTy *IterType = nullptr;
1782 SmallVector<unsigned, 16> Ranges; 2451 SmallVector<unsigned, 16> Ranges;
1783 2452
1784 switch (Lex.getCode()) { 2453 switch (Lex.getCode()) {
1785 default: TokError("Unknown token when expecting a range list"); return nullptr;
1786 case tgtok::l_square: { // '[' ValueList ']'
1787 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1788 ForeachListValue = dyn_cast<ListInit>(List);
1789 if (!ForeachListValue) {
1790 TokError("Expected a Value list");
1791 return nullptr;
1792 }
1793 RecTy *ValueType = ForeachListValue->getType();
1794 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1795 if (!ListType) {
1796 TokError("Value list is not of list type");
1797 return nullptr;
1798 }
1799 IterType = ListType->getElementType();
1800 break;
1801 }
1802
1803 case tgtok::IntVal: { // RangePiece.
1804 if (ParseRangePiece(Ranges))
1805 return nullptr;
1806 break;
1807 }
1808
1809 case tgtok::l_brace: { // '{' RangeList '}' 2454 case tgtok::l_brace: { // '{' RangeList '}'
1810 Lex.Lex(); // eat the '{' 2455 Lex.Lex(); // eat the '{'
1811 ParseRangeList(Ranges); 2456 ParseRangeList(Ranges);
1812 if (Lex.getCode() != tgtok::r_brace) { 2457 if (Lex.getCode() != tgtok::r_brace) {
1813 TokError("expected '}' at end of bit range list"); 2458 TokError("expected '}' at end of bit range list");
1814 return nullptr; 2459 return nullptr;
1815 } 2460 }
1816 Lex.Lex(); 2461 Lex.Lex();
1817 break; 2462 break;
1818 } 2463 }
1819 } 2464
2465 default: {
2466 SMLoc ValueLoc = Lex.getLoc();
2467 Init *I = ParseValue(nullptr);
2468 if (!I)
2469 return nullptr;
2470
2471 TypedInit *TI = dyn_cast<TypedInit>(I);
2472 if (TI && isa<ListRecTy>(TI->getType())) {
2473 ForeachListValue = I;
2474 IterType = cast<ListRecTy>(TI->getType())->getElementType();
2475 break;
2476 }
2477
2478 if (TI) {
2479 if (ParseRangePiece(Ranges, TI))
2480 return nullptr;
2481 break;
2482 }
2483
2484 std::string Type;
2485 if (TI)
2486 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2487 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2488 if (CurMultiClass) {
2489 PrintNote({}, "references to multiclass template arguments cannot be "
2490 "resolved at this time");
2491 }
2492 return nullptr;
2493 }
2494 }
2495
1820 2496
1821 if (!Ranges.empty()) { 2497 if (!Ranges.empty()) {
1822 assert(!IterType && "Type already initialized?"); 2498 assert(!IterType && "Type already initialized?");
1823 IterType = IntRecTy::get(); 2499 IterType = IntRecTy::get();
1824 std::vector<Init*> Values; 2500 std::vector<Init*> Values;
1855 2531
1856 while (Lex.getCode() == tgtok::comma) { 2532 while (Lex.getCode() == tgtok::comma) {
1857 Lex.Lex(); // eat the ',' 2533 Lex.Lex(); // eat the ','
1858 2534
1859 // Read the following declarations. 2535 // Read the following declarations.
2536 SMLoc Loc = Lex.getLoc();
1860 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2537 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1861 if (!TemplArg) 2538 if (!TemplArg)
1862 return true; 2539 return true;
2540
2541 if (TheRecToAddTo->isTemplateArg(TemplArg))
2542 return Error(Loc, "template argument with the same name has already been "
2543 "defined");
2544
1863 TheRecToAddTo->addTemplateArg(TemplArg); 2545 TheRecToAddTo->addTemplateArg(TemplArg);
1864 } 2546 }
1865 2547
1866 if (Lex.getCode() != tgtok::greater) 2548 if (Lex.getCode() != tgtok::greater)
1867 return TokError("expected '>' at end of template argument list"); 2549 return TokError("expected '>' at end of template argument list");
1943 // Eat the '}'. 2625 // Eat the '}'.
1944 Lex.Lex(); 2626 Lex.Lex();
1945 return false; 2627 return false;
1946 } 2628 }
1947 2629
1948 /// \brief Apply the current let bindings to \a CurRec. 2630 /// Apply the current let bindings to \a CurRec.
1949 /// \returns true on error, false otherwise. 2631 /// \returns true on error, false otherwise.
1950 bool TGParser::ApplyLetStack(Record *CurRec) { 2632 bool TGParser::ApplyLetStack(Record *CurRec) {
1951 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack) 2633 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
1952 for (LetRecord &LR : LetInfo) 2634 for (LetRecord &LR : LetInfo)
1953 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value)) 2635 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
1954 return true; 2636 return true;
1955 return false; 2637 return false;
1956 } 2638 }
1957 2639
2640 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2641 if (Entry.Rec)
2642 return ApplyLetStack(Entry.Rec.get());
2643
2644 for (auto &E : Entry.Loop->Entries) {
2645 if (ApplyLetStack(E))
2646 return true;
2647 }
2648
2649 return false;
2650 }
2651
1958 /// ParseObjectBody - Parse the body of a def or class. This consists of an 2652 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1959 /// optional ClassList followed by a Body. CurRec is the current def or class 2653 /// optional ClassList followed by a Body. CurRec is the current def or class
1960 /// that is being parsed. 2654 /// that is being parsed.
1961 /// 2655 ///
1962 /// ObjectBody ::= BaseClassList Body 2656 /// ObjectBody ::= BaseClassList Body
2000 SMLoc DefLoc = Lex.getLoc(); 2694 SMLoc DefLoc = Lex.getLoc();
2001 assert(Lex.getCode() == tgtok::Def && "Unknown tok"); 2695 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2002 Lex.Lex(); // Eat the 'def' token. 2696 Lex.Lex(); // Eat the 'def' token.
2003 2697
2004 // Parse ObjectName and make a record for it. 2698 // Parse ObjectName and make a record for it.
2005 std::unique_ptr<Record> CurRecOwner; 2699 std::unique_ptr<Record> CurRec;
2006 Init *Name = ParseObjectName(CurMultiClass); 2700 Init *Name = ParseObjectName(CurMultiClass);
2007 if (Name) 2701 if (!Name)
2008 CurRecOwner = make_unique<Record>(Name, DefLoc, Records); 2702 return true;
2703
2704 if (isa<UnsetInit>(Name))
2705 CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2706 /*Anonymous=*/true);
2009 else 2707 else
2010 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc, 2708 CurRec = make_unique<Record>(Name, DefLoc, Records);
2011 Records, /*IsAnonymous=*/true); 2709
2012 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release. 2710 if (ParseObjectBody(CurRec.get()))
2013
2014 if (!CurMultiClass && Loops.empty()) {
2015 // Top-level def definition.
2016
2017 // Ensure redefinition doesn't happen.
2018 if (Records.getDef(CurRec->getNameInitAsString()))
2019 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2020 "' already defined");
2021 Records.addDef(std::move(CurRecOwner));
2022
2023 if (ParseObjectBody(CurRec))
2024 return true;
2025 } else if (CurMultiClass) {
2026 // Parse the body before adding this prototype to the DefPrototypes vector.
2027 // That way implicit definitions will be added to the DefPrototypes vector
2028 // before this object, instantiated prior to defs derived from this object,
2029 // and this available for indirect name resolution when defs derived from
2030 // this object are instantiated.
2031 if (ParseObjectBody(CurRec))
2032 return true;
2033
2034 // Otherwise, a def inside a multiclass, add it to the multiclass.
2035 for (const auto &Proto : CurMultiClass->DefPrototypes)
2036 if (Proto->getNameInit() == CurRec->getNameInit())
2037 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2038 "' already defined in this multiclass!");
2039 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2040 } else if (ParseObjectBody(CurRec)) {
2041 return true; 2711 return true;
2042 } 2712
2043 2713 return addEntry(std::move(CurRec));
2044 if (!CurMultiClass) // Def's in multiclasses aren't really defs. 2714 }
2045 // See Record::setName(). This resolve step will see any new name 2715
2046 // for the def that might have been created when resolving 2716 /// ParseDefset - Parse a defset statement.
2047 // inheritance, values and arguments above. 2717 ///
2048 CurRec->resolveReferences(); 2718 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2049 2719 ///
2050 // If ObjectBody has template arguments, it's an error. 2720 bool TGParser::ParseDefset() {
2051 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?"); 2721 assert(Lex.getCode() == tgtok::Defset);
2052 2722 Lex.Lex(); // Eat the 'defset' token
2053 if (CurMultiClass) { 2723
2054 // Copy the template arguments for the multiclass into the def. 2724 DefsetRecord Defset;
2055 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) { 2725 Defset.Loc = Lex.getLoc();
2056 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg); 2726 RecTy *Type = ParseType();
2057 assert(RV && "Template arg doesn't exist?"); 2727 if (!Type)
2058 CurRec->addValue(*RV); 2728 return true;
2059 } 2729 if (!isa<ListRecTy>(Type))
2060 } 2730 return Error(Defset.Loc, "expected list type");
2061 2731 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2062 if (ProcessForeachDefs(CurRec, DefLoc)) 2732
2063 return Error(DefLoc, "Could not process loops for def" + 2733 if (Lex.getCode() != tgtok::Id)
2064 CurRec->getNameInitAsString()); 2734 return TokError("expected identifier");
2065 2735 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2736 if (Records.getGlobal(DeclName->getValue()))
2737 return TokError("def or global variable of this name already exists");
2738
2739 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2740 return TokError("expected '='");
2741 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2742 return TokError("expected '{'");
2743 SMLoc BraceLoc = Lex.getLoc();
2744 Lex.Lex(); // Eat the '{'
2745
2746 Defsets.push_back(&Defset);
2747 bool Err = ParseObjectList(nullptr);
2748 Defsets.pop_back();
2749 if (Err)
2750 return true;
2751
2752 if (Lex.getCode() != tgtok::r_brace) {
2753 TokError("expected '}' at end of defset");
2754 return Error(BraceLoc, "to match this '{'");
2755 }
2756 Lex.Lex(); // Eat the '}'
2757
2758 Records.addExtraGlobal(DeclName->getValue(),
2759 ListInit::get(Defset.Elements, Defset.EltTy));
2066 return false; 2760 return false;
2067 } 2761 }
2068 2762
2069 /// ParseForeach - Parse a for statement. Return the record corresponding 2763 /// ParseForeach - Parse a for statement. Return the record corresponding
2070 /// to it. This returns true on error. 2764 /// to it. This returns true on error.
2071 /// 2765 ///
2072 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}' 2766 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2073 /// Foreach ::= FOREACH Declaration IN Object 2767 /// Foreach ::= FOREACH Declaration IN Object
2074 /// 2768 ///
2075 bool TGParser::ParseForeach(MultiClass *CurMultiClass) { 2769 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2770 SMLoc Loc = Lex.getLoc();
2076 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok"); 2771 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2077 Lex.Lex(); // Eat the 'for' token. 2772 Lex.Lex(); // Eat the 'for' token.
2078 2773
2079 // Make a temporary object to record items associated with the for 2774 // Make a temporary object to record items associated with the for
2080 // loop. 2775 // loop.
2081 ListInit *ListValue = nullptr; 2776 Init *ListValue = nullptr;
2082 VarInit *IterName = ParseForeachDeclaration(ListValue); 2777 VarInit *IterName = ParseForeachDeclaration(ListValue);
2083 if (!IterName) 2778 if (!IterName)
2084 return TokError("expected declaration in for"); 2779 return TokError("expected declaration in for");
2085 2780
2086 if (Lex.getCode() != tgtok::In) 2781 if (Lex.getCode() != tgtok::In)
2087 return TokError("Unknown tok"); 2782 return TokError("Unknown tok");
2088 Lex.Lex(); // Eat the in 2783 Lex.Lex(); // Eat the in
2089 2784
2090 // Create a loop object and remember it. 2785 // Create a loop object and remember it.
2091 Loops.push_back(ForeachLoop(IterName, ListValue)); 2786 Loops.push_back(llvm::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2092 2787
2093 if (Lex.getCode() != tgtok::l_brace) { 2788 if (Lex.getCode() != tgtok::l_brace) {
2094 // FOREACH Declaration IN Object 2789 // FOREACH Declaration IN Object
2095 if (ParseObject(CurMultiClass)) 2790 if (ParseObject(CurMultiClass))
2096 return true; 2791 return true;
2108 return Error(BraceLoc, "to match this '{'"); 2803 return Error(BraceLoc, "to match this '{'");
2109 } 2804 }
2110 Lex.Lex(); // Eat the } 2805 Lex.Lex(); // Eat the }
2111 } 2806 }
2112 2807
2113 // We've processed everything in this loop. 2808 // Resolve the loop or store it for later resolution.
2809 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2114 Loops.pop_back(); 2810 Loops.pop_back();
2115 2811
2116 return false; 2812 return addEntry(std::move(Loop));
2117 } 2813 }
2118 2814
2119 /// ParseClass - Parse a tblgen class definition. 2815 /// ParseClass - Parse a tblgen class definition.
2120 /// 2816 ///
2121 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody 2817 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2128 return TokError("expected class name after 'class' keyword"); 2824 return TokError("expected class name after 'class' keyword");
2129 2825
2130 Record *CurRec = Records.getClass(Lex.getCurStrVal()); 2826 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2131 if (CurRec) { 2827 if (CurRec) {
2132 // If the body was previously defined, this is an error. 2828 // If the body was previously defined, this is an error.
2133 if (CurRec->getValues().size() > 1 || // Account for NAME. 2829 if (!CurRec->getValues().empty() ||
2134 !CurRec->getSuperClasses().empty() || 2830 !CurRec->getSuperClasses().empty() ||
2135 !CurRec->getTemplateArgs().empty()) 2831 !CurRec->getTemplateArgs().empty())
2136 return TokError("Class '" + CurRec->getNameInitAsString() + 2832 return TokError("Class '" + CurRec->getNameInitAsString() +
2137 "' already defined"); 2833 "' already defined");
2138 } else { 2834 } else {
2139 // If this is the first reference to this class, create and add it. 2835 // If this is the first reference to this class, create and add it.
2140 auto NewRec = 2836 auto NewRec =
2141 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records); 2837 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
2838 /*Class=*/true);
2142 CurRec = NewRec.get(); 2839 CurRec = NewRec.get();
2143 Records.addClass(std::move(NewRec)); 2840 Records.addClass(std::move(NewRec));
2144 } 2841 }
2145 Lex.Lex(); // eat the name. 2842 Lex.Lex(); // eat the name.
2146 2843
2147 // If there are template args, parse them. 2844 // If there are template args, parse them.
2148 if (Lex.getCode() == tgtok::less) 2845 if (Lex.getCode() == tgtok::less)
2149 if (ParseTemplateArgList(CurRec)) 2846 if (ParseTemplateArgList(CurRec))
2150 return true; 2847 return true;
2151 2848
2152 // Finally, parse the object body.
2153 return ParseObjectBody(CurRec); 2849 return ParseObjectBody(CurRec);
2154 } 2850 }
2155 2851
2156 /// ParseLetList - Parse a non-empty list of assignment expressions into a list 2852 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2157 /// of LetRecords. 2853 /// of LetRecords.
2316 return TokError("multiclass must contain at least one def"); 3012 return TokError("multiclass must contain at least one def");
2317 3013
2318 while (Lex.getCode() != tgtok::r_brace) { 3014 while (Lex.getCode() != tgtok::r_brace) {
2319 switch (Lex.getCode()) { 3015 switch (Lex.getCode()) {
2320 default: 3016 default:
2321 return TokError("expected 'let', 'def' or 'defm' in multiclass body"); 3017 return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
3018 "multiclass body");
2322 case tgtok::Let: 3019 case tgtok::Let:
2323 case tgtok::Def: 3020 case tgtok::Def:
2324 case tgtok::Defm: 3021 case tgtok::Defm:
2325 case tgtok::Foreach: 3022 case tgtok::Foreach:
2326 if (ParseObject(CurMultiClass)) 3023 if (ParseObject(CurMultiClass))
2333 3030
2334 CurMultiClass = nullptr; 3031 CurMultiClass = nullptr;
2335 return false; 3032 return false;
2336 } 3033 }
2337 3034
2338 Record *TGParser::InstantiateMulticlassDef(MultiClass &MC, Record *DefProto,
2339 Init *&DefmPrefix,
2340 SMRange DefmPrefixRange,
2341 ArrayRef<Init *> TArgs,
2342 ArrayRef<Init *> TemplateVals) {
2343 // We need to preserve DefProto so it can be reused for later
2344 // instantiations, so create a new Record to inherit from it.
2345
2346 // Add in the defm name. If the defm prefix is empty, give each
2347 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2348 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2349 // as a prefix.
2350
2351 bool IsAnonymous = false;
2352 if (!DefmPrefix) {
2353 DefmPrefix = GetNewAnonymousName();
2354 IsAnonymous = true;
2355 }
2356
2357 Init *DefName = DefProto->getNameInit();
2358 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2359
2360 if (DefNameString) {
2361 // We have a fully expanded string so there are no operators to
2362 // resolve. We should concatenate the given prefix and name.
2363 DefName =
2364 BinOpInit::get(BinOpInit::STRCONCAT,
2365 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2366 StringRecTy::get())->Fold(DefProto, &MC),
2367 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2368 }
2369
2370 // Make a trail of SMLocs from the multiclass instantiations.
2371 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2372 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2373 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2374
2375 SubClassReference Ref;
2376 Ref.RefRange = DefmPrefixRange;
2377 Ref.Rec = DefProto;
2378 AddSubClass(CurRec.get(), Ref);
2379
2380 // Set the value for NAME. We don't resolve references to it 'til later,
2381 // though, so that uses in nested multiclass names don't get
2382 // confused.
2383 if (SetValue(CurRec.get(), Ref.RefRange.Start, StringInit::get("NAME"), None,
2384 DefmPrefix, /*AllowSelfAssignment*/true)) {
2385 Error(DefmPrefixRange.Start, "Could not resolve " +
2386 CurRec->getNameInitAsString() + ":NAME to '" +
2387 DefmPrefix->getAsUnquotedString() + "'");
2388 return nullptr;
2389 }
2390
2391 // If the DefNameString didn't resolve, we probably have a reference to
2392 // NAME and need to replace it. We need to do at least this much greedily,
2393 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2394 if (!DefNameString) {
2395 RecordVal *DefNameRV = CurRec->getValue("NAME");
2396 CurRec->resolveReferencesTo(DefNameRV);
2397 }
2398
2399 if (!CurMultiClass) {
2400 // Now that we're at the top level, resolve all NAME references
2401 // in the resultant defs that weren't in the def names themselves.
2402 RecordVal *DefNameRV = CurRec->getValue("NAME");
2403 CurRec->resolveReferencesTo(DefNameRV);
2404
2405 // Check if the name is a complex pattern.
2406 // If so, resolve it.
2407 DefName = CurRec->getNameInit();
2408 DefNameString = dyn_cast<StringInit>(DefName);
2409
2410 // OK the pattern is more complex than simply using NAME.
2411 // Let's use the heavy weaponery.
2412 if (!DefNameString) {
2413 ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
2414 Lex.getLoc(), TArgs, TemplateVals,
2415 false/*Delete args*/);
2416 DefName = CurRec->getNameInit();
2417 DefNameString = dyn_cast<StringInit>(DefName);
2418
2419 if (!DefNameString)
2420 DefName = DefName->convertInitializerTo(StringRecTy::get());
2421
2422 // We ran out of options here...
2423 DefNameString = dyn_cast<StringInit>(DefName);
2424 if (!DefNameString) {
2425 PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
2426 DefName->getAsUnquotedString() + " is not a string.");
2427 return nullptr;
2428 }
2429
2430 CurRec->setName(DefName);
2431 }
2432
2433 // Now that NAME references are resolved and we're at the top level of
2434 // any multiclass expansions, add the record to the RecordKeeper. If we are
2435 // currently in a multiclass, it means this defm appears inside a
2436 // multiclass and its name won't be fully resolvable until we see
2437 // the top-level defm. Therefore, we don't add this to the
2438 // RecordKeeper at this point. If we did we could get duplicate
2439 // defs as more than one probably refers to NAME or some other
2440 // common internal placeholder.
2441
2442 // Ensure redefinition doesn't happen.
2443 if (Records.getDef(CurRec->getNameInitAsString())) {
2444 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2445 "' already defined, instantiating defm with subdef '" +
2446 DefProto->getNameInitAsString() + "'");
2447 return nullptr;
2448 }
2449
2450 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2451 Records.addDef(std::move(CurRec));
2452 return CurRecSave;
2453 }
2454
2455 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2456 // The unique_ptr in this function at least protects the exits above.
2457 return CurRec.release();
2458 }
2459
2460 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC, Record *CurRec,
2461 SMLoc DefmPrefixLoc, SMLoc SubClassLoc,
2462 ArrayRef<Init *> TArgs,
2463 ArrayRef<Init *> TemplateVals,
2464 bool DeleteArgs) {
2465 // Loop over all of the template arguments, setting them to the specified
2466 // value or leaving them as the default if necessary.
2467 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2468 // Check if a value is specified for this temp-arg.
2469 if (i < TemplateVals.size()) {
2470 // Set it now.
2471 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], None, TemplateVals[i]))
2472 return true;
2473
2474 // Resolve it next.
2475 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2476
2477 if (DeleteArgs)
2478 // Now remove it.
2479 CurRec->removeValue(TArgs[i]);
2480
2481 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2482 return Error(SubClassLoc, "value not specified for template argument #" +
2483 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2484 ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
2485 "'");
2486 }
2487 }
2488 return false;
2489 }
2490
2491 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2492 Record *CurRec,
2493 Record *DefProto,
2494 SMLoc DefmPrefixLoc) {
2495 // If the mdef is inside a 'let' expression, add to each def.
2496 if (ApplyLetStack(CurRec))
2497 return Error(DefmPrefixLoc, "when instantiating this defm");
2498
2499 // Don't create a top level definition for defm inside multiclasses,
2500 // instead, only update the prototypes and bind the template args
2501 // with the new created definition.
2502 if (!CurMultiClass)
2503 return false;
2504 for (const auto &Proto : CurMultiClass->DefPrototypes)
2505 if (Proto->getNameInit() == CurRec->getNameInit())
2506 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2507 "' already defined in this multiclass!");
2508 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2509
2510 // Copy the template arguments for the multiclass into the new def.
2511 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2512 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2513 assert(RV && "Template arg doesn't exist?");
2514 CurRec->addValue(*RV);
2515 }
2516
2517 return false;
2518 }
2519
2520 /// ParseDefm - Parse the instantiation of a multiclass. 3035 /// ParseDefm - Parse the instantiation of a multiclass.
2521 /// 3036 ///
2522 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';' 3037 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2523 /// 3038 ///
2524 bool TGParser::ParseDefm(MultiClass *CurMultiClass) { 3039 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2525 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!"); 3040 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2526 SMLoc DefmLoc = Lex.getLoc(); 3041 Lex.Lex(); // eat the defm
2527 Init *DefmPrefix = nullptr; 3042
2528 3043 Init *DefmName = ParseObjectName(CurMultiClass);
2529 if (Lex.Lex() == tgtok::Id) { // eat the defm. 3044 if (!DefmName)
2530 DefmPrefix = ParseObjectName(CurMultiClass); 3045 return true;
2531 } 3046 if (isa<UnsetInit>(DefmName)) {
2532 3047 DefmName = Records.getNewAnonymousName();
2533 SMLoc DefmPrefixEndLoc = Lex.getLoc(); 3048 if (CurMultiClass)
3049 DefmName = BinOpInit::getStrConcat(
3050 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3051 StringRecTy::get()),
3052 DefmName);
3053 }
3054
2534 if (Lex.getCode() != tgtok::colon) 3055 if (Lex.getCode() != tgtok::colon)
2535 return TokError("expected ':' after defm identifier"); 3056 return TokError("expected ':' after defm identifier");
2536 3057
2537 // Keep track of the new generated record definitions. 3058 // Keep track of the new generated record definitions.
2538 std::vector<Record*> NewRecDefs; 3059 std::vector<RecordsEntry> NewEntries;
2539 3060
2540 // This record also inherits from a regular class (non-multiclass)? 3061 // This record also inherits from a regular class (non-multiclass)?
2541 bool InheritFromClass = false; 3062 bool InheritFromClass = false;
2542 3063
2543 // eat the colon. 3064 // eat the colon.
2560 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs(); 3081 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
2561 if (TArgs.size() < TemplateVals.size()) 3082 if (TArgs.size() < TemplateVals.size())
2562 return Error(SubClassLoc, 3083 return Error(SubClassLoc,
2563 "more template args specified than multiclass expects"); 3084 "more template args specified than multiclass expects");
2564 3085
2565 // Loop over all the def's in the multiclass, instantiating each one. 3086 SubstStack Substs;
2566 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) { 3087 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2567 // The record name construction goes as follow: 3088 if (i < TemplateVals.size()) {
2568 // - If the def name is a string, prepend the prefix. 3089 Substs.emplace_back(TArgs[i], TemplateVals[i]);
2569 // - If the def name is a more complex pattern, use that pattern. 3090 } else {
2570 // As a result, the record is instantiated before resolving 3091 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
2571 // arguments, as it would make its name a string. 3092 if (!Default->isComplete()) {
2572 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix, 3093 return Error(SubClassLoc,
2573 SMRange(DefmLoc, 3094 "value not specified for template argument #" +
2574 DefmPrefixEndLoc), 3095 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2575 TArgs, TemplateVals); 3096 ") of multiclass '" + MC->Rec.getNameInitAsString() +
2576 if (!CurRec) 3097 "'");
2577 return true; 3098 }
2578 3099 Substs.emplace_back(TArgs[i], Default);
2579 // Now that the record is instantiated, we can resolve arguments. 3100 }
2580 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc, 3101 }
2581 TArgs, TemplateVals, true/*Delete args*/)) 3102
2582 return Error(SubClassLoc, "could not instantiate def"); 3103 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
2583 3104
2584 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc)) 3105 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
2585 return Error(SubClassLoc, "could not instantiate def"); 3106 &SubClassLoc))
2586 3107 return true;
2587 // Defs that can be used by other definitions should be fully resolved
2588 // before any use.
2589 if (DefProto->isResolveFirst() && !CurMultiClass) {
2590 CurRec->resolveReferences();
2591 CurRec->setResolveFirst(false);
2592 }
2593 NewRecDefs.push_back(CurRec);
2594 }
2595
2596 3108
2597 if (Lex.getCode() != tgtok::comma) break; 3109 if (Lex.getCode() != tgtok::comma) break;
2598 Lex.Lex(); // eat ','. 3110 Lex.Lex(); // eat ','.
2599 3111
2600 if (Lex.getCode() != tgtok::Id) 3112 if (Lex.getCode() != tgtok::Id)
2620 // Check for error. 3132 // Check for error.
2621 if (!SubClass.Rec) return true; 3133 if (!SubClass.Rec) return true;
2622 3134
2623 // Get the expanded definition prototypes and teach them about 3135 // Get the expanded definition prototypes and teach them about
2624 // the record values the current class to inherit has 3136 // the record values the current class to inherit has
2625 for (Record *CurRec : NewRecDefs) { 3137 for (auto &E : NewEntries) {
2626 // Add it. 3138 // Add it.
2627 if (AddSubClass(CurRec, SubClass)) 3139 if (AddSubClass(E, SubClass))
2628 return true;
2629
2630 if (ApplyLetStack(CurRec))
2631 return true; 3140 return true;
2632 } 3141 }
2633 3142
2634 if (Lex.getCode() != tgtok::comma) break; 3143 if (Lex.getCode() != tgtok::comma) break;
2635 Lex.Lex(); // eat ','. 3144 Lex.Lex(); // eat ','.
2636 SubClass = ParseSubClassReference(nullptr, false); 3145 SubClass = ParseSubClassReference(nullptr, false);
2637 } 3146 }
2638 } 3147 }
2639 3148
2640 if (!CurMultiClass) 3149 for (auto &E : NewEntries) {
2641 for (Record *CurRec : NewRecDefs) 3150 if (ApplyLetStack(E))
2642 // See Record::setName(). This resolve step will see any new 3151 return true;
2643 // name for the def that might have been created when resolving 3152
2644 // inheritance, values and arguments above. 3153 addEntry(std::move(E));
2645 CurRec->resolveReferences(); 3154 }
2646 3155
2647 if (Lex.getCode() != tgtok::semi) 3156 if (Lex.getCode() != tgtok::semi)
2648 return TokError("expected ';' at end of defm"); 3157 return TokError("expected ';' at end of defm");
2649 Lex.Lex(); 3158 Lex.Lex();
2650 3159
2659 /// Object ::= LETCommand '{' ObjectList '}' 3168 /// Object ::= LETCommand '{' ObjectList '}'
2660 /// Object ::= LETCommand Object 3169 /// Object ::= LETCommand Object
2661 bool TGParser::ParseObject(MultiClass *MC) { 3170 bool TGParser::ParseObject(MultiClass *MC) {
2662 switch (Lex.getCode()) { 3171 switch (Lex.getCode()) {
2663 default: 3172 default:
2664 return TokError("Expected class, def, defm, multiclass or let definition"); 3173 return TokError("Expected class, def, defm, defset, multiclass, let or "
3174 "foreach");
2665 case tgtok::Let: return ParseTopLevelLet(MC); 3175 case tgtok::Let: return ParseTopLevelLet(MC);
2666 case tgtok::Def: return ParseDef(MC); 3176 case tgtok::Def: return ParseDef(MC);
2667 case tgtok::Foreach: return ParseForeach(MC); 3177 case tgtok::Foreach: return ParseForeach(MC);
2668 case tgtok::Defm: return ParseDefm(MC); 3178 case tgtok::Defm: return ParseDefm(MC);
2669 case tgtok::Class: return ParseClass(); 3179 case tgtok::Defset:
2670 case tgtok::MultiClass: return ParseMultiClass(); 3180 if (MC)
3181 return TokError("defset is not allowed inside multiclass");
3182 return ParseDefset();
3183 case tgtok::Class:
3184 if (MC)
3185 return TokError("class is not allowed inside multiclass");
3186 if (!Loops.empty())
3187 return TokError("class is not allowed inside foreach loop");
3188 return ParseClass();
3189 case tgtok::MultiClass:
3190 if (!Loops.empty())
3191 return TokError("multiclass is not allowed inside foreach loop");
3192 return ParseMultiClass();
2671 } 3193 }
2672 } 3194 }
2673 3195
2674 /// ParseObjectList 3196 /// ParseObjectList
2675 /// ObjectList :== Object* 3197 /// ObjectList :== Object*
2689 if (Lex.getCode() == tgtok::Eof) 3211 if (Lex.getCode() == tgtok::Eof)
2690 return false; 3212 return false;
2691 3213
2692 return TokError("Unexpected input at top level"); 3214 return TokError("Unexpected input at top level");
2693 } 3215 }
3216
3217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3218 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3219 if (Loop)
3220 Loop->dump();
3221 if (Rec)
3222 Rec->dump();
3223 }
3224
3225 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3226 errs() << "foreach " << IterVar->getAsString() << " = "
3227 << ListValue->getAsString() << " in {\n";
3228
3229 for (const auto &E : Entries)
3230 E.dump();
3231
3232 errs() << "}\n";
3233 }
3234
3235 LLVM_DUMP_METHOD void MultiClass::dump() const {
3236 errs() << "Record:\n";
3237 Rec.dump();
3238
3239 errs() << "Defs:\n";
3240 for (const auto &E : Entries)
3241 E.dump();
3242 }
3243 #endif