Bug Summary

File:lib/TableGen/TGParser.cpp
Warning:line 2590, column 9
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name TGParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/lib/TableGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp

/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp

1//===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implement the Parser for TableGen.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TGParser.h"
15#include "llvm/ADT/None.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Support/Compiler.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/raw_ostream.h"
23#include "llvm/TableGen/Record.h"
24#include <algorithm>
25#include <cassert>
26#include <cstdint>
27
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
31// Support Code for the Semantic Actions.
32//===----------------------------------------------------------------------===//
33
34namespace llvm {
35
36struct SubClassReference {
37 SMRange RefRange;
38 Record *Rec;
39 SmallVector<Init*, 4> TemplateArgs;
40
41 SubClassReference() : Rec(nullptr) {}
42
43 bool isInvalid() const { return Rec == nullptr; }
44};
45
46struct SubMultiClassReference {
47 SMRange RefRange;
48 MultiClass *MC;
49 SmallVector<Init*, 4> TemplateArgs;
50
51 SubMultiClassReference() : MC(nullptr) {}
52
53 bool isInvalid() const { return MC == nullptr; }
54 void dump() const;
55};
56
57#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SubMultiClassReference::dump() const {
59 errs() << "Multiclass:\n";
60
61 MC->dump();
62
63 errs() << "Template args:\n";
64 for (Init *TA : TemplateArgs)
65 TA->dump();
66}
67#endif
68
69} // end namespace llvm
70
71static 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
90static 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
112bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
113 if (!CurRec)
114 CurRec = &CurMultiClass->Rec;
115
116 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
117 // The value already exists in the class, treat this as a set.
118 if (ERV->setValue(RV.getValue()))
119 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
120 RV.getType()->getAsString() + "' is incompatible with " +
121 "previous definition of type '" +
122 ERV->getType()->getAsString() + "'");
123 } else {
124 CurRec->addValue(RV);
125 }
126 return false;
127}
128
129/// SetValue -
130/// Return true on error, false on success.
131bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
132 ArrayRef<unsigned> BitList, Init *V,
133 bool AllowSelfAssignment) {
134 if (!V) return false;
135
136 if (!CurRec) CurRec = &CurMultiClass->Rec;
137
138 RecordVal *RV = CurRec->getValue(ValName);
139 if (!RV)
140 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
141 "' unknown!");
142
143 // Do not allow assignments like 'X = X'. This will just cause infinite loops
144 // in the resolution machinery.
145 if (BitList.empty())
146 if (VarInit *VI = dyn_cast<VarInit>(V))
147 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
148 return Error(Loc, "Recursion / self-assignment forbidden");
149
150 // If we are assigning to a subset of the bits in the value... then we must be
151 // assigning to a field of BitsRecTy, which must have a BitsInit
152 // initializer.
153 //
154 if (!BitList.empty()) {
155 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
156 if (!CurVal)
157 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
158 "' is not a bits type");
159
160 // Convert the incoming value to a bits type of the appropriate size...
161 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
162 if (!BI)
163 return Error(Loc, "Initializer is not compatible with bit range");
164
165 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
166
167 // Loop over bits, assigning values as appropriate.
168 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
169 unsigned Bit = BitList[i];
170 if (NewBits[Bit])
171 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
172 ValName->getAsUnquotedString() + "' more than once");
173 NewBits[Bit] = BI->getBit(i);
174 }
175
176 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
177 if (!NewBits[i])
178 NewBits[i] = CurVal->getBit(i);
179
180 V = BitsInit::get(NewBits);
181 }
182
183 if (RV->setValue(V)) {
184 std::string InitType;
185 if (BitsInit *BI = dyn_cast<BitsInit>(V))
186 InitType = (Twine("' of type bit initializer with length ") +
187 Twine(BI->getNumBits())).str();
188 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
189 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
190 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
191 "' of type '" + RV->getType()->getAsString() +
192 "' is incompatible with initializer '" +
193 V->getAsString() + InitType + "'");
194 }
195 return false;
196}
197
198/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
199/// args as SubClass's template arguments.
200bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
201 Record *SC = SubClass.Rec;
202 // Add all of the values in the subclass into the current class.
203 for (const RecordVal &Val : SC->getValues())
204 if (AddValue(CurRec, SubClass.RefRange.Start, Val))
205 return true;
206
207 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
208
209 // Ensure that an appropriate number of template arguments are specified.
210 if (TArgs.size() < SubClass.TemplateArgs.size())
211 return Error(SubClass.RefRange.Start,
212 "More template args specified than expected");
213
214 // Loop over all of the template arguments, setting them to the specified
215 // value or leaving them as the default if necessary.
216 MapResolver R(CurRec);
217
218 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
219 if (i < SubClass.TemplateArgs.size()) {
220 // If a value is specified for this template arg, set it now.
221 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
222 None, SubClass.TemplateArgs[i]))
223 return true;
224 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
225 return Error(SubClass.RefRange.Start,
226 "Value not specified for template argument #" +
227 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
228 ") of subclass '" + SC->getNameInitAsString() + "'!");
229 }
230
231 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
232
233 CurRec->removeValue(TArgs[i]);
234 }
235
236 CurRec->resolveReferences(R);
237
238 // Since everything went well, we can now set the "superclass" list for the
239 // current record.
240 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
241 for (const auto &SCPair : SCs) {
242 if (CurRec->isSubClassOf(SCPair.first))
243 return Error(SubClass.RefRange.Start,
244 "Already subclass of '" + SCPair.first->getName() + "'!\n");
245 CurRec->addSuperClass(SCPair.first, SCPair.second);
246 }
247
248 if (CurRec->isSubClassOf(SC))
249 return Error(SubClass.RefRange.Start,
250 "Already subclass of '" + SC->getName() + "'!\n");
251 CurRec->addSuperClass(SC, SubClass.RefRange);
252 return false;
253}
254
255/// AddSubMultiClass - Add SubMultiClass as a subclass to
256/// CurMC, resolving its template args as SubMultiClass's
257/// template arguments.
258bool TGParser::AddSubMultiClass(MultiClass *CurMC,
259 SubMultiClassReference &SubMultiClass) {
260 MultiClass *SMC = SubMultiClass.MC;
261 Record *CurRec = &CurMC->Rec;
262
263 // Add all of the values in the subclass into the current class.
264 for (const auto &SMCVal : SMC->Rec.getValues())
265 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
266 return true;
267
268 unsigned newDefStart = CurMC->DefPrototypes.size();
269
270 // Add all of the defs in the subclass into the current multiclass.
271 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
272 // Clone the def and add it to the current multiclass
273 auto NewDef = make_unique<Record>(*R);
274
275 // Add all of the values in the superclass into the current def.
276 for (const auto &MCVal : CurRec->getValues())
277 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
278 return true;
279
280 CurMC->DefPrototypes.push_back(std::move(NewDef));
281 }
282
283 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
284
285 // Ensure that an appropriate number of template arguments are
286 // specified.
287 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
288 return Error(SubMultiClass.RefRange.Start,
289 "More template args specified than expected");
290
291 // Loop over all of the template arguments, setting them to the specified
292 // value or leaving them as the default if necessary.
293 MapResolver CurRecResolver(CurRec);
294
295 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
296 if (i < SubMultiClass.TemplateArgs.size()) {
297 // If a value is specified for this template arg, set it in the
298 // superclass now.
299 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
300 None, SubMultiClass.TemplateArgs[i]))
301 return true;
302
303 // If a value is specified for this template arg, set it in the
304 // new defs now.
305 for (const auto &Def :
306 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
307 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
308 None, SubMultiClass.TemplateArgs[i]))
309 return true;
310 }
311 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
312 return Error(SubMultiClass.RefRange.Start,
313 "Value not specified for template argument #" +
314 Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
315 ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
316 }
317
318 CurRecResolver.set(SMCTArgs[i], CurRec->getValue(SMCTArgs[i])->getValue());
319
320 CurRec->removeValue(SMCTArgs[i]);
321 }
322
323 CurRec->resolveReferences(CurRecResolver);
324
325 for (const auto &Def :
326 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
327 MapResolver R(Def.get());
328
329 for (Init *SMCTArg : SMCTArgs) {
330 R.set(SMCTArg, Def->getValue(SMCTArg)->getValue());
331 Def->removeValue(SMCTArg);
332 }
333
334 Def->resolveReferences(R);
335 }
336
337 return false;
338}
339
340/// Add a record that results from 'def' or 'defm', after template arguments
341/// and the external let stack have been resolved.
342///
343/// Apply foreach loops, resolve internal variable references, and add to the
344/// current multi class or the global record keeper as appropriate.
345bool TGParser::addDef(std::unique_ptr<Record> Rec, Init *DefmName) {
346 IterSet IterVals;
347
348 if (Loops.empty())
349 return addDefOne(std::move(Rec), DefmName, IterVals);
350
351 return addDefForeach(Rec.get(), DefmName, IterVals);
352}
353
354/// Recursive helper function for addDef/addDefOne to resolve references to
355/// foreach variables.
356bool TGParser::addDefForeach(Record *Rec, Init *DefmName, IterSet &IterVals) {
357 if (IterVals.size() != Loops.size()) {
358 assert(IterVals.size() < Loops.size())(static_cast <bool> (IterVals.size() < Loops.size())
? void (0) : __assert_fail ("IterVals.size() < Loops.size()"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 358, __extension__ __PRETTY_FUNCTION__))
;
359 ForeachLoop &CurLoop = Loops[IterVals.size()];
360 ListInit *List = CurLoop.ListValue;
361
362 // Process each value.
363 for (unsigned i = 0; i < List->size(); ++i) {
364 IterVals.push_back(IterRecord(CurLoop.IterVar, List->getElement(i)));
365 if (addDefForeach(Rec, DefmName, IterVals))
366 return true;
367 IterVals.pop_back();
368 }
369 return false;
370 }
371
372 // This is the bottom of the recursion. We have all of the iterator values
373 // for this point in the iteration space. Instantiate a new record to
374 // reflect this combination of values.
375 auto IterRec = make_unique<Record>(*Rec);
376 return addDefOne(std::move(IterRec), DefmName, IterVals);
377}
378
379/// After resolving foreach loops, add the record as a prototype to the
380/// current multiclass, or resolve fully and add to the record keeper.
381bool TGParser::addDefOne(std::unique_ptr<Record> Rec, Init *DefmName,
382 IterSet &IterVals) {
383 MapResolver R(Rec.get());
384
385 for (IterRecord &IR : IterVals)
386 R.set(IR.IterVar->getNameInit(), IR.IterValue);
387
388 Rec->resolveReferences(R);
389
390 if (CurMultiClass) {
391 for (const auto &Proto : CurMultiClass->DefPrototypes) {
392 if (Proto->getNameInit() == Rec->getNameInit()) {
393 if (!Rec->isAnonymous()) {
394 PrintError(Rec->getLoc(),
395 Twine("def '") + Rec->getNameInitAsString() +
396 "' already defined in this multiclass!");
397 PrintNote(Proto->getLoc(), "location of previous definition");
398 return true;
399 }
400 Rec->setName(Records.getNewAnonymousName());
401 break;
402 }
403 }
404 CurMultiClass->DefPrototypes.emplace_back(std::move(Rec));
405 return false;
406 }
407
408 // Name construction is an incoherent mess. Unfortunately, existing .td
409 // files rely on pretty much all the quirks and implementation details of
410 // this.
411 if (DefmName) {
412 MapResolver R(Rec.get());
413 R.set(StringInit::get("NAME"), DefmName);
414 Rec->resolveReferences(R);
415 }
416
417 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
418 if (!Rec->isAnonymous()) {
419 PrintError(Rec->getLoc(),
420 "def already exists: " + Rec->getNameInitAsString());
421 PrintNote(Prev->getLoc(), "location of previous definition");
422 return true;
423 }
424 Rec->setName(Records.getNewAnonymousName());
425 }
426
427 Rec->resolveReferences();
428 checkConcrete(*Rec);
429
430 // If ObjectBody has template arguments, it's an error.
431 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?")(static_cast <bool> (Rec->getTemplateArgs().empty() &&
"How'd this get template args?") ? void (0) : __assert_fail (
"Rec->getTemplateArgs().empty() && \"How'd this get template args?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 431, __extension__ __PRETTY_FUNCTION__))
;
432
433 for (DefsetRecord *Defset : Defsets) {
434 DefInit *I = Rec->getDefInit();
435 if (!I->getType()->typeIsA(Defset->EltTy)) {
436 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
437 I->getType()->getAsString() +
438 "' to defset");
439 PrintNote(Defset->Loc, "location of defset declaration");
440 return true;
441 }
442 Defset->Elements.push_back(I);
443 }
444
445 Records.addDef(std::move(Rec));
446 return false;
447}
448
449//===----------------------------------------------------------------------===//
450// Parser Code
451//===----------------------------------------------------------------------===//
452
453/// isObjectStart - Return true if this is a valid first token for an Object.
454static bool isObjectStart(tgtok::TokKind K) {
455 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
456 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
457 K == tgtok::Defset;
458}
459
460/// ParseObjectName - If a valid object name is specified, return it. If no
461/// name is specified, return the unset initializer. Return nullptr on parse
462/// error.
463/// ObjectName ::= Value [ '#' Value ]*
464/// ObjectName ::= /*empty*/
465///
466Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
467 switch (Lex.getCode()) {
468 case tgtok::colon:
469 case tgtok::semi:
470 case tgtok::l_brace:
471 // These are all of the tokens that can begin an object body.
472 // Some of these can also begin values but we disallow those cases
473 // because they are unlikely to be useful.
474 return UnsetInit::get();
475 default:
476 break;
477 }
478
479 Record *CurRec = nullptr;
480 if (CurMultiClass)
481 CurRec = &CurMultiClass->Rec;
482
483 return ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
484}
485
486/// ParseClassID - Parse and resolve a reference to a class name. This returns
487/// null on error.
488///
489/// ClassID ::= ID
490///
491Record *TGParser::ParseClassID() {
492 if (Lex.getCode() != tgtok::Id) {
493 TokError("expected name for ClassID");
494 return nullptr;
495 }
496
497 Record *Result = Records.getClass(Lex.getCurStrVal());
498 if (!Result)
499 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
500
501 Lex.Lex();
502 return Result;
503}
504
505/// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
506/// This returns null on error.
507///
508/// MultiClassID ::= ID
509///
510MultiClass *TGParser::ParseMultiClassID() {
511 if (Lex.getCode() != tgtok::Id) {
512 TokError("expected name for MultiClassID");
513 return nullptr;
514 }
515
516 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
517 if (!Result)
518 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
519
520 Lex.Lex();
521 return Result;
522}
523
524/// ParseSubClassReference - Parse a reference to a subclass or to a templated
525/// subclass. This returns a SubClassRefTy with a null Record* on error.
526///
527/// SubClassRef ::= ClassID
528/// SubClassRef ::= ClassID '<' ValueList '>'
529///
530SubClassReference TGParser::
531ParseSubClassReference(Record *CurRec, bool isDefm) {
532 SubClassReference Result;
533 Result.RefRange.Start = Lex.getLoc();
534
535 if (isDefm) {
536 if (MultiClass *MC = ParseMultiClassID())
537 Result.Rec = &MC->Rec;
538 } else {
539 Result.Rec = ParseClassID();
540 }
541 if (!Result.Rec) return Result;
542
543 // If there is no template arg list, we're done.
544 if (Lex.getCode() != tgtok::less) {
545 Result.RefRange.End = Lex.getLoc();
546 return Result;
547 }
548 Lex.Lex(); // Eat the '<'
549
550 if (Lex.getCode() == tgtok::greater) {
551 TokError("subclass reference requires a non-empty list of template values");
552 Result.Rec = nullptr;
553 return Result;
554 }
555
556 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
557 if (Result.TemplateArgs.empty()) {
558 Result.Rec = nullptr; // Error parsing value list.
559 return Result;
560 }
561
562 if (Lex.getCode() != tgtok::greater) {
563 TokError("expected '>' in template value list");
564 Result.Rec = nullptr;
565 return Result;
566 }
567 Lex.Lex();
568 Result.RefRange.End = Lex.getLoc();
569
570 return Result;
571}
572
573/// ParseSubMultiClassReference - Parse a reference to a subclass or to a
574/// templated submulticlass. This returns a SubMultiClassRefTy with a null
575/// Record* on error.
576///
577/// SubMultiClassRef ::= MultiClassID
578/// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
579///
580SubMultiClassReference TGParser::
581ParseSubMultiClassReference(MultiClass *CurMC) {
582 SubMultiClassReference Result;
583 Result.RefRange.Start = Lex.getLoc();
584
585 Result.MC = ParseMultiClassID();
586 if (!Result.MC) return Result;
587
588 // If there is no template arg list, we're done.
589 if (Lex.getCode() != tgtok::less) {
590 Result.RefRange.End = Lex.getLoc();
591 return Result;
592 }
593 Lex.Lex(); // Eat the '<'
594
595 if (Lex.getCode() == tgtok::greater) {
596 TokError("subclass reference requires a non-empty list of template values");
597 Result.MC = nullptr;
598 return Result;
599 }
600
601 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
602 if (Result.TemplateArgs.empty()) {
603 Result.MC = nullptr; // Error parsing value list.
604 return Result;
605 }
606
607 if (Lex.getCode() != tgtok::greater) {
608 TokError("expected '>' in template value list");
609 Result.MC = nullptr;
610 return Result;
611 }
612 Lex.Lex();
613 Result.RefRange.End = Lex.getLoc();
614
615 return Result;
616}
617
618/// ParseRangePiece - Parse a bit/value range.
619/// RangePiece ::= INTVAL
620/// RangePiece ::= INTVAL '-' INTVAL
621/// RangePiece ::= INTVAL INTVAL
622bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges) {
623 if (Lex.getCode() != tgtok::IntVal) {
624 TokError("expected integer or bitrange");
625 return true;
626 }
627 int64_t Start = Lex.getCurIntVal();
628 int64_t End;
629
630 if (Start < 0)
631 return TokError("invalid range, cannot be negative");
632
633 switch (Lex.Lex()) { // eat first character.
634 default:
635 Ranges.push_back(Start);
636 return false;
637 case tgtok::minus:
638 if (Lex.Lex() != tgtok::IntVal) {
639 TokError("expected integer value as end of range");
640 return true;
641 }
642 End = Lex.getCurIntVal();
643 break;
644 case tgtok::IntVal:
645 End = -Lex.getCurIntVal();
646 break;
647 }
648 if (End < 0)
649 return TokError("invalid range, cannot be negative");
650 Lex.Lex();
651
652 // Add to the range.
653 if (Start < End)
654 for (; Start <= End; ++Start)
655 Ranges.push_back(Start);
656 else
657 for (; Start >= End; --Start)
658 Ranges.push_back(Start);
659 return false;
660}
661
662/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
663///
664/// RangeList ::= RangePiece (',' RangePiece)*
665///
666void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
667 // Parse the first piece.
668 if (ParseRangePiece(Result)) {
669 Result.clear();
670 return;
671 }
672 while (Lex.getCode() == tgtok::comma) {
673 Lex.Lex(); // Eat the comma.
674
675 // Parse the next range piece.
676 if (ParseRangePiece(Result)) {
677 Result.clear();
678 return;
679 }
680 }
681}
682
683/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
684/// OptionalRangeList ::= '<' RangeList '>'
685/// OptionalRangeList ::= /*empty*/
686bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
687 if (Lex.getCode() != tgtok::less)
688 return false;
689
690 SMLoc StartLoc = Lex.getLoc();
691 Lex.Lex(); // eat the '<'
692
693 // Parse the range list.
694 ParseRangeList(Ranges);
695 if (Ranges.empty()) return true;
696
697 if (Lex.getCode() != tgtok::greater) {
698 TokError("expected '>' at end of range list");
699 return Error(StartLoc, "to match this '<'");
700 }
701 Lex.Lex(); // eat the '>'.
702 return false;
703}
704
705/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
706/// OptionalBitList ::= '{' RangeList '}'
707/// OptionalBitList ::= /*empty*/
708bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
709 if (Lex.getCode() != tgtok::l_brace)
710 return false;
711
712 SMLoc StartLoc = Lex.getLoc();
713 Lex.Lex(); // eat the '{'
714
715 // Parse the range list.
716 ParseRangeList(Ranges);
717 if (Ranges.empty()) return true;
718
719 if (Lex.getCode() != tgtok::r_brace) {
720 TokError("expected '}' at end of bit list");
721 return Error(StartLoc, "to match this '{'");
722 }
723 Lex.Lex(); // eat the '}'.
724 return false;
725}
726
727/// ParseType - Parse and return a tblgen type. This returns null on error.
728///
729/// Type ::= STRING // string type
730/// Type ::= CODE // code type
731/// Type ::= BIT // bit type
732/// Type ::= BITS '<' INTVAL '>' // bits<x> type
733/// Type ::= INT // int type
734/// Type ::= LIST '<' Type '>' // list<x> type
735/// Type ::= DAG // dag type
736/// Type ::= ClassID // Record Type
737///
738RecTy *TGParser::ParseType() {
739 switch (Lex.getCode()) {
740 default: TokError("Unknown token when expecting a type"); return nullptr;
741 case tgtok::String: Lex.Lex(); return StringRecTy::get();
742 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
743 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
744 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
745 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
746 case tgtok::Id:
747 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
748 TokError("unknown class name");
749 return nullptr;
750 case tgtok::Bits: {
751 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
752 TokError("expected '<' after bits type");
753 return nullptr;
754 }
755 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
756 TokError("expected integer in bits<n> type");
757 return nullptr;
758 }
759 uint64_t Val = Lex.getCurIntVal();
760 if (Lex.Lex() != tgtok::greater) { // Eat count.
761 TokError("expected '>' at end of bits<n> type");
762 return nullptr;
763 }
764 Lex.Lex(); // Eat '>'
765 return BitsRecTy::get(Val);
766 }
767 case tgtok::List: {
768 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
769 TokError("expected '<' after list type");
770 return nullptr;
771 }
772 Lex.Lex(); // Eat '<'
773 RecTy *SubType = ParseType();
774 if (!SubType) return nullptr;
775
776 if (Lex.getCode() != tgtok::greater) {
777 TokError("expected '>' at end of list<ty> type");
778 return nullptr;
779 }
780 Lex.Lex(); // Eat '>'
781 return ListRecTy::get(SubType);
782 }
783 }
784}
785
786/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
787/// has already been read.
788Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
789 IDParseMode Mode) {
790 if (CurRec) {
791 if (const RecordVal *RV = CurRec->getValue(Name))
792 return VarInit::get(Name, RV->getType());
793
794 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
795
796 if (CurMultiClass)
797 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
798 "::");
799
800 if (CurRec->isTemplateArg(TemplateArgName)) {
801 const RecordVal *RV = CurRec->getValue(TemplateArgName);
802 assert(RV && "Template arg doesn't exist??")(static_cast <bool> (RV && "Template arg doesn't exist??"
) ? void (0) : __assert_fail ("RV && \"Template arg doesn't exist??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 802, __extension__ __PRETTY_FUNCTION__))
;
803 return VarInit::get(TemplateArgName, RV->getType());
804 }
805 }
806
807 if (CurMultiClass) {
808 if (Name->getValue() == "NAME")
809 return VarInit::get(Name, StringRecTy::get());
810
811 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
812
813 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
814 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
815 assert(RV && "Template arg doesn't exist??")(static_cast <bool> (RV && "Template arg doesn't exist??"
) ? void (0) : __assert_fail ("RV && \"Template arg doesn't exist??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 815, __extension__ __PRETTY_FUNCTION__))
;
816 return VarInit::get(MCName, RV->getType());
817 }
818 }
819
820 // If this is in a foreach loop, make sure it's not a loop iterator
821 for (const auto &L : Loops) {
822 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
823 if (IterVar && IterVar->getNameInit() == Name)
824 return IterVar;
825 }
826
827 if (Mode == ParseNameMode)
828 return Name;
829
830 if (Init *I = Records.getGlobal(Name->getValue()))
831 return I;
832
833 // Allow self-references of concrete defs, but delay the lookup so that we
834 // get the correct type.
835 if (CurRec && !CurMultiClass && CurRec->getNameInit() == Name)
836 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
837
838 if (Mode == ParseValueMode) {
839 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
840 return nullptr;
841 }
842
843 return Name;
844}
845
846/// ParseOperation - Parse an operator. This returns null on error.
847///
848/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
849///
850Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
851 switch (Lex.getCode()) {
852 default:
853 TokError("unknown operation");
854 return nullptr;
855 case tgtok::XHead:
856 case tgtok::XTail:
857 case tgtok::XSize:
858 case tgtok::XEmpty:
859 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
860 UnOpInit::UnaryOp Code;
861 RecTy *Type = nullptr;
862
863 switch (Lex.getCode()) {
864 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 864)
;
865 case tgtok::XCast:
866 Lex.Lex(); // eat the operation
867 Code = UnOpInit::CAST;
868
869 Type = ParseOperatorType();
870
871 if (!Type) {
872 TokError("did not get type for unary operator");
873 return nullptr;
874 }
875
876 break;
877 case tgtok::XHead:
878 Lex.Lex(); // eat the operation
879 Code = UnOpInit::HEAD;
880 break;
881 case tgtok::XTail:
882 Lex.Lex(); // eat the operation
883 Code = UnOpInit::TAIL;
884 break;
885 case tgtok::XSize:
886 Lex.Lex();
887 Code = UnOpInit::SIZE;
888 Type = IntRecTy::get();
889 break;
890 case tgtok::XEmpty:
891 Lex.Lex(); // eat the operation
892 Code = UnOpInit::EMPTY;
893 Type = IntRecTy::get();
894 break;
895 }
896 if (Lex.getCode() != tgtok::l_paren) {
897 TokError("expected '(' after unary operator");
898 return nullptr;
899 }
900 Lex.Lex(); // eat the '('
901
902 Init *LHS = ParseValue(CurRec);
903 if (!LHS) return nullptr;
904
905 if (Code == UnOpInit::HEAD ||
906 Code == UnOpInit::TAIL ||
907 Code == UnOpInit::EMPTY) {
908 ListInit *LHSl = dyn_cast<ListInit>(LHS);
909 StringInit *LHSs = dyn_cast<StringInit>(LHS);
910 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
911 if (!LHSl && !LHSs && !LHSt) {
912 TokError("expected list or string type argument in unary operator");
913 return nullptr;
914 }
915 if (LHSt) {
916 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
917 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
918 if (!LType && !SType) {
919 TokError("expected list or string type argument in unary operator");
920 return nullptr;
921 }
922 }
923
924 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
925 Code == UnOpInit::SIZE) {
926 if (!LHSl && !LHSt) {
927 TokError("expected list type argument in unary operator");
928 return nullptr;
929 }
930 }
931
932 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
933 if (LHSl && LHSl->empty()) {
934 TokError("empty list argument in unary operator");
935 return nullptr;
936 }
937 if (LHSl) {
938 Init *Item = LHSl->getElement(0);
939 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
940 if (!Itemt) {
941 TokError("untyped list element in unary operator");
942 return nullptr;
943 }
944 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
945 : ListRecTy::get(Itemt->getType());
946 } else {
947 assert(LHSt && "expected list type argument in unary operator")(static_cast <bool> (LHSt && "expected list type argument in unary operator"
) ? void (0) : __assert_fail ("LHSt && \"expected list type argument in unary operator\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 947, __extension__ __PRETTY_FUNCTION__))
;
948 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
949 if (!LType) {
950 TokError("expected list type argument in unary operator");
951 return nullptr;
952 }
953 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
954 }
955 }
956 }
957
958 if (Lex.getCode() != tgtok::r_paren) {
959 TokError("expected ')' in unary operator");
960 return nullptr;
961 }
962 Lex.Lex(); // eat the ')'
963 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
964 }
965
966 case tgtok::XIsA: {
967 // Value ::= !isa '<' Type '>' '(' Value ')'
968 Lex.Lex(); // eat the operation
969
970 RecTy *Type = ParseOperatorType();
971 if (!Type)
972 return nullptr;
973
974 if (Lex.getCode() != tgtok::l_paren) {
975 TokError("expected '(' after type of !isa");
976 return nullptr;
977 }
978 Lex.Lex(); // eat the '('
979
980 Init *LHS = ParseValue(CurRec);
981 if (!LHS)
982 return nullptr;
983
984 if (Lex.getCode() != tgtok::r_paren) {
985 TokError("expected ')' in !isa");
986 return nullptr;
987 }
988 Lex.Lex(); // eat the ')'
989
990 return (IsAOpInit::get(Type, LHS))->Fold();
991 }
992
993 case tgtok::XConcat:
994 case tgtok::XADD:
995 case tgtok::XAND:
996 case tgtok::XOR:
997 case tgtok::XSRA:
998 case tgtok::XSRL:
999 case tgtok::XSHL:
1000 case tgtok::XEq:
1001 case tgtok::XNe:
1002 case tgtok::XLe:
1003 case tgtok::XLt:
1004 case tgtok::XGe:
1005 case tgtok::XGt:
1006 case tgtok::XListConcat:
1007 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
1008 tgtok::TokKind OpTok = Lex.getCode();
1009 SMLoc OpLoc = Lex.getLoc();
1010 Lex.Lex(); // eat the operation
1011
1012 BinOpInit::BinaryOp Code;
1013 switch (OpTok) {
1014 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 1014)
;
1015 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1016 case tgtok::XADD: Code = BinOpInit::ADD; break;
1017 case tgtok::XAND: Code = BinOpInit::AND; break;
1018 case tgtok::XOR: Code = BinOpInit::OR; break;
1019 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1020 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1021 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1022 case tgtok::XEq: Code = BinOpInit::EQ; break;
1023 case tgtok::XNe: Code = BinOpInit::NE; break;
1024 case tgtok::XLe: Code = BinOpInit::LE; break;
1025 case tgtok::XLt: Code = BinOpInit::LT; break;
1026 case tgtok::XGe: Code = BinOpInit::GE; break;
1027 case tgtok::XGt: Code = BinOpInit::GT; break;
1028 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1029 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1030 }
1031
1032 RecTy *Type = nullptr;
1033 RecTy *ArgType = nullptr;
1034 switch (OpTok) {
1035 default:
1036 llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 1036)
;
1037 case tgtok::XConcat:
1038 Type = DagRecTy::get();
1039 ArgType = DagRecTy::get();
1040 break;
1041 case tgtok::XAND:
1042 case tgtok::XOR:
1043 case tgtok::XSRA:
1044 case tgtok::XSRL:
1045 case tgtok::XSHL:
1046 case tgtok::XADD:
1047 Type = IntRecTy::get();
1048 ArgType = IntRecTy::get();
1049 break;
1050 case tgtok::XEq:
1051 case tgtok::XNe:
1052 Type = BitRecTy::get();
1053 // ArgType for Eq / Ne is not known at this point
1054 break;
1055 case tgtok::XLe:
1056 case tgtok::XLt:
1057 case tgtok::XGe:
1058 case tgtok::XGt:
1059 Type = BitRecTy::get();
1060 ArgType = IntRecTy::get();
1061 break;
1062 case tgtok::XListConcat:
1063 // We don't know the list type until we parse the first argument
1064 ArgType = ItemType;
1065 break;
1066 case tgtok::XStrConcat:
1067 Type = StringRecTy::get();
1068 ArgType = StringRecTy::get();
1069 break;
1070 }
1071
1072 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1073 Error(OpLoc, Twine("expected value of type '") +
1074 ItemType->getAsString() + "', got '" +
1075 Type->getAsString() + "'");
1076 return nullptr;
1077 }
1078
1079 if (Lex.getCode() != tgtok::l_paren) {
1080 TokError("expected '(' after binary operator");
1081 return nullptr;
1082 }
1083 Lex.Lex(); // eat the '('
1084
1085 SmallVector<Init*, 2> InitList;
1086
1087 for (;;) {
1088 SMLoc InitLoc = Lex.getLoc();
1089 InitList.push_back(ParseValue(CurRec, ArgType));
1090 if (!InitList.back()) return nullptr;
1091
1092 // All BinOps require their arguments to be of compatible types.
1093 TypedInit *TI = dyn_cast<TypedInit>(InitList.back());
1094 if (!ArgType) {
1095 ArgType = TI->getType();
1096
1097 switch (Code) {
1098 case BinOpInit::LISTCONCAT:
1099 if (!isa<ListRecTy>(ArgType)) {
1100 Error(InitLoc, Twine("expected a list, got value of type '") +
1101 ArgType->getAsString() + "'");
1102 return nullptr;
1103 }
1104 break;
1105 case BinOpInit::EQ:
1106 case BinOpInit::NE:
1107 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1108 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1109 Error(InitLoc, Twine("expected int, bits, or string; got value of "
1110 "type '") + ArgType->getAsString() + "'");
1111 return nullptr;
1112 }
1113 break;
1114 default: llvm_unreachable("other ops have fixed argument types")::llvm::llvm_unreachable_internal("other ops have fixed argument types"
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 1114)
;
1115 }
1116 } else {
1117 RecTy *Resolved = resolveTypes(ArgType, TI->getType());
1118 if (!Resolved) {
1119 Error(InitLoc, Twine("expected value of type '") +
1120 ArgType->getAsString() + "', got '" +
1121 TI->getType()->getAsString() + "'");
1122 return nullptr;
1123 }
1124 if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1125 Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1126 Code != BinOpInit::SRL && Code != BinOpInit::SHL)
1127 ArgType = Resolved;
1128 }
1129
1130 if (Lex.getCode() != tgtok::comma)
1131 break;
1132 Lex.Lex(); // eat the ','
1133 }
1134
1135 if (Lex.getCode() != tgtok::r_paren) {
1136 TokError("expected ')' in operator");
1137 return nullptr;
1138 }
1139 Lex.Lex(); // eat the ')'
1140
1141 if (Code == BinOpInit::LISTCONCAT)
1142 Type = ArgType;
1143
1144 // We allow multiple operands to associative operators like !strconcat as
1145 // shorthand for nesting them.
1146 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1147 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1148 Code == BinOpInit::AND || Code == BinOpInit::OR) {
1149 while (InitList.size() > 2) {
1150 Init *RHS = InitList.pop_back_val();
1151 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1152 InitList.back() = RHS;
1153 }
1154 }
1155
1156 if (InitList.size() == 2)
1157 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1158 ->Fold(CurRec);
1159
1160 Error(OpLoc, "expected two operands to operator");
1161 return nullptr;
1162 }
1163
1164 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1165 SMLoc OpLoc = Lex.getLoc();
1166 Lex.Lex(); // eat the operation
1167 if (Lex.getCode() != tgtok::l_paren) {
1168 TokError("expected '(' after !foreach");
1169 return nullptr;
1170 }
1171
1172 if (Lex.Lex() != tgtok::Id) { // eat the '('
1173 TokError("first argument of !foreach must be an identifier");
1174 return nullptr;
1175 }
1176
1177 Init *LHS = StringInit::get(Lex.getCurStrVal());
1178
1179 if (CurRec->getValue(LHS)) {
1180 TokError((Twine("iteration variable '") + LHS->getAsString() +
1181 "' already defined")
1182 .str());
1183 return nullptr;
1184 }
1185
1186 if (Lex.Lex() != tgtok::comma) { // eat the id
1187 TokError("expected ',' in ternary operator");
1188 return nullptr;
1189 }
1190 Lex.Lex(); // eat the ','
1191
1192 Init *MHS = ParseValue(CurRec);
1193 if (!MHS)
1194 return nullptr;
1195
1196 if (Lex.getCode() != tgtok::comma) {
1197 TokError("expected ',' in ternary operator");
1198 return nullptr;
1199 }
1200 Lex.Lex(); // eat the ','
1201
1202 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1203 if (!MHSt) {
1204 TokError("could not get type of !foreach input");
1205 return nullptr;
1206 }
1207
1208 RecTy *InEltType = nullptr;
1209 RecTy *OutEltType = nullptr;
1210 bool IsDAG = false;
1211
1212 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1213 InEltType = InListTy->getElementType();
1214 if (ItemType) {
1215 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1216 OutEltType = OutListTy->getElementType();
1217 } else {
1218 Error(OpLoc,
1219 "expected value of type '" + Twine(ItemType->getAsString()) +
1220 "', but got !foreach of list type");
1221 return nullptr;
1222 }
1223 }
1224 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1225 InEltType = InDagTy;
1226 if (ItemType && !isa<DagRecTy>(ItemType)) {
1227 Error(OpLoc,
1228 "expected value of type '" + Twine(ItemType->getAsString()) +
1229 "', but got !foreach of dag type");
1230 return nullptr;
1231 }
1232 IsDAG = true;
1233 } else {
1234 TokError("!foreach must have list or dag input");
1235 return nullptr;
1236 }
1237
1238 CurRec->addValue(RecordVal(LHS, InEltType, false));
1239 Init *RHS = ParseValue(CurRec, OutEltType);
1240 CurRec->removeValue(LHS);
1241 if (!RHS)
1242 return nullptr;
1243
1244 if (Lex.getCode() != tgtok::r_paren) {
1245 TokError("expected ')' in binary operator");
1246 return nullptr;
1247 }
1248 Lex.Lex(); // eat the ')'
1249
1250 RecTy *OutType;
1251 if (IsDAG) {
1252 OutType = InEltType;
1253 } else {
1254 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1255 if (!RHSt) {
1256 TokError("could not get type of !foreach result");
1257 return nullptr;
1258 }
1259 OutType = RHSt->getType()->getListTy();
1260 }
1261
1262 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1263 ->Fold(CurRec);
1264 }
1265
1266 case tgtok::XDag:
1267 case tgtok::XIf:
1268 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1269 TernOpInit::TernaryOp Code;
1270 RecTy *Type = nullptr;
1271
1272 tgtok::TokKind LexCode = Lex.getCode();
1273 Lex.Lex(); // eat the operation
1274 switch (LexCode) {
1275 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 1275)
;
1276 case tgtok::XDag:
1277 Code = TernOpInit::DAG;
1278 Type = DagRecTy::get();
1279 ItemType = nullptr;
1280 break;
1281 case tgtok::XIf:
1282 Code = TernOpInit::IF;
1283 break;
1284 case tgtok::XSubst:
1285 Code = TernOpInit::SUBST;
1286 break;
1287 }
1288 if (Lex.getCode() != tgtok::l_paren) {
1289 TokError("expected '(' after ternary operator");
1290 return nullptr;
1291 }
1292 Lex.Lex(); // eat the '('
1293
1294 Init *LHS = ParseValue(CurRec);
1295 if (!LHS) return nullptr;
1296
1297 if (Lex.getCode() != tgtok::comma) {
1298 TokError("expected ',' in ternary operator");
1299 return nullptr;
1300 }
1301 Lex.Lex(); // eat the ','
1302
1303 SMLoc MHSLoc = Lex.getLoc();
1304 Init *MHS = ParseValue(CurRec, ItemType);
1305 if (!MHS)
1306 return nullptr;
1307
1308 if (Lex.getCode() != tgtok::comma) {
1309 TokError("expected ',' in ternary operator");
1310 return nullptr;
1311 }
1312 Lex.Lex(); // eat the ','
1313
1314 SMLoc RHSLoc = Lex.getLoc();
1315 Init *RHS = ParseValue(CurRec, ItemType);
1316 if (!RHS)
1317 return nullptr;
1318
1319 if (Lex.getCode() != tgtok::r_paren) {
1320 TokError("expected ')' in binary operator");
1321 return nullptr;
1322 }
1323 Lex.Lex(); // eat the ')'
1324
1325 switch (LexCode) {
1326 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 1326)
;
1327 case tgtok::XDag: {
1328 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1329 if (!MHSt && !isa<UnsetInit>(MHS)) {
1330 Error(MHSLoc, "could not determine type of the child list in !dag");
1331 return nullptr;
1332 }
1333 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1334 Error(MHSLoc, Twine("expected list of children, got type '") +
1335 MHSt->getType()->getAsString() + "'");
1336 return nullptr;
1337 }
1338
1339 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1340 if (!RHSt && !isa<UnsetInit>(RHS)) {
1341 Error(RHSLoc, "could not determine type of the name list in !dag");
1342 return nullptr;
1343 }
1344 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1345 Error(RHSLoc, Twine("expected list<string>, got type '") +
1346 RHSt->getType()->getAsString() + "'");
1347 return nullptr;
1348 }
1349
1350 if (!MHSt && !RHSt) {
1351 Error(MHSLoc,
1352 "cannot have both unset children and unset names in !dag");
1353 return nullptr;
1354 }
1355 break;
1356 }
1357 case tgtok::XIf: {
1358 RecTy *MHSTy = nullptr;
1359 RecTy *RHSTy = nullptr;
1360
1361 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1362 MHSTy = MHSt->getType();
1363 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1364 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1365 if (isa<BitInit>(MHS))
1366 MHSTy = BitRecTy::get();
1367
1368 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1369 RHSTy = RHSt->getType();
1370 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1371 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1372 if (isa<BitInit>(RHS))
1373 RHSTy = BitRecTy::get();
1374
1375 // For UnsetInit, it's typed from the other hand.
1376 if (isa<UnsetInit>(MHS))
1377 MHSTy = RHSTy;
1378 if (isa<UnsetInit>(RHS))
1379 RHSTy = MHSTy;
1380
1381 if (!MHSTy || !RHSTy) {
1382 TokError("could not get type for !if");
1383 return nullptr;
1384 }
1385
1386 Type = resolveTypes(MHSTy, RHSTy);
1387 if (!Type) {
1388 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1389 "' and '" + RHSTy->getAsString() + "' for !if");
1390 return nullptr;
1391 }
1392 break;
1393 }
1394 case tgtok::XSubst: {
1395 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1396 if (!RHSt) {
1397 TokError("could not get type for !subst");
1398 return nullptr;
1399 }
1400 Type = RHSt->getType();
1401 break;
1402 }
1403 }
1404 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1405 }
1406
1407 case tgtok::XFoldl: {
1408 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1409 Lex.Lex(); // eat the operation
1410 if (Lex.getCode() != tgtok::l_paren) {
1411 TokError("expected '(' after !foldl");
1412 return nullptr;
1413 }
1414 Lex.Lex(); // eat the '('
1415
1416 Init *StartUntyped = ParseValue(CurRec);
1417 if (!StartUntyped)
1418 return nullptr;
1419
1420 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1421 if (!Start) {
1422 TokError(Twine("could not get type of !foldl start: '") +
1423 StartUntyped->getAsString() + "'");
1424 return nullptr;
1425 }
1426
1427 if (Lex.getCode() != tgtok::comma) {
1428 TokError("expected ',' in !foldl");
1429 return nullptr;
1430 }
1431 Lex.Lex(); // eat the ','
1432
1433 Init *ListUntyped = ParseValue(CurRec);
1434 if (!ListUntyped)
1435 return nullptr;
1436
1437 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1438 if (!List) {
1439 TokError(Twine("could not get type of !foldl list: '") +
1440 ListUntyped->getAsString() + "'");
1441 return nullptr;
1442 }
1443
1444 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1445 if (!ListType) {
1446 TokError(Twine("!foldl list must be a list, but is of type '") +
1447 List->getType()->getAsString());
1448 return nullptr;
1449 }
1450
1451 if (Lex.getCode() != tgtok::comma) {
1452 TokError("expected ',' in !foldl");
1453 return nullptr;
1454 }
1455
1456 if (Lex.Lex() != tgtok::Id) { // eat the ','
1457 TokError("third argument of !foldl must be an identifier");
1458 return nullptr;
1459 }
1460
1461 Init *A = StringInit::get(Lex.getCurStrVal());
1462 if (CurRec->getValue(A)) {
1463 TokError((Twine("left !foldl variable '") + A->getAsString() +
1464 "' already defined")
1465 .str());
1466 return nullptr;
1467 }
1468
1469 if (Lex.Lex() != tgtok::comma) { // eat the id
1470 TokError("expected ',' in !foldl");
1471 return nullptr;
1472 }
1473
1474 if (Lex.Lex() != tgtok::Id) { // eat the ','
1475 TokError("fourth argument of !foldl must be an identifier");
1476 return nullptr;
1477 }
1478
1479 Init *B = StringInit::get(Lex.getCurStrVal());
1480 if (CurRec->getValue(B)) {
1481 TokError((Twine("right !foldl variable '") + B->getAsString() +
1482 "' already defined")
1483 .str());
1484 return nullptr;
1485 }
1486
1487 if (Lex.Lex() != tgtok::comma) { // eat the id
1488 TokError("expected ',' in !foldl");
1489 return nullptr;
1490 }
1491 Lex.Lex(); // eat the ','
1492
1493 CurRec->addValue(RecordVal(A, Start->getType(), false));
1494 CurRec->addValue(RecordVal(B, ListType->getElementType(), false));
1495 Init *ExprUntyped = ParseValue(CurRec);
1496 CurRec->removeValue(A);
1497 CurRec->removeValue(B);
1498 if (!ExprUntyped)
1499 return nullptr;
1500
1501 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1502 if (!Expr) {
1503 TokError("could not get type of !foldl expression");
1504 return nullptr;
1505 }
1506
1507 if (Expr->getType() != Start->getType()) {
1508 TokError(Twine("!foldl expression must be of same type as start (") +
1509 Start->getType()->getAsString() + "), but is of type " +
1510 Expr->getType()->getAsString());
1511 return nullptr;
1512 }
1513
1514 if (Lex.getCode() != tgtok::r_paren) {
1515 TokError("expected ')' in fold operator");
1516 return nullptr;
1517 }
1518 Lex.Lex(); // eat the ')'
1519
1520 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1521 ->Fold(CurRec);
1522 }
1523 }
1524}
1525
1526/// ParseOperatorType - Parse a type for an operator. This returns
1527/// null on error.
1528///
1529/// OperatorType ::= '<' Type '>'
1530///
1531RecTy *TGParser::ParseOperatorType() {
1532 RecTy *Type = nullptr;
1533
1534 if (Lex.getCode() != tgtok::less) {
1535 TokError("expected type name for operator");
1536 return nullptr;
1537 }
1538 Lex.Lex(); // eat the <
1539
1540 Type = ParseType();
1541
1542 if (!Type) {
1543 TokError("expected type name for operator");
1544 return nullptr;
1545 }
1546
1547 if (Lex.getCode() != tgtok::greater) {
1548 TokError("expected type name for operator");
1549 return nullptr;
1550 }
1551 Lex.Lex(); // eat the >
1552
1553 return Type;
1554}
1555
1556/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1557///
1558/// SimpleValue ::= IDValue
1559/// SimpleValue ::= INTVAL
1560/// SimpleValue ::= STRVAL+
1561/// SimpleValue ::= CODEFRAGMENT
1562/// SimpleValue ::= '?'
1563/// SimpleValue ::= '{' ValueList '}'
1564/// SimpleValue ::= ID '<' ValueListNE '>'
1565/// SimpleValue ::= '[' ValueList ']'
1566/// SimpleValue ::= '(' IDValue DagArgList ')'
1567/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1568/// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1569/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1570/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1571/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1572/// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1573/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1574///
1575Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1576 IDParseMode Mode) {
1577 Init *R = nullptr;
1578 switch (Lex.getCode()) {
1579 default: TokError("Unknown token when parsing a value"); break;
1580 case tgtok::paste:
1581 // This is a leading paste operation. This is deprecated but
1582 // still exists in some .td files. Ignore it.
1583 Lex.Lex(); // Skip '#'.
1584 return ParseSimpleValue(CurRec, ItemType, Mode);
1585 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1586 case tgtok::BinaryIntVal: {
1587 auto BinaryVal = Lex.getCurBinaryIntVal();
1588 SmallVector<Init*, 16> Bits(BinaryVal.second);
1589 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1590 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1591 R = BitsInit::get(Bits);
1592 Lex.Lex();
1593 break;
1594 }
1595 case tgtok::StrVal: {
1596 std::string Val = Lex.getCurStrVal();
1597 Lex.Lex();
1598
1599 // Handle multiple consecutive concatenated strings.
1600 while (Lex.getCode() == tgtok::StrVal) {
1601 Val += Lex.getCurStrVal();
1602 Lex.Lex();
1603 }
1604
1605 R = StringInit::get(Val);
1606 break;
1607 }
1608 case tgtok::CodeFragment:
1609 R = CodeInit::get(Lex.getCurStrVal());
1610 Lex.Lex();
1611 break;
1612 case tgtok::question:
1613 R = UnsetInit::get();
1614 Lex.Lex();
1615 break;
1616 case tgtok::Id: {
1617 SMLoc NameLoc = Lex.getLoc();
1618 StringInit *Name = StringInit::get(Lex.getCurStrVal());
1619 if (Lex.Lex() != tgtok::less) // consume the Id.
1620 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1621
1622 // Value ::= ID '<' ValueListNE '>'
1623 if (Lex.Lex() == tgtok::greater) {
1624 TokError("expected non-empty value list");
1625 return nullptr;
1626 }
1627
1628 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1629 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1630 // body.
1631 Record *Class = Records.getClass(Name->getValue());
1632 if (!Class) {
1633 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1634 return nullptr;
1635 }
1636
1637 SmallVector<Init *, 8> Args;
1638 ParseValueList(Args, CurRec, Class);
1639 if (Args.empty()) return nullptr;
1640
1641 if (Lex.getCode() != tgtok::greater) {
1642 TokError("expected '>' at end of value list");
1643 return nullptr;
1644 }
1645 Lex.Lex(); // eat the '>'
1646
1647 // Typecheck the template arguments list
1648 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1649 if (ExpectedArgs.size() < Args.size()) {
1650 Error(NameLoc,
1651 "More template args specified than expected");
1652 return nullptr;
1653 }
1654
1655 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1656 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1657 if (i < Args.size()) {
1658 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1659 RecTy *ExpectedType = ExpectedArg->getType();
1660 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1661 Error(NameLoc,
1662 "Value specified for template argument #" + Twine(i) + " (" +
1663 ExpectedArg->getNameInitAsString() + ") is of type '" +
1664 TI->getType()->getAsString() + "', expected '" +
1665 ExpectedType->getAsString() + "': " + TI->getAsString());
1666 return nullptr;
1667 }
1668 continue;
1669 }
1670 } else if (ExpectedArg->getValue()->isComplete())
1671 continue;
1672
1673 Error(NameLoc,
1674 "Value not specified for template argument #" + Twine(i) + " (" +
1675 ExpectedArgs[i]->getAsUnquotedString() + ")");
1676 return nullptr;
1677 }
1678
1679 return VarDefInit::get(Class, Args)->Fold();
1680 }
1681 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1682 SMLoc BraceLoc = Lex.getLoc();
1683 Lex.Lex(); // eat the '{'
1684 SmallVector<Init*, 16> Vals;
1685
1686 if (Lex.getCode() != tgtok::r_brace) {
1687 ParseValueList(Vals, CurRec);
1688 if (Vals.empty()) return nullptr;
1689 }
1690 if (Lex.getCode() != tgtok::r_brace) {
1691 TokError("expected '}' at end of bit list value");
1692 return nullptr;
1693 }
1694 Lex.Lex(); // eat the '}'
1695
1696 SmallVector<Init *, 16> NewBits;
1697
1698 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1699 // first. We'll first read everything in to a vector, then we can reverse
1700 // it to get the bits in the correct order for the BitsInit value.
1701 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1702 // FIXME: The following two loops would not be duplicated
1703 // if the API was a little more orthogonal.
1704
1705 // bits<n> values are allowed to initialize n bits.
1706 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1707 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1708 NewBits.push_back(BI->getBit((e - i) - 1));
1709 continue;
1710 }
1711 // bits<n> can also come from variable initializers.
1712 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1713 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1714 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1715 NewBits.push_back(VI->getBit((e - i) - 1));
1716 continue;
1717 }
1718 // Fallthrough to try convert this to a bit.
1719 }
1720 // All other values must be convertible to just a single bit.
1721 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1722 if (!Bit) {
1723 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1724 ") is not convertable to a bit");
1725 return nullptr;
1726 }
1727 NewBits.push_back(Bit);
1728 }
1729 std::reverse(NewBits.begin(), NewBits.end());
1730 return BitsInit::get(NewBits);
1731 }
1732 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1733 Lex.Lex(); // eat the '['
1734 SmallVector<Init*, 16> Vals;
1735
1736 RecTy *DeducedEltTy = nullptr;
1737 ListRecTy *GivenListTy = nullptr;
1738
1739 if (ItemType) {
1740 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1741 if (!ListType) {
1742 TokError(Twine("Type mismatch for list, expected list type, got ") +
1743 ItemType->getAsString());
1744 return nullptr;
1745 }
1746 GivenListTy = ListType;
1747 }
1748
1749 if (Lex.getCode() != tgtok::r_square) {
1750 ParseValueList(Vals, CurRec, nullptr,
1751 GivenListTy ? GivenListTy->getElementType() : nullptr);
1752 if (Vals.empty()) return nullptr;
1753 }
1754 if (Lex.getCode() != tgtok::r_square) {
1755 TokError("expected ']' at end of list value");
1756 return nullptr;
1757 }
1758 Lex.Lex(); // eat the ']'
1759
1760 RecTy *GivenEltTy = nullptr;
1761 if (Lex.getCode() == tgtok::less) {
1762 // Optional list element type
1763 Lex.Lex(); // eat the '<'
1764
1765 GivenEltTy = ParseType();
1766 if (!GivenEltTy) {
1767 // Couldn't parse element type
1768 return nullptr;
1769 }
1770
1771 if (Lex.getCode() != tgtok::greater) {
1772 TokError("expected '>' at end of list element type");
1773 return nullptr;
1774 }
1775 Lex.Lex(); // eat the '>'
1776 }
1777
1778 // Check elements
1779 RecTy *EltTy = nullptr;
1780 for (Init *V : Vals) {
1781 TypedInit *TArg = dyn_cast<TypedInit>(V);
1782 if (TArg) {
1783 if (EltTy) {
1784 EltTy = resolveTypes(EltTy, TArg->getType());
1785 if (!EltTy) {
1786 TokError("Incompatible types in list elements");
1787 return nullptr;
1788 }
1789 } else {
1790 EltTy = TArg->getType();
1791 }
1792 }
1793 }
1794
1795 if (GivenEltTy) {
1796 if (EltTy) {
1797 // Verify consistency
1798 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1799 TokError("Incompatible types in list elements");
1800 return nullptr;
1801 }
1802 }
1803 EltTy = GivenEltTy;
1804 }
1805
1806 if (!EltTy) {
1807 if (!ItemType) {
1808 TokError("No type for list");
1809 return nullptr;
1810 }
1811 DeducedEltTy = GivenListTy->getElementType();
1812 } else {
1813 // Make sure the deduced type is compatible with the given type
1814 if (GivenListTy) {
1815 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1816 TokError(Twine("Element type mismatch for list: element type '") +
1817 EltTy->getAsString() + "' not convertible to '" +
1818 GivenListTy->getElementType()->getAsString());
1819 return nullptr;
1820 }
1821 }
1822 DeducedEltTy = EltTy;
1823 }
1824
1825 return ListInit::get(Vals, DeducedEltTy);
1826 }
1827 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1828 Lex.Lex(); // eat the '('
1829 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1830 TokError("expected identifier in dag init");
1831 return nullptr;
1832 }
1833
1834 Init *Operator = ParseValue(CurRec);
1835 if (!Operator) return nullptr;
1836
1837 // If the operator name is present, parse it.
1838 StringInit *OperatorName = nullptr;
1839 if (Lex.getCode() == tgtok::colon) {
1840 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1841 TokError("expected variable name in dag operator");
1842 return nullptr;
1843 }
1844 OperatorName = StringInit::get(Lex.getCurStrVal());
1845 Lex.Lex(); // eat the VarName.
1846 }
1847
1848 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
1849 if (Lex.getCode() != tgtok::r_paren) {
1850 ParseDagArgList(DagArgs, CurRec);
1851 if (DagArgs.empty()) return nullptr;
1852 }
1853
1854 if (Lex.getCode() != tgtok::r_paren) {
1855 TokError("expected ')' in dag init");
1856 return nullptr;
1857 }
1858 Lex.Lex(); // eat the ')'
1859
1860 return DagInit::get(Operator, OperatorName, DagArgs);
1861 }
1862
1863 case tgtok::XHead:
1864 case tgtok::XTail:
1865 case tgtok::XSize:
1866 case tgtok::XEmpty:
1867 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1868 case tgtok::XIsA:
1869 case tgtok::XConcat:
1870 case tgtok::XDag:
1871 case tgtok::XADD:
1872 case tgtok::XAND:
1873 case tgtok::XOR:
1874 case tgtok::XSRA:
1875 case tgtok::XSRL:
1876 case tgtok::XSHL:
1877 case tgtok::XEq:
1878 case tgtok::XNe:
1879 case tgtok::XLe:
1880 case tgtok::XLt:
1881 case tgtok::XGe:
1882 case tgtok::XGt:
1883 case tgtok::XListConcat:
1884 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1885 case tgtok::XIf:
1886 case tgtok::XFoldl:
1887 case tgtok::XForEach:
1888 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1889 return ParseOperation(CurRec, ItemType);
1890 }
1891 }
1892
1893 return R;
1894}
1895
1896/// ParseValue - Parse a tblgen value. This returns null on error.
1897///
1898/// Value ::= SimpleValue ValueSuffix*
1899/// ValueSuffix ::= '{' BitList '}'
1900/// ValueSuffix ::= '[' BitList ']'
1901/// ValueSuffix ::= '.' ID
1902///
1903Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1904 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1905 if (!Result) return nullptr;
1906
1907 // Parse the suffixes now if present.
1908 while (true) {
1909 switch (Lex.getCode()) {
1910 default: return Result;
1911 case tgtok::l_brace: {
1912 if (Mode == ParseNameMode)
1913 // This is the beginning of the object body.
1914 return Result;
1915
1916 SMLoc CurlyLoc = Lex.getLoc();
1917 Lex.Lex(); // eat the '{'
1918 SmallVector<unsigned, 16> Ranges;
1919 ParseRangeList(Ranges);
1920 if (Ranges.empty()) return nullptr;
1921
1922 // Reverse the bitlist.
1923 std::reverse(Ranges.begin(), Ranges.end());
1924 Result = Result->convertInitializerBitRange(Ranges);
1925 if (!Result) {
1926 Error(CurlyLoc, "Invalid bit range for value");
1927 return nullptr;
1928 }
1929
1930 // Eat the '}'.
1931 if (Lex.getCode() != tgtok::r_brace) {
1932 TokError("expected '}' at end of bit range list");
1933 return nullptr;
1934 }
1935 Lex.Lex();
1936 break;
1937 }
1938 case tgtok::l_square: {
1939 SMLoc SquareLoc = Lex.getLoc();
1940 Lex.Lex(); // eat the '['
1941 SmallVector<unsigned, 16> Ranges;
1942 ParseRangeList(Ranges);
1943 if (Ranges.empty()) return nullptr;
1944
1945 Result = Result->convertInitListSlice(Ranges);
1946 if (!Result) {
1947 Error(SquareLoc, "Invalid range for list slice");
1948 return nullptr;
1949 }
1950
1951 // Eat the ']'.
1952 if (Lex.getCode() != tgtok::r_square) {
1953 TokError("expected ']' at end of list slice");
1954 return nullptr;
1955 }
1956 Lex.Lex();
1957 break;
1958 }
1959 case tgtok::period: {
1960 if (Lex.Lex() != tgtok::Id) { // eat the .
1961 TokError("expected field identifier after '.'");
1962 return nullptr;
1963 }
1964 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
1965 if (!Result->getFieldType(FieldName)) {
1966 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1967 Result->getAsString() + "'");
1968 return nullptr;
1969 }
1970 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
1971 Lex.Lex(); // eat field name
1972 break;
1973 }
1974
1975 case tgtok::paste:
1976 SMLoc PasteLoc = Lex.getLoc();
1977
1978 // Create a !strconcat() operation, first casting each operand to
1979 // a string if necessary.
1980
1981 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1982 if (!LHS) {
1983 Error(PasteLoc, "LHS of paste is not typed!");
1984 return nullptr;
1985 }
1986
1987 if (LHS->getType() != StringRecTy::get()) {
1988 LHS = dyn_cast<TypedInit>(
1989 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
1990 ->Fold(CurRec));
1991 if (!LHS) {
1992 Error(PasteLoc, Twine("can't cast '") + LHS->getAsString() +
1993 "' to string");
1994 return nullptr;
1995 }
1996 }
1997
1998 TypedInit *RHS = nullptr;
1999
2000 Lex.Lex(); // Eat the '#'.
2001 switch (Lex.getCode()) {
2002 case tgtok::colon:
2003 case tgtok::semi:
2004 case tgtok::l_brace:
2005 // These are all of the tokens that can begin an object body.
2006 // Some of these can also begin values but we disallow those cases
2007 // because they are unlikely to be useful.
2008
2009 // Trailing paste, concat with an empty string.
2010 RHS = StringInit::get("");
2011 break;
2012
2013 default:
2014 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2015 RHS = dyn_cast<TypedInit>(RHSResult);
2016 if (!RHS) {
2017 Error(PasteLoc, "RHS of paste is not typed!");
2018 return nullptr;
2019 }
2020
2021 if (RHS->getType() != StringRecTy::get()) {
2022 RHS = dyn_cast<TypedInit>(
2023 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2024 ->Fold(CurRec));
2025 if (!RHS) {
2026 Error(PasteLoc, Twine("can't cast '") + RHS->getAsString() +
2027 "' to string");
2028 return nullptr;
2029 }
2030 }
2031
2032 break;
2033 }
2034
2035 Result = BinOpInit::getStrConcat(LHS, RHS);
2036 break;
2037 }
2038 }
2039}
2040
2041/// ParseDagArgList - Parse the argument list for a dag literal expression.
2042///
2043/// DagArg ::= Value (':' VARNAME)?
2044/// DagArg ::= VARNAME
2045/// DagArgList ::= DagArg
2046/// DagArgList ::= DagArgList ',' DagArg
2047void TGParser::ParseDagArgList(
2048 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2049 Record *CurRec) {
2050
2051 while (true) {
2052 // DagArg ::= VARNAME
2053 if (Lex.getCode() == tgtok::VarName) {
2054 // A missing value is treated like '?'.
2055 StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2056 Result.emplace_back(UnsetInit::get(), VarName);
2057 Lex.Lex();
2058 } else {
2059 // DagArg ::= Value (':' VARNAME)?
2060 Init *Val = ParseValue(CurRec);
2061 if (!Val) {
2062 Result.clear();
2063 return;
2064 }
2065
2066 // If the variable name is present, add it.
2067 StringInit *VarName = nullptr;
2068 if (Lex.getCode() == tgtok::colon) {
2069 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2070 TokError("expected variable name in dag literal");
2071 Result.clear();
2072 return;
2073 }
2074 VarName = StringInit::get(Lex.getCurStrVal());
2075 Lex.Lex(); // eat the VarName.
2076 }
2077
2078 Result.push_back(std::make_pair(Val, VarName));
2079 }
2080 if (Lex.getCode() != tgtok::comma) break;
2081 Lex.Lex(); // eat the ','
2082 }
2083}
2084
2085/// ParseValueList - Parse a comma separated list of values, returning them as a
2086/// vector. Note that this always expects to be able to parse at least one
2087/// value. It returns an empty list if this is not possible.
2088///
2089/// ValueList ::= Value (',' Value)
2090///
2091void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2092 Record *ArgsRec, RecTy *EltTy) {
2093 RecTy *ItemType = EltTy;
2094 unsigned int ArgN = 0;
2095 if (ArgsRec && !EltTy) {
2096 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2097 if (TArgs.empty()) {
2098 TokError("template argument provided to non-template class");
2099 Result.clear();
2100 return;
2101 }
2102 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2103 if (!RV) {
2104 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2105 << ")\n";
2106 }
2107 assert(RV && "Template argument record not found??")(static_cast <bool> (RV && "Template argument record not found??"
) ? void (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2107, __extension__ __PRETTY_FUNCTION__))
;
2108 ItemType = RV->getType();
2109 ++ArgN;
2110 }
2111 Result.push_back(ParseValue(CurRec, ItemType));
2112 if (!Result.back()) {
2113 Result.clear();
2114 return;
2115 }
2116
2117 while (Lex.getCode() == tgtok::comma) {
2118 Lex.Lex(); // Eat the comma
2119
2120 if (ArgsRec && !EltTy) {
2121 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2122 if (ArgN >= TArgs.size()) {
2123 TokError("too many template arguments");
2124 Result.clear();
2125 return;
2126 }
2127 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2128 assert(RV && "Template argument record not found??")(static_cast <bool> (RV && "Template argument record not found??"
) ? void (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2128, __extension__ __PRETTY_FUNCTION__))
;
2129 ItemType = RV->getType();
2130 ++ArgN;
2131 }
2132 Result.push_back(ParseValue(CurRec, ItemType));
2133 if (!Result.back()) {
2134 Result.clear();
2135 return;
2136 }
2137 }
2138}
2139
2140/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2141/// empty string on error. This can happen in a number of different context's,
2142/// including within a def or in the template args for a def (which which case
2143/// CurRec will be non-null) and within the template args for a multiclass (in
2144/// which case CurRec will be null, but CurMultiClass will be set). This can
2145/// also happen within a def that is within a multiclass, which will set both
2146/// CurRec and CurMultiClass.
2147///
2148/// Declaration ::= FIELD? Type ID ('=' Value)?
2149///
2150Init *TGParser::ParseDeclaration(Record *CurRec,
2151 bool ParsingTemplateArgs) {
2152 // Read the field prefix if present.
2153 bool HasField = Lex.getCode() == tgtok::Field;
2154 if (HasField) Lex.Lex();
2155
2156 RecTy *Type = ParseType();
2157 if (!Type) return nullptr;
2158
2159 if (Lex.getCode() != tgtok::Id) {
2160 TokError("Expected identifier in declaration");
2161 return nullptr;
2162 }
2163
2164 SMLoc IdLoc = Lex.getLoc();
2165 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2166 Lex.Lex();
2167
2168 if (ParsingTemplateArgs) {
2169 if (CurRec)
2170 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2171 else
2172 assert(CurMultiClass)(static_cast <bool> (CurMultiClass) ? void (0) : __assert_fail
("CurMultiClass", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2172, __extension__ __PRETTY_FUNCTION__))
;
2173 if (CurMultiClass)
2174 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2175 "::");
2176 }
2177
2178 // Add the value.
2179 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2180 return nullptr;
2181
2182 // If a value is present, parse it.
2183 if (Lex.getCode() == tgtok::equal) {
2184 Lex.Lex();
2185 SMLoc ValLoc = Lex.getLoc();
2186 Init *Val = ParseValue(CurRec, Type);
2187 if (!Val ||
2188 SetValue(CurRec, ValLoc, DeclName, None, Val))
2189 // Return the name, even if an error is thrown. This is so that we can
2190 // continue to make some progress, even without the value having been
2191 // initialized.
2192 return DeclName;
2193 }
2194
2195 return DeclName;
2196}
2197
2198/// ParseForeachDeclaration - Read a foreach declaration, returning
2199/// the name of the declared object or a NULL Init on error. Return
2200/// the name of the parsed initializer list through ForeachListName.
2201///
2202/// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2203/// ForeachDeclaration ::= ID '=' RangePiece
2204/// ForeachDeclaration ::= ID '=' Value
2205///
2206VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
2207 if (Lex.getCode() != tgtok::Id) {
2208 TokError("Expected identifier in foreach declaration");
2209 return nullptr;
2210 }
2211
2212 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2213 Lex.Lex();
2214
2215 // If a value is present, parse it.
2216 if (Lex.getCode() != tgtok::equal) {
2217 TokError("Expected '=' in foreach declaration");
2218 return nullptr;
2219 }
2220 Lex.Lex(); // Eat the '='
2221
2222 RecTy *IterType = nullptr;
2223 SmallVector<unsigned, 16> Ranges;
2224
2225 switch (Lex.getCode()) {
2226 case tgtok::IntVal: { // RangePiece.
2227 if (ParseRangePiece(Ranges))
2228 return nullptr;
2229 break;
2230 }
2231
2232 case tgtok::l_brace: { // '{' RangeList '}'
2233 Lex.Lex(); // eat the '{'
2234 ParseRangeList(Ranges);
2235 if (Lex.getCode() != tgtok::r_brace) {
2236 TokError("expected '}' at end of bit range list");
2237 return nullptr;
2238 }
2239 Lex.Lex();
2240 break;
2241 }
2242
2243 default: {
2244 SMLoc ValueLoc = Lex.getLoc();
2245 Init *I = ParseValue(nullptr);
2246 if (!isa<ListInit>(I)) {
2247 std::string Type;
2248 if (TypedInit *TI = dyn_cast<TypedInit>(I))
2249 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2250 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2251 if (CurMultiClass)
2252 PrintNote({}, "references to multiclass template arguments cannot be "
2253 "resolved at this time");
2254 return nullptr;
2255 }
2256 ForeachListValue = dyn_cast<ListInit>(I);
2257 IterType = ForeachListValue->getElementType();
2258 break;
2259 }
2260 }
2261
2262 if (!Ranges.empty()) {
2263 assert(!IterType && "Type already initialized?")(static_cast <bool> (!IterType && "Type already initialized?"
) ? void (0) : __assert_fail ("!IterType && \"Type already initialized?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2263, __extension__ __PRETTY_FUNCTION__))
;
2264 IterType = IntRecTy::get();
2265 std::vector<Init*> Values;
2266 for (unsigned R : Ranges)
2267 Values.push_back(IntInit::get(R));
2268 ForeachListValue = ListInit::get(Values, IterType);
2269 }
2270
2271 if (!IterType)
2272 return nullptr;
2273
2274 return VarInit::get(DeclName, IterType);
2275}
2276
2277/// ParseTemplateArgList - Read a template argument list, which is a non-empty
2278/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2279/// template args for a def, which may or may not be in a multiclass. If null,
2280/// these are the template args for a multiclass.
2281///
2282/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2283///
2284bool TGParser::ParseTemplateArgList(Record *CurRec) {
2285 assert(Lex.getCode() == tgtok::less && "Not a template arg list!")(static_cast <bool> (Lex.getCode() == tgtok::less &&
"Not a template arg list!") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::less && \"Not a template arg list!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2285, __extension__ __PRETTY_FUNCTION__))
;
2286 Lex.Lex(); // eat the '<'
2287
2288 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2289
2290 // Read the first declaration.
2291 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2292 if (!TemplArg)
2293 return true;
2294
2295 TheRecToAddTo->addTemplateArg(TemplArg);
2296
2297 while (Lex.getCode() == tgtok::comma) {
2298 Lex.Lex(); // eat the ','
2299
2300 // Read the following declarations.
2301 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2302 if (!TemplArg)
2303 return true;
2304 TheRecToAddTo->addTemplateArg(TemplArg);
2305 }
2306
2307 if (Lex.getCode() != tgtok::greater)
2308 return TokError("expected '>' at end of template argument list");
2309 Lex.Lex(); // eat the '>'.
2310 return false;
2311}
2312
2313/// ParseBodyItem - Parse a single item at within the body of a def or class.
2314///
2315/// BodyItem ::= Declaration ';'
2316/// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2317bool TGParser::ParseBodyItem(Record *CurRec) {
2318 if (Lex.getCode() != tgtok::Let) {
2319 if (!ParseDeclaration(CurRec, false))
2320 return true;
2321
2322 if (Lex.getCode() != tgtok::semi)
2323 return TokError("expected ';' after declaration");
2324 Lex.Lex();
2325 return false;
2326 }
2327
2328 // LET ID OptionalRangeList '=' Value ';'
2329 if (Lex.Lex() != tgtok::Id)
2330 return TokError("expected field identifier after let");
2331
2332 SMLoc IdLoc = Lex.getLoc();
2333 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2334 Lex.Lex(); // eat the field name.
2335
2336 SmallVector<unsigned, 16> BitList;
2337 if (ParseOptionalBitList(BitList))
2338 return true;
2339 std::reverse(BitList.begin(), BitList.end());
2340
2341 if (Lex.getCode() != tgtok::equal)
2342 return TokError("expected '=' in let expression");
2343 Lex.Lex(); // eat the '='.
2344
2345 RecordVal *Field = CurRec->getValue(FieldName);
2346 if (!Field)
2347 return TokError("Value '" + FieldName->getValue() + "' unknown!");
2348
2349 RecTy *Type = Field->getType();
2350
2351 Init *Val = ParseValue(CurRec, Type);
2352 if (!Val) return true;
2353
2354 if (Lex.getCode() != tgtok::semi)
2355 return TokError("expected ';' after let expression");
2356 Lex.Lex();
2357
2358 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2359}
2360
2361/// ParseBody - Read the body of a class or def. Return true on error, false on
2362/// success.
2363///
2364/// Body ::= ';'
2365/// Body ::= '{' BodyList '}'
2366/// BodyList BodyItem*
2367///
2368bool TGParser::ParseBody(Record *CurRec) {
2369 // If this is a null definition, just eat the semi and return.
2370 if (Lex.getCode() == tgtok::semi) {
2371 Lex.Lex();
2372 return false;
2373 }
2374
2375 if (Lex.getCode() != tgtok::l_brace)
2376 return TokError("Expected ';' or '{' to start body");
2377 // Eat the '{'.
2378 Lex.Lex();
2379
2380 while (Lex.getCode() != tgtok::r_brace)
2381 if (ParseBodyItem(CurRec))
2382 return true;
2383
2384 // Eat the '}'.
2385 Lex.Lex();
2386 return false;
2387}
2388
2389/// \brief Apply the current let bindings to \a CurRec.
2390/// \returns true on error, false otherwise.
2391bool TGParser::ApplyLetStack(Record *CurRec) {
2392 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2393 for (LetRecord &LR : LetInfo)
2394 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2395 return true;
2396 return false;
2397}
2398
2399/// ParseObjectBody - Parse the body of a def or class. This consists of an
2400/// optional ClassList followed by a Body. CurRec is the current def or class
2401/// that is being parsed.
2402///
2403/// ObjectBody ::= BaseClassList Body
2404/// BaseClassList ::= /*empty*/
2405/// BaseClassList ::= ':' BaseClassListNE
2406/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2407///
2408bool TGParser::ParseObjectBody(Record *CurRec) {
2409 // If there is a baseclass list, read it.
2410 if (Lex.getCode() == tgtok::colon) {
2411 Lex.Lex();
2412
2413 // Read all of the subclasses.
2414 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2415 while (true) {
2416 // Check for error.
2417 if (!SubClass.Rec) return true;
2418
2419 // Add it.
2420 if (AddSubClass(CurRec, SubClass))
2421 return true;
2422
2423 if (Lex.getCode() != tgtok::comma) break;
2424 Lex.Lex(); // eat ','.
2425 SubClass = ParseSubClassReference(CurRec, false);
2426 }
2427 }
2428
2429 if (ApplyLetStack(CurRec))
2430 return true;
2431
2432 return ParseBody(CurRec);
2433}
2434
2435/// ParseDef - Parse and return a top level or multiclass def, return the record
2436/// corresponding to it. This returns null on error.
2437///
2438/// DefInst ::= DEF ObjectName ObjectBody
2439///
2440bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2441 SMLoc DefLoc = Lex.getLoc();
2442 assert(Lex.getCode() == tgtok::Def && "Unknown tok")(static_cast <bool> (Lex.getCode() == tgtok::Def &&
"Unknown tok") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::Def && \"Unknown tok\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2442, __extension__ __PRETTY_FUNCTION__))
;
2443 Lex.Lex(); // Eat the 'def' token.
2444
2445 // Parse ObjectName and make a record for it.
2446 std::unique_ptr<Record> CurRec;
2447 Init *Name = ParseObjectName(CurMultiClass);
2448 if (!Name)
2449 return true;
2450
2451 if (isa<UnsetInit>(Name))
2452 CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2453 /*Anonymous=*/true);
2454 else
2455 CurRec = make_unique<Record>(Name, DefLoc, Records);
2456
2457 if (ParseObjectBody(CurRec.get()))
2458 return true;
2459
2460 return addDef(std::move(CurRec), nullptr);
2461}
2462
2463/// ParseDefset - Parse a defset statement.
2464///
2465/// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2466///
2467bool TGParser::ParseDefset() {
2468 assert(Lex.getCode() == tgtok::Defset)(static_cast <bool> (Lex.getCode() == tgtok::Defset) ? void
(0) : __assert_fail ("Lex.getCode() == tgtok::Defset", "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2468, __extension__ __PRETTY_FUNCTION__))
;
2469 Lex.Lex(); // Eat the 'defset' token
2470
2471 DefsetRecord Defset;
2472 Defset.Loc = Lex.getLoc();
2473 RecTy *Type = ParseType();
2474 if (!Type)
2475 return true;
2476 if (!isa<ListRecTy>(Type))
2477 return Error(Defset.Loc, "expected list type");
2478 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2479
2480 if (Lex.getCode() != tgtok::Id)
2481 return TokError("expected identifier");
2482 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2483 if (Records.getGlobal(DeclName->getValue()))
2484 return TokError("def or global variable of this name already exists");
2485
2486 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2487 return TokError("expected '='");
2488 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2489 return TokError("expected '{'");
2490 SMLoc BraceLoc = Lex.getLoc();
2491 Lex.Lex(); // Eat the '{'
2492
2493 Defsets.push_back(&Defset);
2494 bool Err = ParseObjectList(nullptr);
2495 Defsets.pop_back();
2496 if (Err)
2497 return true;
2498
2499 if (Lex.getCode() != tgtok::r_brace) {
2500 TokError("expected '}' at end of defset");
2501 return Error(BraceLoc, "to match this '{'");
2502 }
2503 Lex.Lex(); // Eat the '}'
2504
2505 Records.addExtraGlobal(DeclName->getValue(),
2506 ListInit::get(Defset.Elements, Defset.EltTy));
2507 return false;
2508}
2509
2510/// ParseForeach - Parse a for statement. Return the record corresponding
2511/// to it. This returns true on error.
2512///
2513/// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2514/// Foreach ::= FOREACH Declaration IN Object
2515///
2516bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2517 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok")(static_cast <bool> (Lex.getCode() == tgtok::Foreach &&
"Unknown tok") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::Foreach && \"Unknown tok\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2517, __extension__ __PRETTY_FUNCTION__))
;
2518 Lex.Lex(); // Eat the 'for' token.
2519
2520 // Make a temporary object to record items associated with the for
2521 // loop.
2522 ListInit *ListValue = nullptr;
2523 VarInit *IterName = ParseForeachDeclaration(ListValue);
2524 if (!IterName)
2525 return TokError("expected declaration in for");
2526
2527 if (Lex.getCode() != tgtok::In)
2528 return TokError("Unknown tok");
2529 Lex.Lex(); // Eat the in
2530
2531 // Create a loop object and remember it.
2532 Loops.push_back(ForeachLoop(IterName, ListValue));
2533
2534 if (Lex.getCode() != tgtok::l_brace) {
2535 // FOREACH Declaration IN Object
2536 if (ParseObject(CurMultiClass))
2537 return true;
2538 } else {
2539 SMLoc BraceLoc = Lex.getLoc();
2540 // Otherwise, this is a group foreach.
2541 Lex.Lex(); // eat the '{'.
2542
2543 // Parse the object list.
2544 if (ParseObjectList(CurMultiClass))
2545 return true;
2546
2547 if (Lex.getCode() != tgtok::r_brace) {
2548 TokError("expected '}' at end of foreach command");
2549 return Error(BraceLoc, "to match this '{'");
2550 }
2551 Lex.Lex(); // Eat the }
2552 }
2553
2554 // We've processed everything in this loop.
2555 Loops.pop_back();
2556
2557 return false;
2558}
2559
2560/// ParseClass - Parse a tblgen class definition.
2561///
2562/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2563///
2564bool TGParser::ParseClass() {
2565 assert(Lex.getCode() == tgtok::Class && "Unexpected token!")(static_cast <bool> (Lex.getCode() == tgtok::Class &&
"Unexpected token!") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::Class && \"Unexpected token!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2565, __extension__ __PRETTY_FUNCTION__))
;
2566 Lex.Lex();
2567
2568 if (Lex.getCode() != tgtok::Id)
9
Assuming the condition is false
10
Taking false branch
2569 return TokError("expected class name after 'class' keyword");
2570
2571 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2572 if (CurRec) {
11
Taking false branch
2573 // If the body was previously defined, this is an error.
2574 if (CurRec->getValues().size() > 1 || // Account for NAME.
2575 !CurRec->getSuperClasses().empty() ||
2576 !CurRec->getTemplateArgs().empty())
2577 return TokError("Class '" + CurRec->getNameInitAsString() +
2578 "' already defined");
2579 } else {
2580 // If this is the first reference to this class, create and add it.
2581 auto NewRec =
2582 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
12
Calling 'make_unique'
14
Returned allocated memory
2583 CurRec = NewRec.get();
2584 Records.addClass(std::move(NewRec));
15
Calling '~unique_ptr'
20
Returning from '~unique_ptr'
2585 }
2586 Lex.Lex(); // eat the name.
2587
2588 // If there are template args, parse them.
2589 if (Lex.getCode() == tgtok::less)
21
Assuming the condition is true
22
Taking true branch
2590 if (ParseTemplateArgList(CurRec))
23
Use of memory after it is freed
2591 return true;
2592
2593 // Finally, parse the object body.
2594 return ParseObjectBody(CurRec);
2595}
2596
2597/// ParseLetList - Parse a non-empty list of assignment expressions into a list
2598/// of LetRecords.
2599///
2600/// LetList ::= LetItem (',' LetItem)*
2601/// LetItem ::= ID OptionalRangeList '=' Value
2602///
2603void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
2604 while (true) {
2605 if (Lex.getCode() != tgtok::Id) {
2606 TokError("expected identifier in let definition");
2607 Result.clear();
2608 return;
2609 }
2610
2611 StringInit *Name = StringInit::get(Lex.getCurStrVal());
2612 SMLoc NameLoc = Lex.getLoc();
2613 Lex.Lex(); // Eat the identifier.
2614
2615 // Check for an optional RangeList.
2616 SmallVector<unsigned, 16> Bits;
2617 if (ParseOptionalRangeList(Bits)) {
2618 Result.clear();
2619 return;
2620 }
2621 std::reverse(Bits.begin(), Bits.end());
2622
2623 if (Lex.getCode() != tgtok::equal) {
2624 TokError("expected '=' in let expression");
2625 Result.clear();
2626 return;
2627 }
2628 Lex.Lex(); // eat the '='.
2629
2630 Init *Val = ParseValue(nullptr);
2631 if (!Val) {
2632 Result.clear();
2633 return;
2634 }
2635
2636 // Now that we have everything, add the record.
2637 Result.emplace_back(Name, Bits, Val, NameLoc);
2638
2639 if (Lex.getCode() != tgtok::comma)
2640 return;
2641 Lex.Lex(); // eat the comma.
2642 }
2643}
2644
2645/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2646/// different related productions. This works inside multiclasses too.
2647///
2648/// Object ::= LET LetList IN '{' ObjectList '}'
2649/// Object ::= LET LetList IN Object
2650///
2651bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2652 assert(Lex.getCode() == tgtok::Let && "Unexpected token")(static_cast <bool> (Lex.getCode() == tgtok::Let &&
"Unexpected token") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::Let && \"Unexpected token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2652, __extension__ __PRETTY_FUNCTION__))
;
2653 Lex.Lex();
2654
2655 // Add this entry to the let stack.
2656 SmallVector<LetRecord, 8> LetInfo;
2657 ParseLetList(LetInfo);
2658 if (LetInfo.empty()) return true;
2659 LetStack.push_back(std::move(LetInfo));
2660
2661 if (Lex.getCode() != tgtok::In)
2662 return TokError("expected 'in' at end of top-level 'let'");
2663 Lex.Lex();
2664
2665 // If this is a scalar let, just handle it now
2666 if (Lex.getCode() != tgtok::l_brace) {
2667 // LET LetList IN Object
2668 if (ParseObject(CurMultiClass))
2669 return true;
2670 } else { // Object ::= LETCommand '{' ObjectList '}'
2671 SMLoc BraceLoc = Lex.getLoc();
2672 // Otherwise, this is a group let.
2673 Lex.Lex(); // eat the '{'.
2674
2675 // Parse the object list.
2676 if (ParseObjectList(CurMultiClass))
2677 return true;
2678
2679 if (Lex.getCode() != tgtok::r_brace) {
2680 TokError("expected '}' at end of top level let command");
2681 return Error(BraceLoc, "to match this '{'");
2682 }
2683 Lex.Lex();
2684 }
2685
2686 // Outside this let scope, this let block is not active.
2687 LetStack.pop_back();
2688 return false;
2689}
2690
2691/// ParseMultiClass - Parse a multiclass definition.
2692///
2693/// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2694/// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2695/// MultiClassObject ::= DefInst
2696/// MultiClassObject ::= MultiClassInst
2697/// MultiClassObject ::= DefMInst
2698/// MultiClassObject ::= LETCommand '{' ObjectList '}'
2699/// MultiClassObject ::= LETCommand Object
2700///
2701bool TGParser::ParseMultiClass() {
2702 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token")(static_cast <bool> (Lex.getCode() == tgtok::MultiClass
&& "Unexpected token") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::MultiClass && \"Unexpected token\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2702, __extension__ __PRETTY_FUNCTION__))
;
2703 Lex.Lex(); // Eat the multiclass token.
2704
2705 if (Lex.getCode() != tgtok::Id)
2706 return TokError("expected identifier after multiclass for name");
2707 std::string Name = Lex.getCurStrVal();
2708
2709 auto Result =
2710 MultiClasses.insert(std::make_pair(Name,
2711 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2712
2713 if (!Result.second)
2714 return TokError("multiclass '" + Name + "' already defined");
2715
2716 CurMultiClass = Result.first->second.get();
2717 Lex.Lex(); // Eat the identifier.
2718
2719 // If there are template args, parse them.
2720 if (Lex.getCode() == tgtok::less)
2721 if (ParseTemplateArgList(nullptr))
2722 return true;
2723
2724 bool inherits = false;
2725
2726 // If there are submulticlasses, parse them.
2727 if (Lex.getCode() == tgtok::colon) {
2728 inherits = true;
2729
2730 Lex.Lex();
2731
2732 // Read all of the submulticlasses.
2733 SubMultiClassReference SubMultiClass =
2734 ParseSubMultiClassReference(CurMultiClass);
2735 while (true) {
2736 // Check for error.
2737 if (!SubMultiClass.MC) return true;
2738
2739 // Add it.
2740 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2741 return true;
2742
2743 if (Lex.getCode() != tgtok::comma) break;
2744 Lex.Lex(); // eat ','.
2745 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2746 }
2747 }
2748
2749 if (Lex.getCode() != tgtok::l_brace) {
2750 if (!inherits)
2751 return TokError("expected '{' in multiclass definition");
2752 if (Lex.getCode() != tgtok::semi)
2753 return TokError("expected ';' in multiclass definition");
2754 Lex.Lex(); // eat the ';'.
2755 } else {
2756 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2757 return TokError("multiclass must contain at least one def");
2758
2759 while (Lex.getCode() != tgtok::r_brace) {
2760 switch (Lex.getCode()) {
2761 default:
2762 return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
2763 "multiclass body");
2764 case tgtok::Let:
2765 case tgtok::Def:
2766 case tgtok::Defm:
2767 case tgtok::Foreach:
2768 if (ParseObject(CurMultiClass))
2769 return true;
2770 break;
2771 }
2772 }
2773 Lex.Lex(); // eat the '}'.
2774 }
2775
2776 CurMultiClass = nullptr;
2777 return false;
2778}
2779
2780/// ParseDefm - Parse the instantiation of a multiclass.
2781///
2782/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2783///
2784bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2785 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!")(static_cast <bool> (Lex.getCode() == tgtok::Defm &&
"Unexpected token!") ? void (0) : __assert_fail ("Lex.getCode() == tgtok::Defm && \"Unexpected token!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2785, __extension__ __PRETTY_FUNCTION__))
;
2786 Lex.Lex(); // eat the defm
2787
2788 Init *DefmName = ParseObjectName(CurMultiClass);
2789 if (!DefmName)
2790 return true;
2791 if (isa<UnsetInit>(DefmName))
2792 DefmName = Records.getNewAnonymousName();
2793
2794 if (Lex.getCode() != tgtok::colon)
2795 return TokError("expected ':' after defm identifier");
2796
2797 // Keep track of the new generated record definitions.
2798 SmallVector<std::unique_ptr<Record>, 8> NewRecDefs;
2799
2800 // This record also inherits from a regular class (non-multiclass)?
2801 bool InheritFromClass = false;
2802
2803 // eat the colon.
2804 Lex.Lex();
2805
2806 SMLoc SubClassLoc = Lex.getLoc();
2807 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2808
2809 while (true) {
2810 if (!Ref.Rec) return true;
2811
2812 // To instantiate a multiclass, we need to first get the multiclass, then
2813 // instantiate each def contained in the multiclass with the SubClassRef
2814 // template parameters.
2815 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2816 assert(MC && "Didn't lookup multiclass correctly?")(static_cast <bool> (MC && "Didn't lookup multiclass correctly?"
) ? void (0) : __assert_fail ("MC && \"Didn't lookup multiclass correctly?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/lib/TableGen/TGParser.cpp"
, 2816, __extension__ __PRETTY_FUNCTION__))
;
2817 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
2818
2819 // Verify that the correct number of template arguments were specified.
2820 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
2821 if (TArgs.size() < TemplateVals.size())
2822 return Error(SubClassLoc,
2823 "more template args specified than multiclass expects");
2824
2825 DenseMap<Init *, Init *> TemplateArgs;
2826 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2827 if (i < TemplateVals.size()) {
2828 TemplateArgs.insert({TArgs[i], TemplateVals[i]});
2829 } else {
2830 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
2831 if (!Default->isComplete()) {
2832 return Error(SubClassLoc,
2833 "value not specified for template argument #" +
2834 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2835 ") of multiclass '" + MC->Rec.getNameInitAsString() +
2836 "'");
2837 }
2838 TemplateArgs.insert({TArgs[i], Default});
2839 }
2840 }
2841
2842 // Loop over all the def's in the multiclass, instantiating each one.
2843 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2844 bool ResolveName = true;
2845 auto CurRec = make_unique<Record>(*DefProto);
2846 CurRec->appendLoc(SubClassLoc);
2847
2848 if (StringInit *NameString =
2849 dyn_cast<StringInit>(CurRec->getNameInit())) {
2850 // We have a fully expanded string so there are no operators to
2851 // resolve. We should concatenate the given prefix and name.
2852 //
2853 // TODO: This MUST happen before template argument resolution. This
2854 // does not make sense and should be changed, but at the time of
2855 // writing, there are existing .td files which rely on this
2856 // implementation detail. It's a bad idea and should be fixed.
2857 // See test/TableGen/name-resolution-consistency.td for some
2858 // examples.
2859 CurRec->setName(BinOpInit::getStrConcat(DefmName, NameString));
2860 ResolveName = false;
2861 }
2862
2863 MapResolver R(CurRec.get());
2864
2865 if (ResolveName) {
2866 // If the proto's name wasn't resolved, we probably have a reference to
2867 // NAME and need to replace it.
2868 //
2869 // TODO: Whether the name is resolved is basically determined by magic.
2870 // Unfortunately, existing .td files depend on it.
2871 R.set(StringInit::get("NAME"), DefmName);
2872 }
2873
2874 for (const auto &TArg : TemplateArgs)
2875 R.set(TArg.first, TArg.second);
2876
2877 CurRec->resolveReferences(R);
2878
2879 NewRecDefs.emplace_back(std::move(CurRec));
2880 }
2881
2882 if (Lex.getCode() != tgtok::comma) break;
2883 Lex.Lex(); // eat ','.
2884
2885 if (Lex.getCode() != tgtok::Id)
2886 return TokError("expected identifier");
2887
2888 SubClassLoc = Lex.getLoc();
2889
2890 // A defm can inherit from regular classes (non-multiclass) as
2891 // long as they come in the end of the inheritance list.
2892 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2893
2894 if (InheritFromClass)
2895 break;
2896
2897 Ref = ParseSubClassReference(nullptr, true);
2898 }
2899
2900 if (InheritFromClass) {
2901 // Process all the classes to inherit as if they were part of a
2902 // regular 'def' and inherit all record values.
2903 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2904 while (true) {
2905 // Check for error.
2906 if (!SubClass.Rec) return true;
2907
2908 // Get the expanded definition prototypes and teach them about
2909 // the record values the current class to inherit has
2910 for (const auto &CurRec : NewRecDefs) {
2911 // Add it.
2912 if (AddSubClass(CurRec.get(), SubClass))
2913 return true;
2914 }
2915
2916 if (Lex.getCode() != tgtok::comma) break;
2917 Lex.Lex(); // eat ','.
2918 SubClass = ParseSubClassReference(nullptr, false);
2919 }
2920 }
2921
2922 for (auto &CurRec : NewRecDefs) {
2923 if (ApplyLetStack(CurRec.get()))
2924 return true;
2925
2926 addDef(std::move(CurRec), DefmName);
2927 }
2928
2929 if (Lex.getCode() != tgtok::semi)
2930 return TokError("expected ';' at end of defm");
2931 Lex.Lex();
2932
2933 return false;
2934}
2935
2936/// ParseObject
2937/// Object ::= ClassInst
2938/// Object ::= DefInst
2939/// Object ::= MultiClassInst
2940/// Object ::= DefMInst
2941/// Object ::= LETCommand '{' ObjectList '}'
2942/// Object ::= LETCommand Object
2943bool TGParser::ParseObject(MultiClass *MC) {
2944 switch (Lex.getCode()) {
4
Control jumps to 'case Class:' at line 2956
2945 default:
2946 return TokError("Expected class, def, defm, defset, multiclass, let or "
2947 "foreach");
2948 case tgtok::Let: return ParseTopLevelLet(MC);
2949 case tgtok::Def: return ParseDef(MC);
2950 case tgtok::Foreach: return ParseForeach(MC);
2951 case tgtok::Defm: return ParseDefm(MC);
2952 case tgtok::Defset:
2953 if (MC)
2954 return TokError("defset is not allowed inside multiclass");
2955 return ParseDefset();
2956 case tgtok::Class:
2957 if (MC)
5
Taking false branch
2958 return TokError("class is not allowed inside multiclass");
2959 if (!Loops.empty())
6
Assuming the condition is false
7
Taking false branch
2960 return TokError("class is not allowed inside foreach loop");
2961 return ParseClass();
8
Calling 'TGParser::ParseClass'
2962 case tgtok::MultiClass:
2963 if (!Loops.empty())
2964 return TokError("multiclass is not allowed inside foreach loop");
2965 return ParseMultiClass();
2966 }
2967}
2968
2969/// ParseObjectList
2970/// ObjectList :== Object*
2971bool TGParser::ParseObjectList(MultiClass *MC) {
2972 while (isObjectStart(Lex.getCode())) {
2
Loop condition is true. Entering loop body
2973 if (ParseObject(MC))
3
Calling 'TGParser::ParseObject'
2974 return true;
2975 }
2976 return false;
2977}
2978
2979bool TGParser::ParseFile() {
2980 Lex.Lex(); // Prime the lexer.
2981 if (ParseObjectList()) return true;
1
Calling 'TGParser::ParseObjectList'
2982
2983 // If we have unread input at the end of the file, report it.
2984 if (Lex.getCode() == tgtok::Eof)
2985 return false;
2986
2987 return TokError("Unexpected input at top level");
2988}

/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <functional>
62//===----------------------------------------------------------------------===//
63
64template <class Ty> struct identity {
65 using argument_type = Ty;
66
67 Ty &operator()(Ty &self) const {
68 return self;
69 }
70 const Ty &operator()(const Ty &self) const {
71 return self;
72 }
73};
74
75template <class Ty> struct less_ptr {
76 bool operator()(const Ty* left, const Ty* right) const {
77 return *left < *right;
78 }
79};
80
81template <class Ty> struct greater_ptr {
82 bool operator()(const Ty* left, const Ty* right) const {
83 return *right < *left;
84 }
85};
86
87/// An efficient, type-erasing, non-owning reference to a callable. This is
88/// intended for use as the type of a function parameter that is not used
89/// after the function in question returns.
90///
91/// This class does not own the callable, so it is not in general safe to store
92/// a function_ref.
93template<typename Fn> class function_ref;
94
95template<typename Ret, typename ...Params>
96class function_ref<Ret(Params...)> {
97 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
98 intptr_t callable;
99
100 template<typename Callable>
101 static Ret callback_fn(intptr_t callable, Params ...params) {
102 return (*reinterpret_cast<Callable*>(callable))(
103 std::forward<Params>(params)...);
104 }
105
106public:
107 function_ref() = default;
108 function_ref(std::nullptr_t) {}
109
110 template <typename Callable>
111 function_ref(Callable &&callable,
112 typename std::enable_if<
113 !std::is_same<typename std::remove_reference<Callable>::type,
114 function_ref>::value>::type * = nullptr)
115 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
116 callable(reinterpret_cast<intptr_t>(&callable)) {}
117
118 Ret operator()(Params ...params) const {
119 return callback(callable, std::forward<Params>(params)...);
120 }
121
122 operator bool() const { return callback; }
123};
124
125// deleter - Very very very simple method that is used to invoke operator
126// delete on something. It is used like this:
127//
128// for_each(V.begin(), B.end(), deleter<Interval>);
129template <class T>
130inline void deleter(T *Ptr) {
131 delete Ptr;
132}
133
134//===----------------------------------------------------------------------===//
135// Extra additions to <iterator>
136//===----------------------------------------------------------------------===//
137
138namespace adl_detail {
139
140using std::begin;
141
142template <typename ContainerTy>
143auto adl_begin(ContainerTy &&container)
144 -> decltype(begin(std::forward<ContainerTy>(container))) {
145 return begin(std::forward<ContainerTy>(container));
146}
147
148using std::end;
149
150template <typename ContainerTy>
151auto adl_end(ContainerTy &&container)
152 -> decltype(end(std::forward<ContainerTy>(container))) {
153 return end(std::forward<ContainerTy>(container));
154}
155
156using std::swap;
157
158template <typename T>
159void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
160 std::declval<T>()))) {
161 swap(std::forward<T>(lhs), std::forward<T>(rhs));
162}
163
164} // end namespace adl_detail
165
166template <typename ContainerTy>
167auto adl_begin(ContainerTy &&container)
168 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
169 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
170}
171
172template <typename ContainerTy>
173auto adl_end(ContainerTy &&container)
174 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
175 return adl_detail::adl_end(std::forward<ContainerTy>(container));
176}
177
178template <typename T>
179void adl_swap(T &&lhs, T &&rhs) noexcept(
180 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
181 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
182}
183
184// mapped_iterator - This is a simple iterator adapter that causes a function to
185// be applied whenever operator* is invoked on the iterator.
186
187template <typename ItTy, typename FuncTy,
188 typename FuncReturnTy =
189 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
190class mapped_iterator
191 : public iterator_adaptor_base<
192 mapped_iterator<ItTy, FuncTy>, ItTy,
193 typename std::iterator_traits<ItTy>::iterator_category,
194 typename std::remove_reference<FuncReturnTy>::type> {
195public:
196 mapped_iterator(ItTy U, FuncTy F)
197 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
198
199 ItTy getCurrent() { return this->I; }
200
201 FuncReturnTy operator*() { return F(*this->I); }
202
203private:
204 FuncTy F;
205};
206
207// map_iterator - Provide a convenient way to create mapped_iterators, just like
208// make_pair is useful for creating pairs...
209template <class ItTy, class FuncTy>
210inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
211 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
212}
213
214/// Helper to determine if type T has a member called rbegin().
215template <typename Ty> class has_rbegin_impl {
216 using yes = char[1];
217 using no = char[2];
218
219 template <typename Inner>
220 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
221
222 template <typename>
223 static no& test(...);
224
225public:
226 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
227};
228
229/// Metafunction to determine if T& or T has a member called rbegin().
230template <typename Ty>
231struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
232};
233
234// Returns an iterator_range over the given container which iterates in reverse.
235// Note that the container must have rbegin()/rend() methods for this to work.
236template <typename ContainerTy>
237auto reverse(ContainerTy &&C,
238 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
239 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
240 return make_range(C.rbegin(), C.rend());
241}
242
243// Returns a std::reverse_iterator wrapped around the given iterator.
244template <typename IteratorTy>
245std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
246 return std::reverse_iterator<IteratorTy>(It);
247}
248
249// Returns an iterator_range over the given container which iterates in reverse.
250// Note that the container must have begin()/end() methods which return
251// bidirectional iterators for this to work.
252template <typename ContainerTy>
253auto reverse(
254 ContainerTy &&C,
255 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
256 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
257 llvm::make_reverse_iterator(std::begin(C)))) {
258 return make_range(llvm::make_reverse_iterator(std::end(C)),
259 llvm::make_reverse_iterator(std::begin(C)));
260}
261
262/// An iterator adaptor that filters the elements of given inner iterators.
263///
264/// The predicate parameter should be a callable object that accepts the wrapped
265/// iterator's reference type and returns a bool. When incrementing or
266/// decrementing the iterator, it will call the predicate on each element and
267/// skip any where it returns false.
268///
269/// \code
270/// int A[] = { 1, 2, 3, 4 };
271/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
272/// // R contains { 1, 3 }.
273/// \endcode
274template <typename WrappedIteratorT, typename PredicateT>
275class filter_iterator
276 : public iterator_adaptor_base<
277 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
278 typename std::common_type<
279 std::forward_iterator_tag,
280 typename std::iterator_traits<
281 WrappedIteratorT>::iterator_category>::type> {
282 using BaseT = iterator_adaptor_base<
283 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
284 typename std::common_type<
285 std::forward_iterator_tag,
286 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
287 type>;
288
289 struct PayloadType {
290 WrappedIteratorT End;
291 PredicateT Pred;
292 };
293
294 Optional<PayloadType> Payload;
295
296 void findNextValid() {
297 assert(Payload && "Payload should be engaged when findNextValid is called")(static_cast <bool> (Payload && "Payload should be engaged when findNextValid is called"
) ? void (0) : __assert_fail ("Payload && \"Payload should be engaged when findNextValid is called\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298 while (this->I != Payload->End && !Payload->Pred(*this->I))
299 BaseT::operator++();
300 }
301
302 // Construct the begin iterator. The begin iterator requires to know where end
303 // is, so that it can properly stop when it hits end.
304 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
305 : BaseT(std::move(Begin)),
306 Payload(PayloadType{std::move(End), std::move(Pred)}) {
307 findNextValid();
308 }
309
310 // Construct the end iterator. It's not incrementable, so Payload doesn't
311 // have to be engaged.
312 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
313
314public:
315 using BaseT::operator++;
316
317 filter_iterator &operator++() {
318 BaseT::operator++();
319 findNextValid();
320 return *this;
321 }
322
323 template <typename RT, typename PT>
324 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
325 make_filter_range(RT &&, PT);
326};
327
328/// Convenience function that takes a range of elements and a predicate,
329/// and return a new filter_iterator range.
330///
331/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
332/// lifetime of that temporary is not kept by the returned range object, and the
333/// temporary is going to be dropped on the floor after the make_iterator_range
334/// full expression that contains this function call.
335template <typename RangeT, typename PredicateT>
336iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
337make_filter_range(RangeT &&Range, PredicateT Pred) {
338 using FilterIteratorT =
339 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
340 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
341 std::end(std::forward<RangeT>(Range)),
342 std::move(Pred)),
343 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
344}
345
346// forward declarations required by zip_shortest/zip_first
347template <typename R, typename UnaryPredicate>
348bool all_of(R &&range, UnaryPredicate P);
349
350template <size_t... I> struct index_sequence;
351
352template <class... Ts> struct index_sequence_for;
353
354namespace detail {
355
356using std::declval;
357
358// We have to alias this since inlining the actual type at the usage site
359// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
360template<typename... Iters> struct ZipTupleType {
361 using type = std::tuple<decltype(*declval<Iters>())...>;
362};
363
364template <typename ZipType, typename... Iters>
365using zip_traits = iterator_facade_base<
366 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
367 typename std::iterator_traits<
368 Iters>::iterator_category...>::type,
369 // ^ TODO: Implement random access methods.
370 typename ZipTupleType<Iters...>::type,
371 typename std::iterator_traits<typename std::tuple_element<
372 0, std::tuple<Iters...>>::type>::difference_type,
373 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
374 // inner iterators have the same difference_type. It would fail if, for
375 // instance, the second field's difference_type were non-numeric while the
376 // first is.
377 typename ZipTupleType<Iters...>::type *,
378 typename ZipTupleType<Iters...>::type>;
379
380template <typename ZipType, typename... Iters>
381struct zip_common : public zip_traits<ZipType, Iters...> {
382 using Base = zip_traits<ZipType, Iters...>;
383 using value_type = typename Base::value_type;
384
385 std::tuple<Iters...> iterators;
386
387protected:
388 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
389 return value_type(*std::get<Ns>(iterators)...);
390 }
391
392 template <size_t... Ns>
393 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
394 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
395 }
396
397 template <size_t... Ns>
398 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
399 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
400 }
401
402public:
403 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
404
405 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
406
407 const value_type operator*() const {
408 return deref(index_sequence_for<Iters...>{});
409 }
410
411 ZipType &operator++() {
412 iterators = tup_inc(index_sequence_for<Iters...>{});
413 return *reinterpret_cast<ZipType *>(this);
414 }
415
416 ZipType &operator--() {
417 static_assert(Base::IsBidirectional,
418 "All inner iterators must be at least bidirectional.");
419 iterators = tup_dec(index_sequence_for<Iters...>{});
420 return *reinterpret_cast<ZipType *>(this);
421 }
422};
423
424template <typename... Iters>
425struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
426 using Base = zip_common<zip_first<Iters...>, Iters...>;
427
428 bool operator==(const zip_first<Iters...> &other) const {
429 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
430 }
431
432 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
433};
434
435template <typename... Iters>
436class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
437 template <size_t... Ns>
438 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
439 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
440 std::get<Ns>(other.iterators)...},
441 identity<bool>{});
442 }
443
444public:
445 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
446
447 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
448
449 bool operator==(const zip_shortest<Iters...> &other) const {
450 return !test(other, index_sequence_for<Iters...>{});
451 }
452};
453
454template <template <typename...> class ItType, typename... Args> class zippy {
455public:
456 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
457 using iterator_category = typename iterator::iterator_category;
458 using value_type = typename iterator::value_type;
459 using difference_type = typename iterator::difference_type;
460 using pointer = typename iterator::pointer;
461 using reference = typename iterator::reference;
462
463private:
464 std::tuple<Args...> ts;
465
466 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
467 return iterator(std::begin(std::get<Ns>(ts))...);
468 }
469 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
470 return iterator(std::end(std::get<Ns>(ts))...);
471 }
472
473public:
474 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
475
476 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
477 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
478};
479
480} // end namespace detail
481
482/// zip iterator for two or more iteratable types.
483template <typename T, typename U, typename... Args>
484detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
485 Args &&... args) {
486 return detail::zippy<detail::zip_shortest, T, U, Args...>(
487 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
488}
489
490/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
491/// be the shortest.
492template <typename T, typename U, typename... Args>
493detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
494 Args &&... args) {
495 return detail::zippy<detail::zip_first, T, U, Args...>(
496 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
497}
498
499/// Iterator wrapper that concatenates sequences together.
500///
501/// This can concatenate different iterators, even with different types, into
502/// a single iterator provided the value types of all the concatenated
503/// iterators expose `reference` and `pointer` types that can be converted to
504/// `ValueT &` and `ValueT *` respectively. It doesn't support more
505/// interesting/customized pointer or reference types.
506///
507/// Currently this only supports forward or higher iterator categories as
508/// inputs and always exposes a forward iterator interface.
509template <typename ValueT, typename... IterTs>
510class concat_iterator
511 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
512 std::forward_iterator_tag, ValueT> {
513 using BaseT = typename concat_iterator::iterator_facade_base;
514
515 /// We store both the current and end iterators for each concatenated
516 /// sequence in a tuple of pairs.
517 ///
518 /// Note that something like iterator_range seems nice at first here, but the
519 /// range properties are of little benefit and end up getting in the way
520 /// because we need to do mutation on the current iterators.
521 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
522
523 /// Attempts to increment a specific iterator.
524 ///
525 /// Returns true if it was able to increment the iterator. Returns false if
526 /// the iterator is already at the end iterator.
527 template <size_t Index> bool incrementHelper() {
528 auto &IterPair = std::get<Index>(IterPairs);
529 if (IterPair.first == IterPair.second)
530 return false;
531
532 ++IterPair.first;
533 return true;
534 }
535
536 /// Increments the first non-end iterator.
537 ///
538 /// It is an error to call this with all iterators at the end.
539 template <size_t... Ns> void increment(index_sequence<Ns...>) {
540 // Build a sequence of functions to increment each iterator if possible.
541 bool (concat_iterator::*IncrementHelperFns[])() = {
542 &concat_iterator::incrementHelper<Ns>...};
543
544 // Loop over them, and stop as soon as we succeed at incrementing one.
545 for (auto &IncrementHelperFn : IncrementHelperFns)
546 if ((this->*IncrementHelperFn)())
547 return;
548
549 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 549)
;
550 }
551
552 /// Returns null if the specified iterator is at the end. Otherwise,
553 /// dereferences the iterator and returns the address of the resulting
554 /// reference.
555 template <size_t Index> ValueT *getHelper() const {
556 auto &IterPair = std::get<Index>(IterPairs);
557 if (IterPair.first == IterPair.second)
558 return nullptr;
559
560 return &*IterPair.first;
561 }
562
563 /// Finds the first non-end iterator, dereferences, and returns the resulting
564 /// reference.
565 ///
566 /// It is an error to call this with all iterators at the end.
567 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
568 // Build a sequence of functions to get from iterator if possible.
569 ValueT *(concat_iterator::*GetHelperFns[])() const = {
570 &concat_iterator::getHelper<Ns>...};
571
572 // Loop over them, and return the first result we find.
573 for (auto &GetHelperFn : GetHelperFns)
574 if (ValueT *P = (this->*GetHelperFn)())
575 return *P;
576
577 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 577)
;
578 }
579
580public:
581 /// Constructs an iterator from a squence of ranges.
582 ///
583 /// We need the full range to know how to switch between each of the
584 /// iterators.
585 template <typename... RangeTs>
586 explicit concat_iterator(RangeTs &&... Ranges)
587 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
588
589 using BaseT::operator++;
590
591 concat_iterator &operator++() {
592 increment(index_sequence_for<IterTs...>());
593 return *this;
594 }
595
596 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
597
598 bool operator==(const concat_iterator &RHS) const {
599 return IterPairs == RHS.IterPairs;
600 }
601};
602
603namespace detail {
604
605/// Helper to store a sequence of ranges being concatenated and access them.
606///
607/// This is designed to facilitate providing actual storage when temporaries
608/// are passed into the constructor such that we can use it as part of range
609/// based for loops.
610template <typename ValueT, typename... RangeTs> class concat_range {
611public:
612 using iterator =
613 concat_iterator<ValueT,
614 decltype(std::begin(std::declval<RangeTs &>()))...>;
615
616private:
617 std::tuple<RangeTs...> Ranges;
618
619 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
620 return iterator(std::get<Ns>(Ranges)...);
621 }
622 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
623 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
624 std::end(std::get<Ns>(Ranges)))...);
625 }
626
627public:
628 concat_range(RangeTs &&... Ranges)
629 : Ranges(std::forward<RangeTs>(Ranges)...) {}
630
631 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
632 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
633};
634
635} // end namespace detail
636
637/// Concatenated range across two or more ranges.
638///
639/// The desired value type must be explicitly specified.
640template <typename ValueT, typename... RangeTs>
641detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
642 static_assert(sizeof...(RangeTs) > 1,
643 "Need more than one range to concatenate!");
644 return detail::concat_range<ValueT, RangeTs...>(
645 std::forward<RangeTs>(Ranges)...);
646}
647
648//===----------------------------------------------------------------------===//
649// Extra additions to <utility>
650//===----------------------------------------------------------------------===//
651
652/// \brief Function object to check whether the first component of a std::pair
653/// compares less than the first component of another std::pair.
654struct less_first {
655 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
656 return lhs.first < rhs.first;
657 }
658};
659
660/// \brief Function object to check whether the second component of a std::pair
661/// compares less than the second component of another std::pair.
662struct less_second {
663 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
664 return lhs.second < rhs.second;
665 }
666};
667
668// A subset of N3658. More stuff can be added as-needed.
669
670/// \brief Represents a compile-time sequence of integers.
671template <class T, T... I> struct integer_sequence {
672 using value_type = T;
673
674 static constexpr size_t size() { return sizeof...(I); }
675};
676
677/// \brief Alias for the common case of a sequence of size_ts.
678template <size_t... I>
679struct index_sequence : integer_sequence<std::size_t, I...> {};
680
681template <std::size_t N, std::size_t... I>
682struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
683template <std::size_t... I>
684struct build_index_impl<0, I...> : index_sequence<I...> {};
685
686/// \brief Creates a compile-time integer sequence for a parameter pack.
687template <class... Ts>
688struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
689
690/// Utility type to build an inheritance chain that makes it easy to rank
691/// overload candidates.
692template <int N> struct rank : rank<N - 1> {};
693template <> struct rank<0> {};
694
695/// \brief traits class for checking whether type T is one of any of the given
696/// types in the variadic list.
697template <typename T, typename... Ts> struct is_one_of {
698 static const bool value = false;
699};
700
701template <typename T, typename U, typename... Ts>
702struct is_one_of<T, U, Ts...> {
703 static const bool value =
704 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
705};
706
707/// \brief traits class for checking whether type T is a base class for all
708/// the given types in the variadic list.
709template <typename T, typename... Ts> struct are_base_of {
710 static const bool value = true;
711};
712
713template <typename T, typename U, typename... Ts>
714struct are_base_of<T, U, Ts...> {
715 static const bool value =
716 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
717};
718
719//===----------------------------------------------------------------------===//
720// Extra additions for arrays
721//===----------------------------------------------------------------------===//
722
723/// Find the length of an array.
724template <class T, std::size_t N>
725constexpr inline size_t array_lengthof(T (&)[N]) {
726 return N;
727}
728
729/// Adapt std::less<T> for array_pod_sort.
730template<typename T>
731inline int array_pod_sort_comparator(const void *P1, const void *P2) {
732 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
733 *reinterpret_cast<const T*>(P2)))
734 return -1;
735 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
736 *reinterpret_cast<const T*>(P1)))
737 return 1;
738 return 0;
739}
740
741/// get_array_pod_sort_comparator - This is an internal helper function used to
742/// get type deduction of T right.
743template<typename T>
744inline int (*get_array_pod_sort_comparator(const T &))
745 (const void*, const void*) {
746 return array_pod_sort_comparator<T>;
747}
748
749/// array_pod_sort - This sorts an array with the specified start and end
750/// extent. This is just like std::sort, except that it calls qsort instead of
751/// using an inlined template. qsort is slightly slower than std::sort, but
752/// most sorts are not performance critical in LLVM and std::sort has to be
753/// template instantiated for each type, leading to significant measured code
754/// bloat. This function should generally be used instead of std::sort where
755/// possible.
756///
757/// This function assumes that you have simple POD-like types that can be
758/// compared with std::less and can be moved with memcpy. If this isn't true,
759/// you should use std::sort.
760///
761/// NOTE: If qsort_r were portable, we could allow a custom comparator and
762/// default to std::less.
763template<class IteratorTy>
764inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
765 // Don't inefficiently call qsort with one element or trigger undefined
766 // behavior with an empty sequence.
767 auto NElts = End - Start;
768 if (NElts <= 1) return;
769#ifdef EXPENSIVE_CHECKS
770 std::mt19937 Generator(std::random_device{}());
771 std::shuffle(Start, End, Generator);
772#endif
773 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
774}
775
776template <class IteratorTy>
777inline void array_pod_sort(
778 IteratorTy Start, IteratorTy End,
779 int (*Compare)(
780 const typename std::iterator_traits<IteratorTy>::value_type *,
781 const typename std::iterator_traits<IteratorTy>::value_type *)) {
782 // Don't inefficiently call qsort with one element or trigger undefined
783 // behavior with an empty sequence.
784 auto NElts = End - Start;
785 if (NElts <= 1) return;
786#ifdef EXPENSIVE_CHECKS
787 std::mt19937 Generator(std::random_device{}());
788 std::shuffle(Start, End, Generator);
789#endif
790 qsort(&*Start, NElts, sizeof(*Start),
791 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
792}
793
794// Provide wrappers to std::sort which shuffle the elements before sorting
795// to help uncover non-deterministic behavior (PR35135).
796template <typename IteratorTy>
797inline void sort(IteratorTy Start, IteratorTy End) {
798#ifdef EXPENSIVE_CHECKS
799 std::mt19937 Generator(std::random_device{}());
800 std::shuffle(Start, End, Generator);
801#endif
802 std::sort(Start, End);
803}
804
805template <typename IteratorTy, typename Compare>
806inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
807#ifdef EXPENSIVE_CHECKS
808 std::mt19937 Generator(std::random_device{}());
809 std::shuffle(Start, End, Generator);
810#endif
811 std::sort(Start, End, Comp);
812}
813
814//===----------------------------------------------------------------------===//
815// Extra additions to <algorithm>
816//===----------------------------------------------------------------------===//
817
818/// For a container of pointers, deletes the pointers and then clears the
819/// container.
820template<typename Container>
821void DeleteContainerPointers(Container &C) {
822 for (auto V : C)
823 delete V;
824 C.clear();
825}
826
827/// In a container of pairs (usually a map) whose second element is a pointer,
828/// deletes the second elements and then clears the container.
829template<typename Container>
830void DeleteContainerSeconds(Container &C) {
831 for (auto &V : C)
832 delete V.second;
833 C.clear();
834}
835
836/// Provide wrappers to std::for_each which take ranges instead of having to
837/// pass begin/end explicitly.
838template <typename R, typename UnaryPredicate>
839UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
840 return std::for_each(adl_begin(Range), adl_end(Range), P);
841}
842
843/// Provide wrappers to std::all_of which take ranges instead of having to pass
844/// begin/end explicitly.
845template <typename R, typename UnaryPredicate>
846bool all_of(R &&Range, UnaryPredicate P) {
847 return std::all_of(adl_begin(Range), adl_end(Range), P);
848}
849
850/// Provide wrappers to std::any_of which take ranges instead of having to pass
851/// begin/end explicitly.
852template <typename R, typename UnaryPredicate>
853bool any_of(R &&Range, UnaryPredicate P) {
854 return std::any_of(adl_begin(Range), adl_end(Range), P);
855}
856
857/// Provide wrappers to std::none_of which take ranges instead of having to pass
858/// begin/end explicitly.
859template <typename R, typename UnaryPredicate>
860bool none_of(R &&Range, UnaryPredicate P) {
861 return std::none_of(adl_begin(Range), adl_end(Range), P);
862}
863
864/// Provide wrappers to std::find which take ranges instead of having to pass
865/// begin/end explicitly.
866template <typename R, typename T>
867auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
868 return std::find(adl_begin(Range), adl_end(Range), Val);
869}
870
871/// Provide wrappers to std::find_if which take ranges instead of having to pass
872/// begin/end explicitly.
873template <typename R, typename UnaryPredicate>
874auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
875 return std::find_if(adl_begin(Range), adl_end(Range), P);
876}
877
878template <typename R, typename UnaryPredicate>
879auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
880 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
881}
882
883/// Provide wrappers to std::remove_if which take ranges instead of having to
884/// pass begin/end explicitly.
885template <typename R, typename UnaryPredicate>
886auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
887 return std::remove_if(adl_begin(Range), adl_end(Range), P);
888}
889
890/// Provide wrappers to std::copy_if which take ranges instead of having to
891/// pass begin/end explicitly.
892template <typename R, typename OutputIt, typename UnaryPredicate>
893OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
894 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
895}
896
897template <typename R, typename OutputIt>
898OutputIt copy(R &&Range, OutputIt Out) {
899 return std::copy(adl_begin(Range), adl_end(Range), Out);
900}
901
902/// Wrapper function around std::find to detect if an element exists
903/// in a container.
904template <typename R, typename E>
905bool is_contained(R &&Range, const E &Element) {
906 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
907}
908
909/// Wrapper function around std::count to count the number of times an element
910/// \p Element occurs in the given range \p Range.
911template <typename R, typename E>
912auto count(R &&Range, const E &Element) ->
913 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
914 return std::count(adl_begin(Range), adl_end(Range), Element);
915}
916
917/// Wrapper function around std::count_if to count the number of times an
918/// element satisfying a given predicate occurs in a range.
919template <typename R, typename UnaryPredicate>
920auto count_if(R &&Range, UnaryPredicate P) ->
921 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
922 return std::count_if(adl_begin(Range), adl_end(Range), P);
923}
924
925/// Wrapper function around std::transform to apply a function to a range and
926/// store the result elsewhere.
927template <typename R, typename OutputIt, typename UnaryPredicate>
928OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
929 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
930}
931
932/// Provide wrappers to std::partition which take ranges instead of having to
933/// pass begin/end explicitly.
934template <typename R, typename UnaryPredicate>
935auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
936 return std::partition(adl_begin(Range), adl_end(Range), P);
937}
938
939/// Provide wrappers to std::lower_bound which take ranges instead of having to
940/// pass begin/end explicitly.
941template <typename R, typename ForwardIt>
942auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
943 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
944}
945
946/// \brief Given a range of type R, iterate the entire range and return a
947/// SmallVector with elements of the vector. This is useful, for example,
948/// when you want to iterate a range and then sort the results.
949template <unsigned Size, typename R>
950SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
951to_vector(R &&Range) {
952 return {adl_begin(Range), adl_end(Range)};
953}
954
955/// Provide a container algorithm similar to C++ Library Fundamentals v2's
956/// `erase_if` which is equivalent to:
957///
958/// C.erase(remove_if(C, pred), C.end());
959///
960/// This version works for any container with an erase method call accepting
961/// two iterators.
962template <typename Container, typename UnaryPredicate>
963void erase_if(Container &C, UnaryPredicate P) {
964 C.erase(remove_if(C, P), C.end());
965}
966
967//===----------------------------------------------------------------------===//
968// Extra additions to <memory>
969//===----------------------------------------------------------------------===//
970
971// Implement make_unique according to N3656.
972
973/// \brief Constructs a `new T()` with the given args and returns a
974/// `unique_ptr<T>` which owns the object.
975///
976/// Example:
977///
978/// auto p = make_unique<int>();
979/// auto p = make_unique<std::tuple<int, int>>(0, 1);
980template <class T, class... Args>
981typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
982make_unique(Args &&... args) {
983 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
13
Memory is allocated
984}
985
986/// \brief Constructs a `new T[n]` with the given args and returns a
987/// `unique_ptr<T[]>` which owns the object.
988///
989/// \param n size of the new array.
990///
991/// Example:
992///
993/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
994template <class T>
995typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
996 std::unique_ptr<T>>::type
997make_unique(size_t n) {
998 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
999}
1000
1001/// This function isn't used and is only here to provide better compile errors.
1002template <class T, class... Args>
1003typename std::enable_if<std::extent<T>::value != 0>::type
1004make_unique(Args &&...) = delete;
1005
1006struct FreeDeleter {
1007 void operator()(void* v) {
1008 ::free(v);
1009 }
1010};
1011
1012template<typename First, typename Second>
1013struct pair_hash {
1014 size_t operator()(const std::pair<First, Second> &P) const {
1015 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1016 }
1017};
1018
1019/// A functor like C++14's std::less<void> in its absence.
1020struct less {
1021 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1022 return std::forward<A>(a) < std::forward<B>(b);
1023 }
1024};
1025
1026/// A functor like C++14's std::equal<void> in its absence.
1027struct equal {
1028 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1029 return std::forward<A>(a) == std::forward<B>(b);
1030 }
1031};
1032
1033/// Binary functor that adapts to any other binary functor after dereferencing
1034/// operands.
1035template <typename T> struct deref {
1036 T func;
1037
1038 // Could be further improved to cope with non-derivable functors and
1039 // non-binary functors (should be a variadic template member function
1040 // operator()).
1041 template <typename A, typename B>
1042 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1043 assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1043, __extension__ __PRETTY_FUNCTION__))
;
1044 assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1044, __extension__ __PRETTY_FUNCTION__))
;
1045 return func(*lhs, *rhs);
1046 }
1047};
1048
1049namespace detail {
1050
1051template <typename R> class enumerator_iter;
1052
1053template <typename R> struct result_pair {
1054 friend class enumerator_iter<R>;
1055
1056 result_pair() = default;
1057 result_pair(std::size_t Index, IterOfRange<R> Iter)
1058 : Index(Index), Iter(Iter) {}
1059
1060 result_pair<R> &operator=(const result_pair<R> &Other) {
1061 Index = Other.Index;
1062 Iter = Other.Iter;
1063 return *this;
1064 }
1065
1066 std::size_t index() const { return Index; }
1067 const ValueOfRange<R> &value() const { return *Iter; }
1068 ValueOfRange<R> &value() { return *Iter; }
1069
1070private:
1071 std::size_t Index = std::numeric_limits<std::size_t>::max();
1072 IterOfRange<R> Iter;
1073};
1074
1075template <typename R>
1076class enumerator_iter
1077 : public iterator_facade_base<
1078 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1079 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1080 typename std::iterator_traits<IterOfRange<R>>::pointer,
1081 typename std::iterator_traits<IterOfRange<R>>::reference> {
1082 using result_type = result_pair<R>;
1083
1084public:
1085 explicit enumerator_iter(IterOfRange<R> EndIter)
1086 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1087
1088 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1089 : Result(Index, Iter) {}
1090
1091 result_type &operator*() { return Result; }
1092 const result_type &operator*() const { return Result; }
1093
1094 enumerator_iter<R> &operator++() {
1095 assert(Result.Index != std::numeric_limits<size_t>::max())(static_cast <bool> (Result.Index != std::numeric_limits
<size_t>::max()) ? void (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1095, __extension__ __PRETTY_FUNCTION__))
;
1096 ++Result.Iter;
1097 ++Result.Index;
1098 return *this;
1099 }
1100
1101 bool operator==(const enumerator_iter<R> &RHS) const {
1102 // Don't compare indices here, only iterators. It's possible for an end
1103 // iterator to have different indices depending on whether it was created
1104 // by calling std::end() versus incrementing a valid iterator.
1105 return Result.Iter == RHS.Result.Iter;
1106 }
1107
1108 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1109 Result = Other.Result;
1110 return *this;
1111 }
1112
1113private:
1114 result_type Result;
1115};
1116
1117template <typename R> class enumerator {
1118public:
1119 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1120
1121 enumerator_iter<R> begin() {
1122 return enumerator_iter<R>(0, std::begin(TheRange));
1123 }
1124
1125 enumerator_iter<R> end() {
1126 return enumerator_iter<R>(std::end(TheRange));
1127 }
1128
1129private:
1130 R TheRange;
1131};
1132
1133} // end namespace detail
1134
1135/// Given an input range, returns a new range whose values are are pair (A,B)
1136/// such that A is the 0-based index of the item in the sequence, and B is
1137/// the value from the original sequence. Example:
1138///
1139/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1140/// for (auto X : enumerate(Items)) {
1141/// printf("Item %d - %c\n", X.index(), X.value());
1142/// }
1143///
1144/// Output:
1145/// Item 0 - A
1146/// Item 1 - B
1147/// Item 2 - C
1148/// Item 3 - D
1149///
1150template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1151 return detail::enumerator<R>(std::forward<R>(TheRange));
1152}
1153
1154namespace detail {
1155
1156template <typename F, typename Tuple, std::size_t... I>
1157auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1158 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1159 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1160}
1161
1162} // end namespace detail
1163
1164/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1165/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1166/// return the result.
1167template <typename F, typename Tuple>
1168auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1169 std::forward<F>(f), std::forward<Tuple>(t),
1170 build_index_impl<
1171 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1172 using Indices = build_index_impl<
1173 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1174
1175 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1176 Indices{});
1177}
1178
1179} // end namespace llvm
1180
1181#endif // LLVM_ADT_STLEXTRAS_H

/usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/unique_ptr.h

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2017 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/unique_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _UNIQUE_PTR_H1
31#define _UNIQUE_PTR_H1 1
32
33#include <bits/c++config.h>
34#include <debug/assertions.h>
35#include <type_traits>
36#include <utility>
37#include <tuple>
38#include <bits/stl_function.h>
39#include <bits/functional_hash.h>
40
41namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
42{
43_GLIBCXX_BEGIN_NAMESPACE_VERSION
44
45 /**
46 * @addtogroup pointer_abstractions
47 * @{
48 */
49
50#if _GLIBCXX_USE_DEPRECATED1
51 template<typename> class auto_ptr;
52#endif
53
54 /// Primary template of default_delete, used by unique_ptr
55 template<typename _Tp>
56 struct default_delete
57 {
58 /// Default constructor
59 constexpr default_delete() noexcept = default;
60
61 /** @brief Converting constructor.
62 *
63 * Allows conversion from a deleter for arrays of another type, @p _Up,
64 * only if @p _Up* is convertible to @p _Tp*.
65 */
66 template<typename _Up, typename = typename
67 enable_if<is_convertible<_Up*, _Tp*>::value>::type>
68 default_delete(const default_delete<_Up>&) noexcept { }
69
70 /// Calls @c delete @p __ptr
71 void
72 operator()(_Tp* __ptr) const
73 {
74 static_assert(!is_void<_Tp>::value,
75 "can't delete pointer to incomplete type");
76 static_assert(sizeof(_Tp)>0,
77 "can't delete pointer to incomplete type");
78 delete __ptr;
18
Memory is released
79 }
80 };
81
82 // _GLIBCXX_RESOLVE_LIB_DEFECTS
83 // DR 740 - omit specialization for array objects with a compile time length
84 /// Specialization for arrays, default_delete.
85 template<typename _Tp>
86 struct default_delete<_Tp[]>
87 {
88 public:
89 /// Default constructor
90 constexpr default_delete() noexcept = default;
91
92 /** @brief Converting constructor.
93 *
94 * Allows conversion from a deleter for arrays of another type, such as
95 * a const-qualified version of @p _Tp.
96 *
97 * Conversions from types derived from @c _Tp are not allowed because
98 * it is unsafe to @c delete[] an array of derived types through a
99 * pointer to the base type.
100 */
101 template<typename _Up, typename = typename
102 enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type>
103 default_delete(const default_delete<_Up[]>&) noexcept { }
104
105 /// Calls @c delete[] @p __ptr
106 template<typename _Up>
107 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
108 operator()(_Up* __ptr) const
109 {
110 static_assert(sizeof(_Tp)>0,
111 "can't delete pointer to incomplete type");
112 delete [] __ptr;
113 }
114 };
115
116 template <typename _Tp, typename _Dp>
117 class __uniq_ptr_impl
118 {
119 template <typename _Up, typename _Ep, typename = void>
120 struct _Ptr
121 {
122 using type = _Up*;
123 };
124
125 template <typename _Up, typename _Ep>
126 struct
127 _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>>
128 {
129 using type = typename remove_reference<_Ep>::type::pointer;
130 };
131
132 public:
133 using _DeleterConstraint = enable_if<
134 __and_<__not_<is_pointer<_Dp>>,
135 is_default_constructible<_Dp>>::value>;
136
137 using pointer = typename _Ptr<_Tp, _Dp>::type;
138
139 __uniq_ptr_impl() = default;
140 __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; }
141
142 template<typename _Del>
143 __uniq_ptr_impl(pointer __p, _Del&& __d)
144 : _M_t(__p, std::forward<_Del>(__d)) { }
145
146 pointer& _M_ptr() { return std::get<0>(_M_t); }
147 pointer _M_ptr() const { return std::get<0>(_M_t); }
148 _Dp& _M_deleter() { return std::get<1>(_M_t); }
149 const _Dp& _M_deleter() const { return std::get<1>(_M_t); }
150
151 private:
152 tuple<pointer, _Dp> _M_t;
153 };
154
155 /// 20.7.1.2 unique_ptr for single objects.
156 template <typename _Tp, typename _Dp = default_delete<_Tp>>
157 class unique_ptr
158 {
159 template <class _Up>
160 using _DeleterConstraint =
161 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
162
163 __uniq_ptr_impl<_Tp, _Dp> _M_t;
164
165 public:
166 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
167 using element_type = _Tp;
168 using deleter_type = _Dp;
169
170 // helper template for detecting a safe conversion from another
171 // unique_ptr
172 template<typename _Up, typename _Ep>
173 using __safe_conversion_up = __and_<
174 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
175 __not_<is_array<_Up>>,
176 __or_<__and_<is_reference<deleter_type>,
177 is_same<deleter_type, _Ep>>,
178 __and_<__not_<is_reference<deleter_type>>,
179 is_convertible<_Ep, deleter_type>>
180 >
181 >;
182
183 // Constructors.
184
185 /// Default constructor, creates a unique_ptr that owns nothing.
186 template <typename _Up = _Dp,
187 typename = _DeleterConstraint<_Up>>
188 constexpr unique_ptr() noexcept
189 : _M_t()
190 { }
191
192 /** Takes ownership of a pointer.
193 *
194 * @param __p A pointer to an object of @c element_type
195 *
196 * The deleter will be value-initialized.
197 */
198 template <typename _Up = _Dp,
199 typename = _DeleterConstraint<_Up>>
200 explicit
201 unique_ptr(pointer __p) noexcept
202 : _M_t(__p)
203 { }
204
205 /** Takes ownership of a pointer.
206 *
207 * @param __p A pointer to an object of @c element_type
208 * @param __d A reference to a deleter.
209 *
210 * The deleter will be initialized with @p __d
211 */
212 unique_ptr(pointer __p,
213 typename conditional<is_reference<deleter_type>::value,
214 deleter_type, const deleter_type&>::type __d) noexcept
215 : _M_t(__p, __d) { }
216
217 /** Takes ownership of a pointer.
218 *
219 * @param __p A pointer to an object of @c element_type
220 * @param __d An rvalue reference to a deleter.
221 *
222 * The deleter will be initialized with @p std::move(__d)
223 */
224 unique_ptr(pointer __p,
225 typename remove_reference<deleter_type>::type&& __d) noexcept
226 : _M_t(std::move(__p), std::move(__d))
227 { static_assert(!std::is_reference<deleter_type>::value,
228 "rvalue deleter bound to reference"); }
229
230 /// Creates a unique_ptr that owns nothing.
231 template <typename _Up = _Dp,
232 typename = _DeleterConstraint<_Up>>
233 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
234
235 // Move constructors.
236
237 /// Move constructor.
238 unique_ptr(unique_ptr&& __u) noexcept
239 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
240
241 /** @brief Converting constructor from another type
242 *
243 * Requires that the pointer owned by @p __u is convertible to the
244 * type of pointer owned by this object, @p __u does not own an array,
245 * and @p __u has a compatible deleter type.
246 */
247 template<typename _Up, typename _Ep, typename = _Require<
248 __safe_conversion_up<_Up, _Ep>,
249 typename conditional<is_reference<_Dp>::value,
250 is_same<_Ep, _Dp>,
251 is_convertible<_Ep, _Dp>>::type>>
252 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
253 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
254 { }
255
256#if _GLIBCXX_USE_DEPRECATED1
257 /// Converting constructor from @c auto_ptr
258 template<typename _Up, typename = _Require<
259 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
260 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
261#endif
262
263 /// Destructor, invokes the deleter if the stored pointer is not null.
264 ~unique_ptr() noexcept
265 {
266 auto& __ptr = _M_t._M_ptr();
267 if (__ptr != nullptr)
16
Taking true branch
268 get_deleter()(__ptr);
17
Calling 'default_delete::operator()'
19
Returning; memory was released via 2nd parameter
269 __ptr = pointer();
270 }
271
272 // Assignment.
273
274 /** @brief Move assignment operator.
275 *
276 * @param __u The object to transfer ownership from.
277 *
278 * Invokes the deleter first if this object owns a pointer.
279 */
280 unique_ptr&
281 operator=(unique_ptr&& __u) noexcept
282 {
283 reset(__u.release());
284 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
285 return *this;
286 }
287
288 /** @brief Assignment from another type.
289 *
290 * @param __u The object to transfer ownership from, which owns a
291 * convertible pointer to a non-array object.
292 *
293 * Invokes the deleter first if this object owns a pointer.
294 */
295 template<typename _Up, typename _Ep>
296 typename enable_if< __and_<
297 __safe_conversion_up<_Up, _Ep>,
298 is_assignable<deleter_type&, _Ep&&>
299 >::value,
300 unique_ptr&>::type
301 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
302 {
303 reset(__u.release());
304 get_deleter() = std::forward<_Ep>(__u.get_deleter());
305 return *this;
306 }
307
308 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
309 unique_ptr&
310 operator=(nullptr_t) noexcept
311 {
312 reset();
313 return *this;
314 }
315
316 // Observers.
317
318 /// Dereference the stored pointer.
319 typename add_lvalue_reference<element_type>::type
320 operator*() const
321 {
322 __glibcxx_assert(get() != pointer());
323 return *get();
324 }
325
326 /// Return the stored pointer.
327 pointer
328 operator->() const noexcept
329 {
330 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
331 return get();
332 }
333
334 /// Return the stored pointer.
335 pointer
336 get() const noexcept
337 { return _M_t._M_ptr(); }
338
339 /// Return a reference to the stored deleter.
340 deleter_type&
341 get_deleter() noexcept
342 { return _M_t._M_deleter(); }
343
344 /// Return a reference to the stored deleter.
345 const deleter_type&
346 get_deleter() const noexcept
347 { return _M_t._M_deleter(); }
348
349 /// Return @c true if the stored pointer is not null.
350 explicit operator bool() const noexcept
351 { return get() == pointer() ? false : true; }
352
353 // Modifiers.
354
355 /// Release ownership of any stored pointer.
356 pointer
357 release() noexcept
358 {
359 pointer __p = get();
360 _M_t._M_ptr() = pointer();
361 return __p;
362 }
363
364 /** @brief Replace the stored pointer.
365 *
366 * @param __p The new pointer to store.
367 *
368 * The deleter will be invoked if a pointer is already owned.
369 */
370 void
371 reset(pointer __p = pointer()) noexcept
372 {
373 using std::swap;
374 swap(_M_t._M_ptr(), __p);
375 if (__p != pointer())
376 get_deleter()(__p);
377 }
378
379 /// Exchange the pointer and deleter with another object.
380 void
381 swap(unique_ptr& __u) noexcept
382 {
383 using std::swap;
384 swap(_M_t, __u._M_t);
385 }
386
387 // Disable copy from lvalue.
388 unique_ptr(const unique_ptr&) = delete;
389 unique_ptr& operator=(const unique_ptr&) = delete;
390 };
391
392 /// 20.7.1.3 unique_ptr for array objects with a runtime length
393 // [unique.ptr.runtime]
394 // _GLIBCXX_RESOLVE_LIB_DEFECTS
395 // DR 740 - omit specialization for array objects with a compile time length
396 template<typename _Tp, typename _Dp>
397 class unique_ptr<_Tp[], _Dp>
398 {
399 template <typename _Up>
400 using _DeleterConstraint =
401 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
402
403 __uniq_ptr_impl<_Tp, _Dp> _M_t;
404
405 template<typename _Up>
406 using __remove_cv = typename remove_cv<_Up>::type;
407
408 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
409 template<typename _Up>
410 using __is_derived_Tp
411 = __and_< is_base_of<_Tp, _Up>,
412 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
413
414 public:
415 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
416 using element_type = _Tp;
417 using deleter_type = _Dp;
418
419 // helper template for detecting a safe conversion from another
420 // unique_ptr
421 template<typename _Up, typename _Ep,
422 typename _Up_up = unique_ptr<_Up, _Ep>,
423 typename _Up_element_type = typename _Up_up::element_type>
424 using __safe_conversion_up = __and_<
425 is_array<_Up>,
426 is_same<pointer, element_type*>,
427 is_same<typename _Up_up::pointer, _Up_element_type*>,
428 is_convertible<_Up_element_type(*)[], element_type(*)[]>,
429 __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>,
430 __and_<__not_<is_reference<deleter_type>>,
431 is_convertible<_Ep, deleter_type>>>
432 >;
433
434 // helper template for detecting a safe conversion from a raw pointer
435 template<typename _Up>
436 using __safe_conversion_raw = __and_<
437 __or_<__or_<is_same<_Up, pointer>,
438 is_same<_Up, nullptr_t>>,
439 __and_<is_pointer<_Up>,
440 is_same<pointer, element_type*>,
441 is_convertible<
442 typename remove_pointer<_Up>::type(*)[],
443 element_type(*)[]>
444 >
445 >
446 >;
447
448 // Constructors.
449
450 /// Default constructor, creates a unique_ptr that owns nothing.
451 template <typename _Up = _Dp,
452 typename = _DeleterConstraint<_Up>>
453 constexpr unique_ptr() noexcept
454 : _M_t()
455 { }
456
457 /** Takes ownership of a pointer.
458 *
459 * @param __p A pointer to an array of a type safely convertible
460 * to an array of @c element_type
461 *
462 * The deleter will be value-initialized.
463 */
464 template<typename _Up,
465 typename _Vp = _Dp,
466 typename = _DeleterConstraint<_Vp>,
467 typename = typename enable_if<
468 __safe_conversion_raw<_Up>::value, bool>::type>
469 explicit
470 unique_ptr(_Up __p) noexcept
471 : _M_t(__p)
472 { }
473
474 /** Takes ownership of a pointer.
475 *
476 * @param __p A pointer to an array of a type safely convertible
477 * to an array of @c element_type
478 * @param __d A reference to a deleter.
479 *
480 * The deleter will be initialized with @p __d
481 */
482 template<typename _Up,
483 typename = typename enable_if<
484 __safe_conversion_raw<_Up>::value, bool>::type>
485 unique_ptr(_Up __p,
486 typename conditional<is_reference<deleter_type>::value,
487 deleter_type, const deleter_type&>::type __d) noexcept
488 : _M_t(__p, __d) { }
489
490 /** Takes ownership of a pointer.
491 *
492 * @param __p A pointer to an array of a type safely convertible
493 * to an array of @c element_type
494 * @param __d A reference to a deleter.
495 *
496 * The deleter will be initialized with @p std::move(__d)
497 */
498 template<typename _Up,
499 typename = typename enable_if<
500 __safe_conversion_raw<_Up>::value, bool>::type>
501 unique_ptr(_Up __p, typename
502 remove_reference<deleter_type>::type&& __d) noexcept
503 : _M_t(std::move(__p), std::move(__d))
504 { static_assert(!is_reference<deleter_type>::value,
505 "rvalue deleter bound to reference"); }
506
507 /// Move constructor.
508 unique_ptr(unique_ptr&& __u) noexcept
509 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
510
511 /// Creates a unique_ptr that owns nothing.
512 template <typename _Up = _Dp,
513 typename = _DeleterConstraint<_Up>>
514 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
515
516 template<typename _Up, typename _Ep,
517 typename = _Require<__safe_conversion_up<_Up, _Ep>>>
518 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
519 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
520 { }
521
522 /// Destructor, invokes the deleter if the stored pointer is not null.
523 ~unique_ptr()
524 {
525 auto& __ptr = _M_t._M_ptr();
526 if (__ptr != nullptr)
527 get_deleter()(__ptr);
528 __ptr = pointer();
529 }
530
531 // Assignment.
532
533 /** @brief Move assignment operator.
534 *
535 * @param __u The object to transfer ownership from.
536 *
537 * Invokes the deleter first if this object owns a pointer.
538 */
539 unique_ptr&
540 operator=(unique_ptr&& __u) noexcept
541 {
542 reset(__u.release());
543 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
544 return *this;
545 }
546
547 /** @brief Assignment from another type.
548 *
549 * @param __u The object to transfer ownership from, which owns a
550 * convertible pointer to an array object.
551 *
552 * Invokes the deleter first if this object owns a pointer.
553 */
554 template<typename _Up, typename _Ep>
555 typename
556 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
557 is_assignable<deleter_type&, _Ep&&>
558 >::value,
559 unique_ptr&>::type
560 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
561 {
562 reset(__u.release());
563 get_deleter() = std::forward<_Ep>(__u.get_deleter());
564 return *this;
565 }
566
567 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
568 unique_ptr&
569 operator=(nullptr_t) noexcept
570 {
571 reset();
572 return *this;
573 }
574
575 // Observers.
576
577 /// Access an element of owned array.
578 typename std::add_lvalue_reference<element_type>::type
579 operator[](size_t __i) const
580 {
581 __glibcxx_assert(get() != pointer());
582 return get()[__i];
583 }
584
585 /// Return the stored pointer.
586 pointer
587 get() const noexcept
588 { return _M_t._M_ptr(); }
589
590 /// Return a reference to the stored deleter.
591 deleter_type&
592 get_deleter() noexcept
593 { return _M_t._M_deleter(); }
594
595 /// Return a reference to the stored deleter.
596 const deleter_type&
597 get_deleter() const noexcept
598 { return _M_t._M_deleter(); }
599
600 /// Return @c true if the stored pointer is not null.
601 explicit operator bool() const noexcept
602 { return get() == pointer() ? false : true; }
603
604 // Modifiers.
605
606 /// Release ownership of any stored pointer.
607 pointer
608 release() noexcept
609 {
610 pointer __p = get();
611 _M_t._M_ptr() = pointer();
612 return __p;
613 }
614
615 /** @brief Replace the stored pointer.
616 *
617 * @param __p The new pointer to store.
618 *
619 * The deleter will be invoked if a pointer is already owned.
620 */
621 template <typename _Up,
622 typename = _Require<
623 __or_<is_same<_Up, pointer>,
624 __and_<is_same<pointer, element_type*>,
625 is_pointer<_Up>,
626 is_convertible<
627 typename remove_pointer<_Up>::type(*)[],
628 element_type(*)[]
629 >
630 >
631 >
632 >>
633 void
634 reset(_Up __p) noexcept
635 {
636 pointer __ptr = __p;
637 using std::swap;
638 swap(_M_t._M_ptr(), __ptr);
639 if (__ptr != nullptr)
640 get_deleter()(__ptr);
641 }
642
643 void reset(nullptr_t = nullptr) noexcept
644 {
645 reset(pointer());
646 }
647
648 /// Exchange the pointer and deleter with another object.
649 void
650 swap(unique_ptr& __u) noexcept
651 {
652 using std::swap;
653 swap(_M_t, __u._M_t);
654 }
655
656 // Disable copy from lvalue.
657 unique_ptr(const unique_ptr&) = delete;
658 unique_ptr& operator=(const unique_ptr&) = delete;
659 };
660
661 template<typename _Tp, typename _Dp>
662 inline
663#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
664 // Constrained free swap overload, see p0185r1
665 typename enable_if<__is_swappable<_Dp>::value>::type
666#else
667 void
668#endif
669 swap(unique_ptr<_Tp, _Dp>& __x,
670 unique_ptr<_Tp, _Dp>& __y) noexcept
671 { __x.swap(__y); }
672
673#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
674 template<typename _Tp, typename _Dp>
675 typename enable_if<!__is_swappable<_Dp>::value>::type
676 swap(unique_ptr<_Tp, _Dp>&,
677 unique_ptr<_Tp, _Dp>&) = delete;
678#endif
679
680 template<typename _Tp, typename _Dp,
681 typename _Up, typename _Ep>
682 inline bool
683 operator==(const unique_ptr<_Tp, _Dp>& __x,
684 const unique_ptr<_Up, _Ep>& __y)
685 { return __x.get() == __y.get(); }
686
687 template<typename _Tp, typename _Dp>
688 inline bool
689 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
690 { return !__x; }
691
692 template<typename _Tp, typename _Dp>
693 inline bool
694 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
695 { return !__x; }
696
697 template<typename _Tp, typename _Dp,
698 typename _Up, typename _Ep>
699 inline bool
700 operator!=(const unique_ptr<_Tp, _Dp>& __x,
701 const unique_ptr<_Up, _Ep>& __y)
702 { return __x.get() != __y.get(); }
703
704 template<typename _Tp, typename _Dp>
705 inline bool
706 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
707 { return (bool)__x; }
708
709 template<typename _Tp, typename _Dp>
710 inline bool
711 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
712 { return (bool)__x; }
713
714 template<typename _Tp, typename _Dp,
715 typename _Up, typename _Ep>
716 inline bool
717 operator<(const unique_ptr<_Tp, _Dp>& __x,
718 const unique_ptr<_Up, _Ep>& __y)
719 {
720 typedef typename
721 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
722 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
723 return std::less<_CT>()(__x.get(), __y.get());
724 }
725
726 template<typename _Tp, typename _Dp>
727 inline bool
728 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
729 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
730 nullptr); }
731
732 template<typename _Tp, typename _Dp>
733 inline bool
734 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
735 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
736 __x.get()); }
737
738 template<typename _Tp, typename _Dp,
739 typename _Up, typename _Ep>
740 inline bool
741 operator<=(const unique_ptr<_Tp, _Dp>& __x,
742 const unique_ptr<_Up, _Ep>& __y)
743 { return !(__y < __x); }
744
745 template<typename _Tp, typename _Dp>
746 inline bool
747 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
748 { return !(nullptr < __x); }
749
750 template<typename _Tp, typename _Dp>
751 inline bool
752 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
753 { return !(__x < nullptr); }
754
755 template<typename _Tp, typename _Dp,
756 typename _Up, typename _Ep>
757 inline bool
758 operator>(const unique_ptr<_Tp, _Dp>& __x,
759 const unique_ptr<_Up, _Ep>& __y)
760 { return (__y < __x); }
761
762 template<typename _Tp, typename _Dp>
763 inline bool
764 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
765 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
766 __x.get()); }
767
768 template<typename _Tp, typename _Dp>
769 inline bool
770 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
771 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
772 nullptr); }
773
774 template<typename _Tp, typename _Dp,
775 typename _Up, typename _Ep>
776 inline bool
777 operator>=(const unique_ptr<_Tp, _Dp>& __x,
778 const unique_ptr<_Up, _Ep>& __y)
779 { return !(__x < __y); }
780
781 template<typename _Tp, typename _Dp>
782 inline bool
783 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
784 { return !(__x < nullptr); }
785
786 template<typename _Tp, typename _Dp>
787 inline bool
788 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
789 { return !(nullptr < __x); }
790
791 /// std::hash specialization for unique_ptr.
792 template<typename _Tp, typename _Dp>
793 struct hash<unique_ptr<_Tp, _Dp>>
794 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>,
795 private __poison_hash<typename unique_ptr<_Tp, _Dp>::pointer>
796 {
797 size_t
798 operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept
799 {
800 typedef unique_ptr<_Tp, _Dp> _UP;
801 return std::hash<typename _UP::pointer>()(__u.get());
802 }
803 };
804
805#if __cplusplus201103L > 201103L
806
807#define __cpp_lib_make_unique 201304
808
809 template<typename _Tp>
810 struct _MakeUniq
811 { typedef unique_ptr<_Tp> __single_object; };
812
813 template<typename _Tp>
814 struct _MakeUniq<_Tp[]>
815 { typedef unique_ptr<_Tp[]> __array; };
816
817 template<typename _Tp, size_t _Bound>
818 struct _MakeUniq<_Tp[_Bound]>
819 { struct __invalid_type { }; };
820
821 /// std::make_unique for single objects
822 template<typename _Tp, typename... _Args>
823 inline typename _MakeUniq<_Tp>::__single_object
824 make_unique(_Args&&... __args)
825 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
826
827 /// std::make_unique for arrays of unknown bound
828 template<typename _Tp>
829 inline typename _MakeUniq<_Tp>::__array
830 make_unique(size_t __num)
831 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
832
833 /// Disable std::make_unique for arrays of known bound
834 template<typename _Tp, typename... _Args>
835 inline typename _MakeUniq<_Tp>::__invalid_type
836 make_unique(_Args&&...) = delete;
837#endif
838
839 // @} group pointer_abstractions
840
841_GLIBCXX_END_NAMESPACE_VERSION
842} // namespace
843
844#endif /* _UNIQUE_PTR_H */