Bug Summary

File:lib/AsmParser/LLParser.cpp
Warning:line 8044, column 23
Assigned value is garbage or undefined

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 LLParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -analyzer-config-compatibility-mode=true -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-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn360410/build-llvm/lib/AsmParser -I /build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser -I /build/llvm-toolchain-snapshot-9~svn360410/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn360410/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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-9~svn360410/build-llvm/lib/AsmParser -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn360410=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-11-053245-11877-1 -x c++ /build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp -faddrsig
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LLParser.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/None.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/AsmParser/SlotMapping.h"
20#include "llvm/BinaryFormat/Dwarf.h"
21#include "llvm/IR/Argument.h"
22#include "llvm/IR/AutoUpgrade.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallingConv.h"
25#include "llvm/IR/Comdat.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DebugInfoMetadata.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/GlobalObject.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
40#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
42#include "llvm/IR/ValueSymbolTable.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Support/SaveAndRestore.h"
47#include "llvm/Support/raw_ostream.h"
48#include <algorithm>
49#include <cassert>
50#include <cstring>
51#include <iterator>
52#include <vector>
53
54using namespace llvm;
55
56static std::string getTypeString(Type *T) {
57 std::string Result;
58 raw_string_ostream Tmp(Result);
59 Tmp << *T;
60 return Tmp.str();
61}
62
63/// Run: module ::= toplevelentity*
64bool LLParser::Run() {
65 // Prime the lexer.
66 Lex.Lex();
67
68 if (Context.shouldDiscardValueNames())
69 return Error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
72
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
74 ValidateEndOfIndex();
75}
76
77bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
80 Lex.Lex();
81
82 Type *Ty = nullptr;
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
84 return true;
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
87 return false;
88}
89
90bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
92 restoreParsingState(Slots);
93 Lex.Lex();
94
95 Read = 0;
96 SMLoc Start = Lex.getLoc();
97 Ty = nullptr;
98 if (ParseType(Ty))
99 return true;
100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
102
103 return false;
104}
105
106void LLParser::restoreParsingState(const SlotMapping *Slots) {
107 if (!Slots)
108 return;
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
112 NamedTypes.insert(
113 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114 for (const auto &I : Slots->Types)
115 NumberedTypes.insert(
116 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
117}
118
119/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
120/// module.
121bool LLParser::ValidateEndOfModule() {
122 if (!M)
123 return false;
124 // Handle any function attribute group forward references.
125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
128 AttrBuilder B;
129
130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
132
133 if (Function *Fn = dyn_cast<Function>(V)) {
134 AttributeList AS = Fn->getAttributes();
135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
137
138 FnAttrs.merge(B);
139
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
145 }
146
147 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
148 AttributeSet::get(Context, FnAttrs));
149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
151 AttributeList AS = CI->getAttributes();
152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
154 FnAttrs.merge(B);
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 CI->setAttributes(AS);
158 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
159 AttributeList AS = II->getAttributes();
160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 FnAttrs.merge(B);
163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
165 II->setAttributes(AS);
166 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
167 AttributeList AS = CBI->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
170 FnAttrs.merge(B);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 CBI->setAttributes(AS);
174 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
175 AttrBuilder Attrs(GV->getAttributes());
176 Attrs.merge(B);
177 GV->setAttributes(AttributeSet::get(Context,Attrs));
178 } else {
179 llvm_unreachable("invalid object with forward attribute group reference")::llvm::llvm_unreachable_internal("invalid object with forward attribute group reference"
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 179)
;
180 }
181 }
182
183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses.empty())
186 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
187 "expected function name in blockaddress");
188
189 for (const auto &NT : NumberedTypes)
190 if (NT.second.second.isValid())
191 return Error(NT.second.second,
192 "use of undefined type '%" + Twine(NT.first) + "'");
193
194 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
195 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
196 if (I->second.second.isValid())
197 return Error(I->second.second,
198 "use of undefined type named '" + I->getKey() + "'");
199
200 if (!ForwardRefComdats.empty())
201 return Error(ForwardRefComdats.begin()->second,
202 "use of undefined comdat '$" +
203 ForwardRefComdats.begin()->first + "'");
204
205 if (!ForwardRefVals.empty())
206 return Error(ForwardRefVals.begin()->second.second,
207 "use of undefined value '@" + ForwardRefVals.begin()->first +
208 "'");
209
210 if (!ForwardRefValIDs.empty())
211 return Error(ForwardRefValIDs.begin()->second.second,
212 "use of undefined value '@" +
213 Twine(ForwardRefValIDs.begin()->first) + "'");
214
215 if (!ForwardRefMDNodes.empty())
216 return Error(ForwardRefMDNodes.begin()->second.second,
217 "use of undefined metadata '!" +
218 Twine(ForwardRefMDNodes.begin()->first) + "'");
219
220 // Resolve metadata cycles.
221 for (auto &N : NumberedMetadata) {
222 if (N.second && !N.second->isResolved())
223 N.second->resolveCycles();
224 }
225
226 for (auto *Inst : InstsWithTBAATag) {
227 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
228 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag")((MD && "UpgradeInstWithTBAATag should have a TBAA tag"
) ? static_cast<void> (0) : __assert_fail ("MD && \"UpgradeInstWithTBAATag should have a TBAA tag\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 228, __PRETTY_FUNCTION__))
;
229 auto *UpgradedMD = UpgradeTBAANode(*MD);
230 if (MD != UpgradedMD)
231 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
232 }
233
234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
236 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
237
238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
242 Function *F = &*FI++;
243 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
244 F->replaceAllUsesWith(Remangled.getValue());
245 F->eraseFromParent();
246 }
247 }
248
249 if (UpgradeDebugInfo)
250 llvm::UpgradeDebugInfo(*M);
251
252 UpgradeModuleFlags(*M);
253 UpgradeSectionAttributes(*M);
254
255 if (!Slots)
256 return false;
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots->GlobalValues = std::move(NumberedVals);
261 Slots->MetadataNodes = std::move(NumberedMetadata);
262 for (const auto &I : NamedTypes)
263 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
264 for (const auto &I : NumberedTypes)
265 Slots->Types.insert(std::make_pair(I.first, I.second.first));
266
267 return false;
268}
269
270/// Do final validity and sanity checks at the end of the index.
271bool LLParser::ValidateEndOfIndex() {
272 if (!Index)
273 return false;
274
275 if (!ForwardRefValueInfos.empty())
276 return Error(ForwardRefValueInfos.begin()->second.front().second,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos.begin()->first) + "'");
279
280 if (!ForwardRefAliasees.empty())
281 return Error(ForwardRefAliasees.begin()->second.front().second,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees.begin()->first) + "'");
284
285 if (!ForwardRefTypeIds.empty())
286 return Error(ForwardRefTypeIds.begin()->second.front().second,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds.begin()->first) + "'");
289
290 return false;
291}
292
293//===----------------------------------------------------------------------===//
294// Top-Level Entities
295//===----------------------------------------------------------------------===//
296
297bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
299 if (!M) {
300 while (true) {
301 switch (Lex.getKind()) {
302 case lltok::Eof:
303 return false;
304 case lltok::SummaryID:
305 if (ParseSummaryEntry())
306 return true;
307 break;
308 case lltok::kw_source_filename:
309 if (ParseSourceFileName())
310 return true;
311 break;
312 default:
313 // Skip everything else
314 Lex.Lex();
315 }
316 }
317 }
318 while (true) {
319 switch (Lex.getKind()) {
320 default: return TokError("expected top-level entity");
321 case lltok::Eof: return false;
322 case lltok::kw_declare: if (ParseDeclare()) return true; break;
323 case lltok::kw_define: if (ParseDefine()) return true; break;
324 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
326 case lltok::kw_source_filename:
327 if (ParseSourceFileName())
328 return true;
329 break;
330 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
331 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
332 case lltok::LocalVar: if (ParseNamedType()) return true; break;
333 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
334 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
335 case lltok::ComdatVar: if (parseComdat()) return true; break;
336 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
337 case lltok::SummaryID:
338 if (ParseSummaryEntry())
339 return true;
340 break;
341 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
342 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
343 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb:
345 if (ParseUseListOrderBB())
346 return true;
347 break;
348 }
349 }
350}
351
352/// toplevelentity
353/// ::= 'module' 'asm' STRINGCONSTANT
354bool LLParser::ParseModuleAsm() {
355 assert(Lex.getKind() == lltok::kw_module)((Lex.getKind() == lltok::kw_module) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_module", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 355, __PRETTY_FUNCTION__))
;
356 Lex.Lex();
357
358 std::string AsmStr;
359 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr)) return true;
361
362 M->appendModuleInlineAsm(AsmStr);
363 return false;
364}
365
366/// toplevelentity
367/// ::= 'target' 'triple' '=' STRINGCONSTANT
368/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369bool LLParser::ParseTargetDefinition() {
370 assert(Lex.getKind() == lltok::kw_target)((Lex.getKind() == lltok::kw_target) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_target", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 370, __PRETTY_FUNCTION__))
;
371 std::string Str;
372 switch (Lex.Lex()) {
373 default: return TokError("unknown target property");
374 case lltok::kw_triple:
375 Lex.Lex();
376 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377 ParseStringConstant(Str))
378 return true;
379 M->setTargetTriple(Str);
380 return false;
381 case lltok::kw_datalayout:
382 Lex.Lex();
383 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str))
385 return true;
386 if (DataLayoutStr.empty())
387 M->setDataLayout(Str);
388 return false;
389 }
390}
391
392/// toplevelentity
393/// ::= 'source_filename' '=' STRINGCONSTANT
394bool LLParser::ParseSourceFileName() {
395 assert(Lex.getKind() == lltok::kw_source_filename)((Lex.getKind() == lltok::kw_source_filename) ? static_cast<
void> (0) : __assert_fail ("Lex.getKind() == lltok::kw_source_filename"
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 395, __PRETTY_FUNCTION__))
;
396 Lex.Lex();
397 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName))
399 return true;
400 if (M)
401 M->setSourceFileName(SourceFileName);
402 return false;
403}
404
405/// toplevelentity
406/// ::= 'deplibs' '=' '[' ']'
407/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408/// FIXME: Remove in 4.0. Currently parse, but ignore.
409bool LLParser::ParseDepLibs() {
410 assert(Lex.getKind() == lltok::kw_deplibs)((Lex.getKind() == lltok::kw_deplibs) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_deplibs", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 410, __PRETTY_FUNCTION__))
;
411 Lex.Lex();
412 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
414 return true;
415
416 if (EatIfPresent(lltok::rsquare))
417 return false;
418
419 do {
420 std::string Str;
421 if (ParseStringConstant(Str)) return true;
422 } while (EatIfPresent(lltok::comma));
423
424 return ParseToken(lltok::rsquare, "expected ']' at end of list");
425}
426
427/// ParseUnnamedType:
428/// ::= LocalVarID '=' 'type' type
429bool LLParser::ParseUnnamedType() {
430 LocTy TypeLoc = Lex.getLoc();
431 unsigned TypeID = Lex.getUIntVal();
432 Lex.Lex(); // eat LocalVarID;
433
434 if (ParseToken(lltok::equal, "expected '=' after name") ||
435 ParseToken(lltok::kw_type, "expected 'type' after '='"))
436 return true;
437
438 Type *Result = nullptr;
439 if (ParseStructDefinition(TypeLoc, "",
440 NumberedTypes[TypeID], Result)) return true;
441
442 if (!isa<StructType>(Result)) {
443 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
444 if (Entry.first)
445 return Error(TypeLoc, "non-struct types may not be recursive");
446 Entry.first = Result;
447 Entry.second = SMLoc();
448 }
449
450 return false;
451}
452
453/// toplevelentity
454/// ::= LocalVar '=' 'type' type
455bool LLParser::ParseNamedType() {
456 std::string Name = Lex.getStrVal();
457 LocTy NameLoc = Lex.getLoc();
458 Lex.Lex(); // eat LocalVar.
459
460 if (ParseToken(lltok::equal, "expected '=' after name") ||
461 ParseToken(lltok::kw_type, "expected 'type' after name"))
462 return true;
463
464 Type *Result = nullptr;
465 if (ParseStructDefinition(NameLoc, Name,
466 NamedTypes[Name], Result)) return true;
467
468 if (!isa<StructType>(Result)) {
469 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
470 if (Entry.first)
471 return Error(NameLoc, "non-struct types may not be recursive");
472 Entry.first = Result;
473 Entry.second = SMLoc();
474 }
475
476 return false;
477}
478
479/// toplevelentity
480/// ::= 'declare' FunctionHeader
481bool LLParser::ParseDeclare() {
482 assert(Lex.getKind() == lltok::kw_declare)((Lex.getKind() == lltok::kw_declare) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_declare", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 482, __PRETTY_FUNCTION__))
;
483 Lex.Lex();
484
485 std::vector<std::pair<unsigned, MDNode *>> MDs;
486 while (Lex.getKind() == lltok::MetadataVar) {
487 unsigned MDK;
488 MDNode *N;
489 if (ParseMetadataAttachment(MDK, N))
490 return true;
491 MDs.push_back({MDK, N});
492 }
493
494 Function *F;
495 if (ParseFunctionHeader(F, false))
496 return true;
497 for (auto &MD : MDs)
498 F->addMetadata(MD.first, *MD.second);
499 return false;
500}
501
502/// toplevelentity
503/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504bool LLParser::ParseDefine() {
505 assert(Lex.getKind() == lltok::kw_define)((Lex.getKind() == lltok::kw_define) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::kw_define", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 505, __PRETTY_FUNCTION__))
;
506 Lex.Lex();
507
508 Function *F;
509 return ParseFunctionHeader(F, true) ||
510 ParseOptionalFunctionMetadata(*F) ||
511 ParseFunctionBody(*F);
512}
513
514/// ParseGlobalType
515/// ::= 'constant'
516/// ::= 'global'
517bool LLParser::ParseGlobalType(bool &IsConstant) {
518 if (Lex.getKind() == lltok::kw_constant)
519 IsConstant = true;
520 else if (Lex.getKind() == lltok::kw_global)
521 IsConstant = false;
522 else {
523 IsConstant = false;
524 return TokError("expected 'global' or 'constant'");
525 }
526 Lex.Lex();
527 return false;
528}
529
530bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr &UnnamedAddr) {
532 if (EatIfPresent(lltok::kw_unnamed_addr))
533 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
535 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
536 else
537 UnnamedAddr = GlobalValue::UnnamedAddr::None;
538 return false;
539}
540
541/// ParseUnnamedGlobal:
542/// OptionalVisibility (ALIAS | IFUNC) ...
543/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544/// OptionalDLLStorageClass
545/// ... -> global variable
546/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548/// OptionalDLLStorageClass
549/// ... -> global variable
550bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID = NumberedVals.size();
552 std::string Name;
553 LocTy NameLoc = Lex.getLoc();
554
555 // Handle the GlobalID form.
556 if (Lex.getKind() == lltok::GlobalID) {
557 if (Lex.getUIntVal() != VarID)
558 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
559 Twine(VarID) + "'");
560 Lex.Lex(); // eat GlobalID;
561
562 if (ParseToken(lltok::equal, "expected '=' after name"))
563 return true;
564 }
565
566 bool HasLinkage;
567 unsigned Linkage, Visibility, DLLStorageClass;
568 bool DSOLocal;
569 GlobalVariable::ThreadLocalMode TLM;
570 GlobalVariable::UnnamedAddr UnnamedAddr;
571 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
572 DSOLocal) ||
573 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
574 return true;
575
576 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
577 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
578 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
579
580 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
581 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
582}
583
584/// ParseNamedGlobal:
585/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587/// OptionalVisibility OptionalDLLStorageClass
588/// ... -> global variable
589bool LLParser::ParseNamedGlobal() {
590 assert(Lex.getKind() == lltok::GlobalVar)((Lex.getKind() == lltok::GlobalVar) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::GlobalVar", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 590, __PRETTY_FUNCTION__))
;
591 LocTy NameLoc = Lex.getLoc();
592 std::string Name = Lex.getStrVal();
593 Lex.Lex();
594
595 bool HasLinkage;
596 unsigned Linkage, Visibility, DLLStorageClass;
597 bool DSOLocal;
598 GlobalVariable::ThreadLocalMode TLM;
599 GlobalVariable::UnnamedAddr UnnamedAddr;
600 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
602 DSOLocal) ||
603 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
604 return true;
605
606 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
607 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
608 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
609
610 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
611 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
612}
613
614bool LLParser::parseComdat() {
615 assert(Lex.getKind() == lltok::ComdatVar)((Lex.getKind() == lltok::ComdatVar) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::ComdatVar", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 615, __PRETTY_FUNCTION__))
;
616 std::string Name = Lex.getStrVal();
617 LocTy NameLoc = Lex.getLoc();
618 Lex.Lex();
619
620 if (ParseToken(lltok::equal, "expected '=' here"))
621 return true;
622
623 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624 return TokError("expected comdat type");
625
626 Comdat::SelectionKind SK;
627 switch (Lex.getKind()) {
628 default:
629 return TokError("unknown selection kind");
630 case lltok::kw_any:
631 SK = Comdat::Any;
632 break;
633 case lltok::kw_exactmatch:
634 SK = Comdat::ExactMatch;
635 break;
636 case lltok::kw_largest:
637 SK = Comdat::Largest;
638 break;
639 case lltok::kw_noduplicates:
640 SK = Comdat::NoDuplicates;
641 break;
642 case lltok::kw_samesize:
643 SK = Comdat::SameSize;
644 break;
645 }
646 Lex.Lex();
647
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
651 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
652 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
653
654 Comdat *C;
655 if (I != ComdatSymTab.end())
656 C = &I->second;
657 else
658 C = M->getOrInsertComdat(Name);
659 C->setSelectionKind(SK);
660
661 return false;
662}
663
664// MDString:
665// ::= '!' STRINGCONSTANT
666bool LLParser::ParseMDString(MDString *&Result) {
667 std::string Str;
668 if (ParseStringConstant(Str)) return true;
669 Result = MDString::get(Context, Str);
670 return false;
671}
672
673// MDNode:
674// ::= '!' MDNodeNumber
675bool LLParser::ParseMDNodeID(MDNode *&Result) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc = Lex.getLoc();
678 unsigned MID = 0;
679 if (ParseUInt32(MID))
680 return true;
681
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata.count(MID)) {
684 Result = NumberedMetadata[MID];
685 return false;
686 }
687
688 // Otherwise, create MDNode forward reference.
689 auto &FwdRef = ForwardRefMDNodes[MID];
690 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
691
692 Result = FwdRef.first.get();
693 NumberedMetadata[MID].reset(Result);
694 return false;
695}
696
697/// ParseNamedMetadata:
698/// !foo = !{ !1, !2 }
699bool LLParser::ParseNamedMetadata() {
700 assert(Lex.getKind() == lltok::MetadataVar)((Lex.getKind() == lltok::MetadataVar) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 700, __PRETTY_FUNCTION__))
;
701 std::string Name = Lex.getStrVal();
702 Lex.Lex();
703
704 if (ParseToken(lltok::equal, "expected '=' here") ||
705 ParseToken(lltok::exclaim, "Expected '!' here") ||
706 ParseToken(lltok::lbrace, "Expected '{' here"))
707 return true;
708
709 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
710 if (Lex.getKind() != lltok::rbrace)
711 do {
712 MDNode *N = nullptr;
713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex.getKind() == lltok::MetadataVar &&
717 Lex.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N, /*IsDistinct=*/false))
719 return true;
720 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
721 ParseMDNodeID(N)) {
722 return true;
723 }
724 NMD->addOperand(N);
725 } while (EatIfPresent(lltok::comma));
726
727 return ParseToken(lltok::rbrace, "expected end of metadata node");
728}
729
730/// ParseStandaloneMetadata:
731/// !42 = !{...}
732bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex.getKind() == lltok::exclaim)((Lex.getKind() == lltok::exclaim) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::exclaim", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 733, __PRETTY_FUNCTION__))
;
734 Lex.Lex();
735 unsigned MetadataID = 0;
736
737 MDNode *Init;
738 if (ParseUInt32(MetadataID) ||
739 ParseToken(lltok::equal, "expected '=' here"))
740 return true;
741
742 // Detect common error, from old metadata syntax.
743 if (Lex.getKind() == lltok::Type)
744 return TokError("unexpected type in metadata definition");
745
746 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
747 if (Lex.getKind() == lltok::MetadataVar) {
748 if (ParseSpecializedMDNode(Init, IsDistinct))
749 return true;
750 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751 ParseMDTuple(Init, IsDistinct))
752 return true;
753
754 // See if this was forward referenced, if so, handle it.
755 auto FI = ForwardRefMDNodes.find(MetadataID);
756 if (FI != ForwardRefMDNodes.end()) {
757 FI->second.first->replaceAllUsesWith(Init);
758 ForwardRefMDNodes.erase(FI);
759
760 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work")((NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"
) ? static_cast<void> (0) : __assert_fail ("NumberedMetadata[MetadataID] == Init && \"Tracking VH didn't work\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 760, __PRETTY_FUNCTION__))
;
761 } else {
762 if (NumberedMetadata.count(MetadataID))
763 return TokError("Metadata id is already used");
764 NumberedMetadata[MetadataID].reset(Init);
765 }
766
767 return false;
768}
769
770// Skips a single module summary entry.
771bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
776 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
777 Lex.getKind() != lltok::kw_typeid)
778 return TokError(
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
780 Lex.Lex();
781 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
783 return true;
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen = 1;
787 do {
788 switch (Lex.getKind()) {
789 case lltok::lparen:
790 NumOpenParen++;
791 break;
792 case lltok::rparen:
793 NumOpenParen--;
794 break;
795 case lltok::Eof:
796 return TokError("found end of file while parsing summary entry");
797 default:
798 // Skip everything in between parentheses.
799 break;
800 }
801 Lex.Lex();
802 } while (NumOpenParen > 0);
803 return false;
804}
805
806/// SummaryEntry
807/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808bool LLParser::ParseSummaryEntry() {
809 assert(Lex.getKind() == lltok::SummaryID)((Lex.getKind() == lltok::SummaryID) ? static_cast<void>
(0) : __assert_fail ("Lex.getKind() == lltok::SummaryID", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 809, __PRETTY_FUNCTION__))
;
810 unsigned SummaryID = Lex.getUIntVal();
811
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex.setIgnoreColonInIdentifiers(true);
815
816 Lex.Lex();
817 if (ParseToken(lltok::equal, "expected '=' here"))
818 return true;
819
820 // If we don't have an index object, skip the summary entry.
821 if (!Index)
822 return SkipModuleSummaryEntry();
823
824 bool result = false;
825 switch (Lex.getKind()) {
826 case lltok::kw_gv:
827 result = ParseGVEntry(SummaryID);
828 break;
829 case lltok::kw_module:
830 result = ParseModuleEntry(SummaryID);
831 break;
832 case lltok::kw_typeid:
833 result = ParseTypeIdEntry(SummaryID);
834 break;
835 default:
836 result = Error(Lex.getLoc(), "unexpected summary kind");
837 break;
838 }
839 Lex.setIgnoreColonInIdentifiers(false);
840 return result;
841}
842
843static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
844 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
845 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
846}
847
848// If there was an explicit dso_local, update GV. In the absence of an explicit
849// dso_local we keep the default value.
850static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
851 if (DSOLocal)
852 GV.setDSOLocal(true);
853}
854
855/// parseIndirectSymbol:
856/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
857/// OptionalVisibility OptionalDLLStorageClass
858/// OptionalThreadLocal OptionalUnnamedAddr
859// 'alias|ifunc' IndirectSymbol
860///
861/// IndirectSymbol
862/// ::= TypeAndValue
863///
864/// Everything through OptionalUnnamedAddr has already been parsed.
865///
866bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
867 unsigned L, unsigned Visibility,
868 unsigned DLLStorageClass, bool DSOLocal,
869 GlobalVariable::ThreadLocalMode TLM,
870 GlobalVariable::UnnamedAddr UnnamedAddr) {
871 bool IsAlias;
872 if (Lex.getKind() == lltok::kw_alias)
873 IsAlias = true;
874 else if (Lex.getKind() == lltok::kw_ifunc)
875 IsAlias = false;
876 else
877 llvm_unreachable("Not an alias or ifunc!")::llvm::llvm_unreachable_internal("Not an alias or ifunc!", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 877)
;
878 Lex.Lex();
879
880 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
881
882 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
883 return Error(NameLoc, "invalid linkage type for alias");
884
885 if (!isValidVisibilityForLinkage(Visibility, L))
886 return Error(NameLoc,
887 "symbol with local linkage must have default visibility");
888
889 Type *Ty;
890 LocTy ExplicitTypeLoc = Lex.getLoc();
891 if (ParseType(Ty) ||
892 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
893 return true;
894
895 Constant *Aliasee;
896 LocTy AliaseeLoc = Lex.getLoc();
897 if (Lex.getKind() != lltok::kw_bitcast &&
898 Lex.getKind() != lltok::kw_getelementptr &&
899 Lex.getKind() != lltok::kw_addrspacecast &&
900 Lex.getKind() != lltok::kw_inttoptr) {
901 if (ParseGlobalTypeAndValue(Aliasee))
902 return true;
903 } else {
904 // The bitcast dest type is not present, it is implied by the dest type.
905 ValID ID;
906 if (ParseValID(ID))
907 return true;
908 if (ID.Kind != ValID::t_Constant)
909 return Error(AliaseeLoc, "invalid aliasee");
910 Aliasee = ID.ConstantVal;
911 }
912
913 Type *AliaseeType = Aliasee->getType();
914 auto *PTy = dyn_cast<PointerType>(AliaseeType);
915 if (!PTy)
916 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
917 unsigned AddrSpace = PTy->getAddressSpace();
918
919 if (IsAlias && Ty != PTy->getElementType())
920 return Error(
921 ExplicitTypeLoc,
922 "explicit pointee type doesn't match operand's pointee type");
923
924 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
925 return Error(
926 ExplicitTypeLoc,
927 "explicit pointee type should be a function type");
928
929 GlobalValue *GVal = nullptr;
930
931 // See if the alias was forward referenced, if so, prepare to replace the
932 // forward reference.
933 if (!Name.empty()) {
934 GVal = M->getNamedValue(Name);
935 if (GVal) {
936 if (!ForwardRefVals.erase(Name))
937 return Error(NameLoc, "redefinition of global '@" + Name + "'");
938 }
939 } else {
940 auto I = ForwardRefValIDs.find(NumberedVals.size());
941 if (I != ForwardRefValIDs.end()) {
942 GVal = I->second.first;
943 ForwardRefValIDs.erase(I);
944 }
945 }
946
947 // Okay, create the alias but do not insert it into the module yet.
948 std::unique_ptr<GlobalIndirectSymbol> GA;
949 if (IsAlias)
950 GA.reset(GlobalAlias::create(Ty, AddrSpace,
951 (GlobalValue::LinkageTypes)Linkage, Name,
952 Aliasee, /*Parent*/ nullptr));
953 else
954 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
955 (GlobalValue::LinkageTypes)Linkage, Name,
956 Aliasee, /*Parent*/ nullptr));
957 GA->setThreadLocalMode(TLM);
958 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
959 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
960 GA->setUnnamedAddr(UnnamedAddr);
961 maybeSetDSOLocal(DSOLocal, *GA);
962
963 if (Name.empty())
964 NumberedVals.push_back(GA.get());
965
966 if (GVal) {
967 // Verify that types agree.
968 if (GVal->getType() != GA->getType())
969 return Error(
970 ExplicitTypeLoc,
971 "forward reference and definition of alias have different types");
972
973 // If they agree, just RAUW the old value with the alias and remove the
974 // forward ref info.
975 GVal->replaceAllUsesWith(GA.get());
976 GVal->eraseFromParent();
977 }
978
979 // Insert into the module, we know its name won't collide now.
980 if (IsAlias)
981 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
982 else
983 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
984 assert(GA->getName() == Name && "Should not be a name conflict!")((GA->getName() == Name && "Should not be a name conflict!"
) ? static_cast<void> (0) : __assert_fail ("GA->getName() == Name && \"Should not be a name conflict!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 984, __PRETTY_FUNCTION__))
;
985
986 // The module owns this now
987 GA.release();
988
989 return false;
990}
991
992/// ParseGlobal
993/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
994/// OptionalVisibility OptionalDLLStorageClass
995/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
996/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
997/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
998/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
999/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1000/// Const OptionalAttrs
1001///
1002/// Everything up to and including OptionalUnnamedAddr has been parsed
1003/// already.
1004///
1005bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
1006 unsigned Linkage, bool HasLinkage,
1007 unsigned Visibility, unsigned DLLStorageClass,
1008 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1009 GlobalVariable::UnnamedAddr UnnamedAddr) {
1010 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1011 return Error(NameLoc,
1012 "symbol with local linkage must have default visibility");
1013
1014 unsigned AddrSpace;
1015 bool IsConstant, IsExternallyInitialized;
1016 LocTy IsExternallyInitializedLoc;
1017 LocTy TyLoc;
1018
1019 Type *Ty = nullptr;
1020 if (ParseOptionalAddrSpace(AddrSpace) ||
1021 ParseOptionalToken(lltok::kw_externally_initialized,
1022 IsExternallyInitialized,
1023 &IsExternallyInitializedLoc) ||
1024 ParseGlobalType(IsConstant) ||
1025 ParseType(Ty, TyLoc))
1026 return true;
1027
1028 // If the linkage is specified and is external, then no initializer is
1029 // present.
1030 Constant *Init = nullptr;
1031 if (!HasLinkage ||
1032 !GlobalValue::isValidDeclarationLinkage(
1033 (GlobalValue::LinkageTypes)Linkage)) {
1034 if (ParseGlobalValue(Ty, Init))
1035 return true;
1036 }
1037
1038 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1039 return Error(TyLoc, "invalid type for global variable");
1040
1041 GlobalValue *GVal = nullptr;
1042
1043 // See if the global was forward referenced, if so, use the global.
1044 if (!Name.empty()) {
1045 GVal = M->getNamedValue(Name);
1046 if (GVal) {
1047 if (!ForwardRefVals.erase(Name))
1048 return Error(NameLoc, "redefinition of global '@" + Name + "'");
1049 }
1050 } else {
1051 auto I = ForwardRefValIDs.find(NumberedVals.size());
1052 if (I != ForwardRefValIDs.end()) {
1053 GVal = I->second.first;
1054 ForwardRefValIDs.erase(I);
1055 }
1056 }
1057
1058 GlobalVariable *GV;
1059 if (!GVal) {
1060 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1061 Name, nullptr, GlobalVariable::NotThreadLocal,
1062 AddrSpace);
1063 } else {
1064 if (GVal->getValueType() != Ty)
1065 return Error(TyLoc,
1066 "forward reference and definition of global have different types");
1067
1068 GV = cast<GlobalVariable>(GVal);
1069
1070 // Move the forward-reference to the correct spot in the module.
1071 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1072 }
1073
1074 if (Name.empty())
1075 NumberedVals.push_back(GV);
1076
1077 // Set the parsed properties on the global.
1078 if (Init)
1079 GV->setInitializer(Init);
1080 GV->setConstant(IsConstant);
1081 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1082 maybeSetDSOLocal(DSOLocal, *GV);
1083 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1084 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1085 GV->setExternallyInitialized(IsExternallyInitialized);
1086 GV->setThreadLocalMode(TLM);
1087 GV->setUnnamedAddr(UnnamedAddr);
1088
1089 // Parse attributes on the global.
1090 while (Lex.getKind() == lltok::comma) {
1091 Lex.Lex();
1092
1093 if (Lex.getKind() == lltok::kw_section) {
1094 Lex.Lex();
1095 GV->setSection(Lex.getStrVal());
1096 if (ParseToken(lltok::StringConstant, "expected global section string"))
1097 return true;
1098 } else if (Lex.getKind() == lltok::kw_align) {
1099 unsigned Alignment;
1100 if (ParseOptionalAlignment(Alignment)) return true;
1101 GV->setAlignment(Alignment);
1102 } else if (Lex.getKind() == lltok::MetadataVar) {
1103 if (ParseGlobalObjectMetadataAttachment(*GV))
1104 return true;
1105 } else {
1106 Comdat *C;
1107 if (parseOptionalComdat(Name, C))
1108 return true;
1109 if (C)
1110 GV->setComdat(C);
1111 else
1112 return TokError("unknown global variable property!");
1113 }
1114 }
1115
1116 AttrBuilder Attrs;
1117 LocTy BuiltinLoc;
1118 std::vector<unsigned> FwdRefAttrGrps;
1119 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1120 return true;
1121 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1122 GV->setAttributes(AttributeSet::get(Context, Attrs));
1123 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1124 }
1125
1126 return false;
1127}
1128
1129/// ParseUnnamedAttrGrp
1130/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1131bool LLParser::ParseUnnamedAttrGrp() {
1132 assert(Lex.getKind() == lltok::kw_attributes)((Lex.getKind() == lltok::kw_attributes) ? static_cast<void
> (0) : __assert_fail ("Lex.getKind() == lltok::kw_attributes"
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 1132, __PRETTY_FUNCTION__))
;
1133 LocTy AttrGrpLoc = Lex.getLoc();
1134 Lex.Lex();
1135
1136 if (Lex.getKind() != lltok::AttrGrpID)
1137 return TokError("expected attribute group id");
1138
1139 unsigned VarID = Lex.getUIntVal();
1140 std::vector<unsigned> unused;
1141 LocTy BuiltinLoc;
1142 Lex.Lex();
1143
1144 if (ParseToken(lltok::equal, "expected '=' here") ||
1145 ParseToken(lltok::lbrace, "expected '{' here") ||
1146 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1147 BuiltinLoc) ||
1148 ParseToken(lltok::rbrace, "expected end of attribute group"))
1149 return true;
1150
1151 if (!NumberedAttrBuilders[VarID].hasAttributes())
1152 return Error(AttrGrpLoc, "attribute group has no attributes");
1153
1154 return false;
1155}
1156
1157/// ParseFnAttributeValuePairs
1158/// ::= <attr> | <attr> '=' <value>
1159bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1160 std::vector<unsigned> &FwdRefAttrGrps,
1161 bool inAttrGrp, LocTy &BuiltinLoc) {
1162 bool HaveError = false;
1163
1164 B.clear();
1165
1166 while (true) {
1167 lltok::Kind Token = Lex.getKind();
1168 if (Token == lltok::kw_builtin)
1169 BuiltinLoc = Lex.getLoc();
1170 switch (Token) {
1171 default:
1172 if (!inAttrGrp) return HaveError;
1173 return Error(Lex.getLoc(), "unterminated attribute group");
1174 case lltok::rbrace:
1175 // Finished.
1176 return false;
1177
1178 case lltok::AttrGrpID: {
1179 // Allow a function to reference an attribute group:
1180 //
1181 // define void @foo() #1 { ... }
1182 if (inAttrGrp)
1183 HaveError |=
1184 Error(Lex.getLoc(),
1185 "cannot have an attribute group reference in an attribute group");
1186
1187 unsigned AttrGrpNum = Lex.getUIntVal();
1188 if (inAttrGrp) break;
1189
1190 // Save the reference to the attribute group. We'll fill it in later.
1191 FwdRefAttrGrps.push_back(AttrGrpNum);
1192 break;
1193 }
1194 // Target-dependent attributes:
1195 case lltok::StringConstant: {
1196 if (ParseStringAttribute(B))
1197 return true;
1198 continue;
1199 }
1200
1201 // Target-independent attributes:
1202 case lltok::kw_align: {
1203 // As a hack, we allow function alignment to be initially parsed as an
1204 // attribute on a function declaration/definition or added to an attribute
1205 // group and later moved to the alignment field.
1206 unsigned Alignment;
1207 if (inAttrGrp) {
1208 Lex.Lex();
1209 if (ParseToken(lltok::equal, "expected '=' here") ||
1210 ParseUInt32(Alignment))
1211 return true;
1212 } else {
1213 if (ParseOptionalAlignment(Alignment))
1214 return true;
1215 }
1216 B.addAlignmentAttr(Alignment);
1217 continue;
1218 }
1219 case lltok::kw_alignstack: {
1220 unsigned Alignment;
1221 if (inAttrGrp) {
1222 Lex.Lex();
1223 if (ParseToken(lltok::equal, "expected '=' here") ||
1224 ParseUInt32(Alignment))
1225 return true;
1226 } else {
1227 if (ParseOptionalStackAlignment(Alignment))
1228 return true;
1229 }
1230 B.addStackAlignmentAttr(Alignment);
1231 continue;
1232 }
1233 case lltok::kw_allocsize: {
1234 unsigned ElemSizeArg;
1235 Optional<unsigned> NumElemsArg;
1236 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1237 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1238 return true;
1239 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1240 continue;
1241 }
1242 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1243 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1244 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1245 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1246 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1247 case lltok::kw_inaccessiblememonly:
1248 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1249 case lltok::kw_inaccessiblemem_or_argmemonly:
1250 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1251 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1252 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1253 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1254 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1255 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1256 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1257 case lltok::kw_noimplicitfloat:
1258 B.addAttribute(Attribute::NoImplicitFloat); break;
1259 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1260 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1261 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1262 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1263 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1264 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1265 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1266 case lltok::kw_optforfuzzing:
1267 B.addAttribute(Attribute::OptForFuzzing); break;
1268 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1269 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1270 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1271 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1272 case lltok::kw_returns_twice:
1273 B.addAttribute(Attribute::ReturnsTwice); break;
1274 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1275 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1276 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1277 case lltok::kw_sspstrong:
1278 B.addAttribute(Attribute::StackProtectStrong); break;
1279 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1280 case lltok::kw_shadowcallstack:
1281 B.addAttribute(Attribute::ShadowCallStack); break;
1282 case lltok::kw_sanitize_address:
1283 B.addAttribute(Attribute::SanitizeAddress); break;
1284 case lltok::kw_sanitize_hwaddress:
1285 B.addAttribute(Attribute::SanitizeHWAddress); break;
1286 case lltok::kw_sanitize_thread:
1287 B.addAttribute(Attribute::SanitizeThread); break;
1288 case lltok::kw_sanitize_memory:
1289 B.addAttribute(Attribute::SanitizeMemory); break;
1290 case lltok::kw_speculative_load_hardening:
1291 B.addAttribute(Attribute::SpeculativeLoadHardening);
1292 break;
1293 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1294 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1295 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1296
1297 // Error handling.
1298 case lltok::kw_inreg:
1299 case lltok::kw_signext:
1300 case lltok::kw_zeroext:
1301 HaveError |=
1302 Error(Lex.getLoc(),
1303 "invalid use of attribute on a function");
1304 break;
1305 case lltok::kw_byval:
1306 case lltok::kw_dereferenceable:
1307 case lltok::kw_dereferenceable_or_null:
1308 case lltok::kw_inalloca:
1309 case lltok::kw_nest:
1310 case lltok::kw_noalias:
1311 case lltok::kw_nocapture:
1312 case lltok::kw_nonnull:
1313 case lltok::kw_returned:
1314 case lltok::kw_sret:
1315 case lltok::kw_swifterror:
1316 case lltok::kw_swiftself:
1317 case lltok::kw_immarg:
1318 HaveError |=
1319 Error(Lex.getLoc(),
1320 "invalid use of parameter-only attribute on a function");
1321 break;
1322 }
1323
1324 Lex.Lex();
1325 }
1326}
1327
1328//===----------------------------------------------------------------------===//
1329// GlobalValue Reference/Resolution Routines.
1330//===----------------------------------------------------------------------===//
1331
1332static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1333 const std::string &Name) {
1334 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1335 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1336 PTy->getAddressSpace(), Name, M);
1337 else
1338 return new GlobalVariable(*M, PTy->getElementType(), false,
1339 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1340 nullptr, GlobalVariable::NotThreadLocal,
1341 PTy->getAddressSpace());
1342}
1343
1344Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1345 Value *Val, bool IsCall) {
1346 if (Val->getType() == Ty)
1347 return Val;
1348 // For calls we also accept variables in the program address space.
1349 Type *SuggestedTy = Ty;
1350 if (IsCall && isa<PointerType>(Ty)) {
1351 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1352 M->getDataLayout().getProgramAddressSpace());
1353 SuggestedTy = TyInProgAS;
1354 if (Val->getType() == TyInProgAS)
1355 return Val;
1356 }
1357 if (Ty->isLabelTy())
1358 Error(Loc, "'" + Name + "' is not a basic block");
1359 else
1360 Error(Loc, "'" + Name + "' defined with type '" +
1361 getTypeString(Val->getType()) + "' but expected '" +
1362 getTypeString(SuggestedTy) + "'");
1363 return nullptr;
1364}
1365
1366/// GetGlobalVal - Get a value with the specified name or ID, creating a
1367/// forward reference record if needed. This can return null if the value
1368/// exists but does not have the right type.
1369GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1370 LocTy Loc, bool IsCall) {
1371 PointerType *PTy = dyn_cast<PointerType>(Ty);
1372 if (!PTy) {
1373 Error(Loc, "global variable reference must have pointer type");
1374 return nullptr;
1375 }
1376
1377 // Look this name up in the normal function symbol table.
1378 GlobalValue *Val =
1379 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1380
1381 // If this is a forward reference for the value, see if we already created a
1382 // forward ref record.
1383 if (!Val) {
1384 auto I = ForwardRefVals.find(Name);
1385 if (I != ForwardRefVals.end())
1386 Val = I->second.first;
1387 }
1388
1389 // If we have the value in the symbol table or fwd-ref table, return it.
1390 if (Val)
1391 return cast_or_null<GlobalValue>(
1392 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1393
1394 // Otherwise, create a new forward reference for this value and remember it.
1395 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1396 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1397 return FwdVal;
1398}
1399
1400GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1401 bool IsCall) {
1402 PointerType *PTy = dyn_cast<PointerType>(Ty);
1403 if (!PTy) {
1404 Error(Loc, "global variable reference must have pointer type");
1405 return nullptr;
1406 }
1407
1408 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1409
1410 // If this is a forward reference for the value, see if we already created a
1411 // forward ref record.
1412 if (!Val) {
1413 auto I = ForwardRefValIDs.find(ID);
1414 if (I != ForwardRefValIDs.end())
1415 Val = I->second.first;
1416 }
1417
1418 // If we have the value in the symbol table or fwd-ref table, return it.
1419 if (Val)
1420 return cast_or_null<GlobalValue>(
1421 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1422
1423 // Otherwise, create a new forward reference for this value and remember it.
1424 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1425 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1426 return FwdVal;
1427}
1428
1429//===----------------------------------------------------------------------===//
1430// Comdat Reference/Resolution Routines.
1431//===----------------------------------------------------------------------===//
1432
1433Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1434 // Look this name up in the comdat symbol table.
1435 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1436 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1437 if (I != ComdatSymTab.end())
1438 return &I->second;
1439
1440 // Otherwise, create a new forward reference for this value and remember it.
1441 Comdat *C = M->getOrInsertComdat(Name);
1442 ForwardRefComdats[Name] = Loc;
1443 return C;
1444}
1445
1446//===----------------------------------------------------------------------===//
1447// Helper Routines.
1448//===----------------------------------------------------------------------===//
1449
1450/// ParseToken - If the current token has the specified kind, eat it and return
1451/// success. Otherwise, emit the specified error and return failure.
1452bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1453 if (Lex.getKind() != T)
1454 return TokError(ErrMsg);
1455 Lex.Lex();
1456 return false;
1457}
1458
1459/// ParseStringConstant
1460/// ::= StringConstant
1461bool LLParser::ParseStringConstant(std::string &Result) {
1462 if (Lex.getKind() != lltok::StringConstant)
1463 return TokError("expected string constant");
1464 Result = Lex.getStrVal();
1465 Lex.Lex();
1466 return false;
1467}
1468
1469/// ParseUInt32
1470/// ::= uint32
1471bool LLParser::ParseUInt32(uint32_t &Val) {
1472 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1473 return TokError("expected integer");
1474 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1475 if (Val64 != unsigned(Val64))
1476 return TokError("expected 32-bit integer (too large)");
1477 Val = Val64;
1478 Lex.Lex();
1479 return false;
1480}
1481
1482/// ParseUInt64
1483/// ::= uint64
1484bool LLParser::ParseUInt64(uint64_t &Val) {
1485 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1486 return TokError("expected integer");
1487 Val = Lex.getAPSIntVal().getLimitedValue();
1488 Lex.Lex();
1489 return false;
1490}
1491
1492/// ParseTLSModel
1493/// := 'localdynamic'
1494/// := 'initialexec'
1495/// := 'localexec'
1496bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1497 switch (Lex.getKind()) {
1498 default:
1499 return TokError("expected localdynamic, initialexec or localexec");
1500 case lltok::kw_localdynamic:
1501 TLM = GlobalVariable::LocalDynamicTLSModel;
1502 break;
1503 case lltok::kw_initialexec:
1504 TLM = GlobalVariable::InitialExecTLSModel;
1505 break;
1506 case lltok::kw_localexec:
1507 TLM = GlobalVariable::LocalExecTLSModel;
1508 break;
1509 }
1510
1511 Lex.Lex();
1512 return false;
1513}
1514
1515/// ParseOptionalThreadLocal
1516/// := /*empty*/
1517/// := 'thread_local'
1518/// := 'thread_local' '(' tlsmodel ')'
1519bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1520 TLM = GlobalVariable::NotThreadLocal;
1521 if (!EatIfPresent(lltok::kw_thread_local))
1522 return false;
1523
1524 TLM = GlobalVariable::GeneralDynamicTLSModel;
1525 if (Lex.getKind() == lltok::lparen) {
1526 Lex.Lex();
1527 return ParseTLSModel(TLM) ||
1528 ParseToken(lltok::rparen, "expected ')' after thread local model");
1529 }
1530 return false;
1531}
1532
1533/// ParseOptionalAddrSpace
1534/// := /*empty*/
1535/// := 'addrspace' '(' uint32 ')'
1536bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1537 AddrSpace = DefaultAS;
1538 if (!EatIfPresent(lltok::kw_addrspace))
1539 return false;
1540 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1541 ParseUInt32(AddrSpace) ||
1542 ParseToken(lltok::rparen, "expected ')' in address space");
1543}
1544
1545/// ParseStringAttribute
1546/// := StringConstant
1547/// := StringConstant '=' StringConstant
1548bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1549 std::string Attr = Lex.getStrVal();
1550 Lex.Lex();
1551 std::string Val;
1552 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1553 return true;
1554 B.addAttribute(Attr, Val);
1555 return false;
1556}
1557
1558/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1559bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1560 bool HaveError = false;
1561
1562 B.clear();
1563
1564 while (true) {
1565 lltok::Kind Token = Lex.getKind();
1566 switch (Token) {
1567 default: // End of attributes.
1568 return HaveError;
1569 case lltok::StringConstant: {
1570 if (ParseStringAttribute(B))
1571 return true;
1572 continue;
1573 }
1574 case lltok::kw_align: {
1575 unsigned Alignment;
1576 if (ParseOptionalAlignment(Alignment))
1577 return true;
1578 B.addAlignmentAttr(Alignment);
1579 continue;
1580 }
1581 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1582 case lltok::kw_dereferenceable: {
1583 uint64_t Bytes;
1584 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1585 return true;
1586 B.addDereferenceableAttr(Bytes);
1587 continue;
1588 }
1589 case lltok::kw_dereferenceable_or_null: {
1590 uint64_t Bytes;
1591 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1592 return true;
1593 B.addDereferenceableOrNullAttr(Bytes);
1594 continue;
1595 }
1596 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1597 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1598 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1599 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1600 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1601 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1602 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1603 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1604 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1605 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1606 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1607 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1608 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1609 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1610 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1611 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1612
1613 case lltok::kw_alignstack:
1614 case lltok::kw_alwaysinline:
1615 case lltok::kw_argmemonly:
1616 case lltok::kw_builtin:
1617 case lltok::kw_inlinehint:
1618 case lltok::kw_jumptable:
1619 case lltok::kw_minsize:
1620 case lltok::kw_naked:
1621 case lltok::kw_nobuiltin:
1622 case lltok::kw_noduplicate:
1623 case lltok::kw_noimplicitfloat:
1624 case lltok::kw_noinline:
1625 case lltok::kw_nonlazybind:
1626 case lltok::kw_noredzone:
1627 case lltok::kw_noreturn:
1628 case lltok::kw_nocf_check:
1629 case lltok::kw_nounwind:
1630 case lltok::kw_optforfuzzing:
1631 case lltok::kw_optnone:
1632 case lltok::kw_optsize:
1633 case lltok::kw_returns_twice:
1634 case lltok::kw_sanitize_address:
1635 case lltok::kw_sanitize_hwaddress:
1636 case lltok::kw_sanitize_memory:
1637 case lltok::kw_sanitize_thread:
1638 case lltok::kw_speculative_load_hardening:
1639 case lltok::kw_ssp:
1640 case lltok::kw_sspreq:
1641 case lltok::kw_sspstrong:
1642 case lltok::kw_safestack:
1643 case lltok::kw_shadowcallstack:
1644 case lltok::kw_strictfp:
1645 case lltok::kw_uwtable:
1646 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1647 break;
1648 }
1649
1650 Lex.Lex();
1651 }
1652}
1653
1654/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1655bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1656 bool HaveError = false;
1657
1658 B.clear();
1659
1660 while (true) {
1661 lltok::Kind Token = Lex.getKind();
1662 switch (Token) {
1663 default: // End of attributes.
1664 return HaveError;
1665 case lltok::StringConstant: {
1666 if (ParseStringAttribute(B))
1667 return true;
1668 continue;
1669 }
1670 case lltok::kw_dereferenceable: {
1671 uint64_t Bytes;
1672 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1673 return true;
1674 B.addDereferenceableAttr(Bytes);
1675 continue;
1676 }
1677 case lltok::kw_dereferenceable_or_null: {
1678 uint64_t Bytes;
1679 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1680 return true;
1681 B.addDereferenceableOrNullAttr(Bytes);
1682 continue;
1683 }
1684 case lltok::kw_align: {
1685 unsigned Alignment;
1686 if (ParseOptionalAlignment(Alignment))
1687 return true;
1688 B.addAlignmentAttr(Alignment);
1689 continue;
1690 }
1691 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1692 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1693 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1694 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1695 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1696
1697 // Error handling.
1698 case lltok::kw_byval:
1699 case lltok::kw_inalloca:
1700 case lltok::kw_nest:
1701 case lltok::kw_nocapture:
1702 case lltok::kw_returned:
1703 case lltok::kw_sret:
1704 case lltok::kw_swifterror:
1705 case lltok::kw_swiftself:
1706 case lltok::kw_immarg:
1707 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1708 break;
1709
1710 case lltok::kw_alignstack:
1711 case lltok::kw_alwaysinline:
1712 case lltok::kw_argmemonly:
1713 case lltok::kw_builtin:
1714 case lltok::kw_cold:
1715 case lltok::kw_inlinehint:
1716 case lltok::kw_jumptable:
1717 case lltok::kw_minsize:
1718 case lltok::kw_naked:
1719 case lltok::kw_nobuiltin:
1720 case lltok::kw_noduplicate:
1721 case lltok::kw_noimplicitfloat:
1722 case lltok::kw_noinline:
1723 case lltok::kw_nonlazybind:
1724 case lltok::kw_noredzone:
1725 case lltok::kw_noreturn:
1726 case lltok::kw_nocf_check:
1727 case lltok::kw_nounwind:
1728 case lltok::kw_optforfuzzing:
1729 case lltok::kw_optnone:
1730 case lltok::kw_optsize:
1731 case lltok::kw_returns_twice:
1732 case lltok::kw_sanitize_address:
1733 case lltok::kw_sanitize_hwaddress:
1734 case lltok::kw_sanitize_memory:
1735 case lltok::kw_sanitize_thread:
1736 case lltok::kw_speculative_load_hardening:
1737 case lltok::kw_ssp:
1738 case lltok::kw_sspreq:
1739 case lltok::kw_sspstrong:
1740 case lltok::kw_safestack:
1741 case lltok::kw_shadowcallstack:
1742 case lltok::kw_strictfp:
1743 case lltok::kw_uwtable:
1744 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1745 break;
1746
1747 case lltok::kw_readnone:
1748 case lltok::kw_readonly:
1749 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1750 }
1751
1752 Lex.Lex();
1753 }
1754}
1755
1756static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1757 HasLinkage = true;
1758 switch (Kind) {
1759 default:
1760 HasLinkage = false;
1761 return GlobalValue::ExternalLinkage;
1762 case lltok::kw_private:
1763 return GlobalValue::PrivateLinkage;
1764 case lltok::kw_internal:
1765 return GlobalValue::InternalLinkage;
1766 case lltok::kw_weak:
1767 return GlobalValue::WeakAnyLinkage;
1768 case lltok::kw_weak_odr:
1769 return GlobalValue::WeakODRLinkage;
1770 case lltok::kw_linkonce:
1771 return GlobalValue::LinkOnceAnyLinkage;
1772 case lltok::kw_linkonce_odr:
1773 return GlobalValue::LinkOnceODRLinkage;
1774 case lltok::kw_available_externally:
1775 return GlobalValue::AvailableExternallyLinkage;
1776 case lltok::kw_appending:
1777 return GlobalValue::AppendingLinkage;
1778 case lltok::kw_common:
1779 return GlobalValue::CommonLinkage;
1780 case lltok::kw_extern_weak:
1781 return GlobalValue::ExternalWeakLinkage;
1782 case lltok::kw_external:
1783 return GlobalValue::ExternalLinkage;
1784 }
1785}
1786
1787/// ParseOptionalLinkage
1788/// ::= /*empty*/
1789/// ::= 'private'
1790/// ::= 'internal'
1791/// ::= 'weak'
1792/// ::= 'weak_odr'
1793/// ::= 'linkonce'
1794/// ::= 'linkonce_odr'
1795/// ::= 'available_externally'
1796/// ::= 'appending'
1797/// ::= 'common'
1798/// ::= 'extern_weak'
1799/// ::= 'external'
1800bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1801 unsigned &Visibility,
1802 unsigned &DLLStorageClass,
1803 bool &DSOLocal) {
1804 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1805 if (HasLinkage)
1806 Lex.Lex();
1807 ParseOptionalDSOLocal(DSOLocal);
1808 ParseOptionalVisibility(Visibility);
1809 ParseOptionalDLLStorageClass(DLLStorageClass);
1810
1811 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1812 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1813 }
1814
1815 return false;
1816}
1817
1818void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1819 switch (Lex.getKind()) {
1820 default:
1821 DSOLocal = false;
1822 break;
1823 case lltok::kw_dso_local:
1824 DSOLocal = true;
1825 Lex.Lex();
1826 break;
1827 case lltok::kw_dso_preemptable:
1828 DSOLocal = false;
1829 Lex.Lex();
1830 break;
1831 }
1832}
1833
1834/// ParseOptionalVisibility
1835/// ::= /*empty*/
1836/// ::= 'default'
1837/// ::= 'hidden'
1838/// ::= 'protected'
1839///
1840void LLParser::ParseOptionalVisibility(unsigned &Res) {
1841 switch (Lex.getKind()) {
1842 default:
1843 Res = GlobalValue::DefaultVisibility;
1844 return;
1845 case lltok::kw_default:
1846 Res = GlobalValue::DefaultVisibility;
1847 break;
1848 case lltok::kw_hidden:
1849 Res = GlobalValue::HiddenVisibility;
1850 break;
1851 case lltok::kw_protected:
1852 Res = GlobalValue::ProtectedVisibility;
1853 break;
1854 }
1855 Lex.Lex();
1856}
1857
1858/// ParseOptionalDLLStorageClass
1859/// ::= /*empty*/
1860/// ::= 'dllimport'
1861/// ::= 'dllexport'
1862///
1863void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1864 switch (Lex.getKind()) {
1865 default:
1866 Res = GlobalValue::DefaultStorageClass;
1867 return;
1868 case lltok::kw_dllimport:
1869 Res = GlobalValue::DLLImportStorageClass;
1870 break;
1871 case lltok::kw_dllexport:
1872 Res = GlobalValue::DLLExportStorageClass;
1873 break;
1874 }
1875 Lex.Lex();
1876}
1877
1878/// ParseOptionalCallingConv
1879/// ::= /*empty*/
1880/// ::= 'ccc'
1881/// ::= 'fastcc'
1882/// ::= 'intel_ocl_bicc'
1883/// ::= 'coldcc'
1884/// ::= 'x86_stdcallcc'
1885/// ::= 'x86_fastcallcc'
1886/// ::= 'x86_thiscallcc'
1887/// ::= 'x86_vectorcallcc'
1888/// ::= 'arm_apcscc'
1889/// ::= 'arm_aapcscc'
1890/// ::= 'arm_aapcs_vfpcc'
1891/// ::= 'aarch64_vector_pcs'
1892/// ::= 'msp430_intrcc'
1893/// ::= 'avr_intrcc'
1894/// ::= 'avr_signalcc'
1895/// ::= 'ptx_kernel'
1896/// ::= 'ptx_device'
1897/// ::= 'spir_func'
1898/// ::= 'spir_kernel'
1899/// ::= 'x86_64_sysvcc'
1900/// ::= 'win64cc'
1901/// ::= 'webkit_jscc'
1902/// ::= 'anyregcc'
1903/// ::= 'preserve_mostcc'
1904/// ::= 'preserve_allcc'
1905/// ::= 'ghccc'
1906/// ::= 'swiftcc'
1907/// ::= 'x86_intrcc'
1908/// ::= 'hhvmcc'
1909/// ::= 'hhvm_ccc'
1910/// ::= 'cxx_fast_tlscc'
1911/// ::= 'amdgpu_vs'
1912/// ::= 'amdgpu_ls'
1913/// ::= 'amdgpu_hs'
1914/// ::= 'amdgpu_es'
1915/// ::= 'amdgpu_gs'
1916/// ::= 'amdgpu_ps'
1917/// ::= 'amdgpu_cs'
1918/// ::= 'amdgpu_kernel'
1919/// ::= 'cc' UINT
1920///
1921bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1922 switch (Lex.getKind()) {
1923 default: CC = CallingConv::C; return false;
1924 case lltok::kw_ccc: CC = CallingConv::C; break;
1925 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1926 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1927 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1928 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1929 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1930 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1931 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1932 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1933 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1934 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1935 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1936 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1937 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1938 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1939 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1940 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1941 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1942 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1943 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1944 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1945 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1946 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1947 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1948 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1949 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1950 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1951 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1952 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1953 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1954 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1955 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1956 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1957 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1958 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1959 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1960 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1961 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1962 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1963 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1964 case lltok::kw_cc: {
1965 Lex.Lex();
1966 return ParseUInt32(CC);
1967 }
1968 }
1969
1970 Lex.Lex();
1971 return false;
1972}
1973
1974/// ParseMetadataAttachment
1975/// ::= !dbg !42
1976bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1977 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment")((Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata attachment\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 1977, __PRETTY_FUNCTION__))
;
1978
1979 std::string Name = Lex.getStrVal();
1980 Kind = M->getMDKindID(Name);
1981 Lex.Lex();
1982
1983 return ParseMDNode(MD);
1984}
1985
1986/// ParseInstructionMetadata
1987/// ::= !dbg !42 (',' !dbg !57)*
1988bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1989 do {
1990 if (Lex.getKind() != lltok::MetadataVar)
1991 return TokError("expected metadata after comma");
1992
1993 unsigned MDK;
1994 MDNode *N;
1995 if (ParseMetadataAttachment(MDK, N))
1996 return true;
1997
1998 Inst.setMetadata(MDK, N);
1999 if (MDK == LLVMContext::MD_tbaa)
2000 InstsWithTBAATag.push_back(&Inst);
2001
2002 // If this is the end of the list, we're done.
2003 } while (EatIfPresent(lltok::comma));
2004 return false;
2005}
2006
2007/// ParseGlobalObjectMetadataAttachment
2008/// ::= !dbg !57
2009bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2010 unsigned MDK;
2011 MDNode *N;
2012 if (ParseMetadataAttachment(MDK, N))
2013 return true;
2014
2015 GO.addMetadata(MDK, *N);
2016 return false;
2017}
2018
2019/// ParseOptionalFunctionMetadata
2020/// ::= (!dbg !57)*
2021bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2022 while (Lex.getKind() == lltok::MetadataVar)
2023 if (ParseGlobalObjectMetadataAttachment(F))
2024 return true;
2025 return false;
2026}
2027
2028/// ParseOptionalAlignment
2029/// ::= /* empty */
2030/// ::= 'align' 4
2031bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2032 Alignment = 0;
2033 if (!EatIfPresent(lltok::kw_align))
2034 return false;
2035 LocTy AlignLoc = Lex.getLoc();
2036 if (ParseUInt32(Alignment)) return true;
2037 if (!isPowerOf2_32(Alignment))
2038 return Error(AlignLoc, "alignment is not a power of two");
2039 if (Alignment > Value::MaximumAlignment)
2040 return Error(AlignLoc, "huge alignments are not supported yet");
2041 return false;
2042}
2043
2044/// ParseOptionalDerefAttrBytes
2045/// ::= /* empty */
2046/// ::= AttrKind '(' 4 ')'
2047///
2048/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2049bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2050 uint64_t &Bytes) {
2051 assert((AttrKind == lltok::kw_dereferenceable ||(((AttrKind == lltok::kw_dereferenceable || AttrKind == lltok
::kw_dereferenceable_or_null) && "contract!") ? static_cast
<void> (0) : __assert_fail ("(AttrKind == lltok::kw_dereferenceable || AttrKind == lltok::kw_dereferenceable_or_null) && \"contract!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 2053, __PRETTY_FUNCTION__))
2052 AttrKind == lltok::kw_dereferenceable_or_null) &&(((AttrKind == lltok::kw_dereferenceable || AttrKind == lltok
::kw_dereferenceable_or_null) && "contract!") ? static_cast
<void> (0) : __assert_fail ("(AttrKind == lltok::kw_dereferenceable || AttrKind == lltok::kw_dereferenceable_or_null) && \"contract!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 2053, __PRETTY_FUNCTION__))
2053 "contract!")(((AttrKind == lltok::kw_dereferenceable || AttrKind == lltok
::kw_dereferenceable_or_null) && "contract!") ? static_cast
<void> (0) : __assert_fail ("(AttrKind == lltok::kw_dereferenceable || AttrKind == lltok::kw_dereferenceable_or_null) && \"contract!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 2053, __PRETTY_FUNCTION__))
;
2054
2055 Bytes = 0;
2056 if (!EatIfPresent(AttrKind))
2057 return false;
2058 LocTy ParenLoc = Lex.getLoc();
2059 if (!EatIfPresent(lltok::lparen))
2060 return Error(ParenLoc, "expected '('");
2061 LocTy DerefLoc = Lex.getLoc();
2062 if (ParseUInt64(Bytes)) return true;
2063 ParenLoc = Lex.getLoc();
2064 if (!EatIfPresent(lltok::rparen))
2065 return Error(ParenLoc, "expected ')'");
2066 if (!Bytes)
2067 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2068 return false;
2069}
2070
2071/// ParseOptionalCommaAlign
2072/// ::=
2073/// ::= ',' align 4
2074///
2075/// This returns with AteExtraComma set to true if it ate an excess comma at the
2076/// end.
2077bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2078 bool &AteExtraComma) {
2079 AteExtraComma = false;
2080 while (EatIfPresent(lltok::comma)) {
2081 // Metadata at the end is an early exit.
2082 if (Lex.getKind() == lltok::MetadataVar) {
2083 AteExtraComma = true;
2084 return false;
2085 }
2086
2087 if (Lex.getKind() != lltok::kw_align)
2088 return Error(Lex.getLoc(), "expected metadata or 'align'");
2089
2090 if (ParseOptionalAlignment(Alignment)) return true;
2091 }
2092
2093 return false;
2094}
2095
2096/// ParseOptionalCommaAddrSpace
2097/// ::=
2098/// ::= ',' addrspace(1)
2099///
2100/// This returns with AteExtraComma set to true if it ate an excess comma at the
2101/// end.
2102bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2103 LocTy &Loc,
2104 bool &AteExtraComma) {
2105 AteExtraComma = false;
2106 while (EatIfPresent(lltok::comma)) {
2107 // Metadata at the end is an early exit.
2108 if (Lex.getKind() == lltok::MetadataVar) {
2109 AteExtraComma = true;
2110 return false;
2111 }
2112
2113 Loc = Lex.getLoc();
2114 if (Lex.getKind() != lltok::kw_addrspace)
2115 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2116
2117 if (ParseOptionalAddrSpace(AddrSpace))
2118 return true;
2119 }
2120
2121 return false;
2122}
2123
2124bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2125 Optional<unsigned> &HowManyArg) {
2126 Lex.Lex();
2127
2128 auto StartParen = Lex.getLoc();
2129 if (!EatIfPresent(lltok::lparen))
2130 return Error(StartParen, "expected '('");
2131
2132 if (ParseUInt32(BaseSizeArg))
2133 return true;
2134
2135 if (EatIfPresent(lltok::comma)) {
2136 auto HowManyAt = Lex.getLoc();
2137 unsigned HowMany;
2138 if (ParseUInt32(HowMany))
2139 return true;
2140 if (HowMany == BaseSizeArg)
2141 return Error(HowManyAt,
2142 "'allocsize' indices can't refer to the same parameter");
2143 HowManyArg = HowMany;
2144 } else
2145 HowManyArg = None;
2146
2147 auto EndParen = Lex.getLoc();
2148 if (!EatIfPresent(lltok::rparen))
2149 return Error(EndParen, "expected ')'");
2150 return false;
2151}
2152
2153/// ParseScopeAndOrdering
2154/// if isAtomic: ::= SyncScope? AtomicOrdering
2155/// else: ::=
2156///
2157/// This sets Scope and Ordering to the parsed values.
2158bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2159 AtomicOrdering &Ordering) {
2160 if (!isAtomic)
2161 return false;
2162
2163 return ParseScope(SSID) || ParseOrdering(Ordering);
2164}
2165
2166/// ParseScope
2167/// ::= syncscope("singlethread" | "<target scope>")?
2168///
2169/// This sets synchronization scope ID to the ID of the parsed value.
2170bool LLParser::ParseScope(SyncScope::ID &SSID) {
2171 SSID = SyncScope::System;
2172 if (EatIfPresent(lltok::kw_syncscope)) {
2173 auto StartParenAt = Lex.getLoc();
2174 if (!EatIfPresent(lltok::lparen))
2175 return Error(StartParenAt, "Expected '(' in syncscope");
2176
2177 std::string SSN;
2178 auto SSNAt = Lex.getLoc();
2179 if (ParseStringConstant(SSN))
2180 return Error(SSNAt, "Expected synchronization scope name");
2181
2182 auto EndParenAt = Lex.getLoc();
2183 if (!EatIfPresent(lltok::rparen))
2184 return Error(EndParenAt, "Expected ')' in syncscope");
2185
2186 SSID = Context.getOrInsertSyncScopeID(SSN);
2187 }
2188
2189 return false;
2190}
2191
2192/// ParseOrdering
2193/// ::= AtomicOrdering
2194///
2195/// This sets Ordering to the parsed value.
2196bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2197 switch (Lex.getKind()) {
2198 default: return TokError("Expected ordering on atomic instruction");
2199 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2200 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2201 // Not specified yet:
2202 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2203 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2204 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2205 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2206 case lltok::kw_seq_cst:
2207 Ordering = AtomicOrdering::SequentiallyConsistent;
2208 break;
2209 }
2210 Lex.Lex();
2211 return false;
2212}
2213
2214/// ParseOptionalStackAlignment
2215/// ::= /* empty */
2216/// ::= 'alignstack' '(' 4 ')'
2217bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2218 Alignment = 0;
2219 if (!EatIfPresent(lltok::kw_alignstack))
2220 return false;
2221 LocTy ParenLoc = Lex.getLoc();
2222 if (!EatIfPresent(lltok::lparen))
2223 return Error(ParenLoc, "expected '('");
2224 LocTy AlignLoc = Lex.getLoc();
2225 if (ParseUInt32(Alignment)) return true;
2226 ParenLoc = Lex.getLoc();
2227 if (!EatIfPresent(lltok::rparen))
2228 return Error(ParenLoc, "expected ')'");
2229 if (!isPowerOf2_32(Alignment))
2230 return Error(AlignLoc, "stack alignment is not a power of two");
2231 return false;
2232}
2233
2234/// ParseIndexList - This parses the index list for an insert/extractvalue
2235/// instruction. This sets AteExtraComma in the case where we eat an extra
2236/// comma at the end of the line and find that it is followed by metadata.
2237/// Clients that don't allow metadata can call the version of this function that
2238/// only takes one argument.
2239///
2240/// ParseIndexList
2241/// ::= (',' uint32)+
2242///
2243bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2244 bool &AteExtraComma) {
2245 AteExtraComma = false;
2246
2247 if (Lex.getKind() != lltok::comma)
2248 return TokError("expected ',' as start of index list");
2249
2250 while (EatIfPresent(lltok::comma)) {
2251 if (Lex.getKind() == lltok::MetadataVar) {
2252 if (Indices.empty()) return TokError("expected index");
2253 AteExtraComma = true;
2254 return false;
2255 }
2256 unsigned Idx = 0;
2257 if (ParseUInt32(Idx)) return true;
2258 Indices.push_back(Idx);
2259 }
2260
2261 return false;
2262}
2263
2264//===----------------------------------------------------------------------===//
2265// Type Parsing.
2266//===----------------------------------------------------------------------===//
2267
2268/// ParseType - Parse a type.
2269bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2270 SMLoc TypeLoc = Lex.getLoc();
2271 switch (Lex.getKind()) {
2272 default:
2273 return TokError(Msg);
2274 case lltok::Type:
2275 // Type ::= 'float' | 'void' (etc)
2276 Result = Lex.getTyVal();
2277 Lex.Lex();
2278 break;
2279 case lltok::lbrace:
2280 // Type ::= StructType
2281 if (ParseAnonStructType(Result, false))
2282 return true;
2283 break;
2284 case lltok::lsquare:
2285 // Type ::= '[' ... ']'
2286 Lex.Lex(); // eat the lsquare.
2287 if (ParseArrayVectorType(Result, false))
2288 return true;
2289 break;
2290 case lltok::less: // Either vector or packed struct.
2291 // Type ::= '<' ... '>'
2292 Lex.Lex();
2293 if (Lex.getKind() == lltok::lbrace) {
2294 if (ParseAnonStructType(Result, true) ||
2295 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2296 return true;
2297 } else if (ParseArrayVectorType(Result, true))
2298 return true;
2299 break;
2300 case lltok::LocalVar: {
2301 // Type ::= %foo
2302 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2303
2304 // If the type hasn't been defined yet, create a forward definition and
2305 // remember where that forward def'n was seen (in case it never is defined).
2306 if (!Entry.first) {
2307 Entry.first = StructType::create(Context, Lex.getStrVal());
2308 Entry.second = Lex.getLoc();
2309 }
2310 Result = Entry.first;
2311 Lex.Lex();
2312 break;
2313 }
2314
2315 case lltok::LocalVarID: {
2316 // Type ::= %4
2317 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2318
2319 // If the type hasn't been defined yet, create a forward definition and
2320 // remember where that forward def'n was seen (in case it never is defined).
2321 if (!Entry.first) {
2322 Entry.first = StructType::create(Context);
2323 Entry.second = Lex.getLoc();
2324 }
2325 Result = Entry.first;
2326 Lex.Lex();
2327 break;
2328 }
2329 }
2330
2331 // Parse the type suffixes.
2332 while (true) {
2333 switch (Lex.getKind()) {
2334 // End of type.
2335 default:
2336 if (!AllowVoid && Result->isVoidTy())
2337 return Error(TypeLoc, "void type only allowed for function results");
2338 return false;
2339
2340 // Type ::= Type '*'
2341 case lltok::star:
2342 if (Result->isLabelTy())
2343 return TokError("basic block pointers are invalid");
2344 if (Result->isVoidTy())
2345 return TokError("pointers to void are invalid - use i8* instead");
2346 if (!PointerType::isValidElementType(Result))
2347 return TokError("pointer to this type is invalid");
2348 Result = PointerType::getUnqual(Result);
2349 Lex.Lex();
2350 break;
2351
2352 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2353 case lltok::kw_addrspace: {
2354 if (Result->isLabelTy())
2355 return TokError("basic block pointers are invalid");
2356 if (Result->isVoidTy())
2357 return TokError("pointers to void are invalid; use i8* instead");
2358 if (!PointerType::isValidElementType(Result))
2359 return TokError("pointer to this type is invalid");
2360 unsigned AddrSpace;
2361 if (ParseOptionalAddrSpace(AddrSpace) ||
2362 ParseToken(lltok::star, "expected '*' in address space"))
2363 return true;
2364
2365 Result = PointerType::get(Result, AddrSpace);
2366 break;
2367 }
2368
2369 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2370 case lltok::lparen:
2371 if (ParseFunctionType(Result))
2372 return true;
2373 break;
2374 }
2375 }
2376}
2377
2378/// ParseParameterList
2379/// ::= '(' ')'
2380/// ::= '(' Arg (',' Arg)* ')'
2381/// Arg
2382/// ::= Type OptionalAttributes Value OptionalAttributes
2383bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2384 PerFunctionState &PFS, bool IsMustTailCall,
2385 bool InVarArgsFunc) {
2386 if (ParseToken(lltok::lparen, "expected '(' in call"))
2387 return true;
2388
2389 while (Lex.getKind() != lltok::rparen) {
2390 // If this isn't the first argument, we need a comma.
2391 if (!ArgList.empty() &&
2392 ParseToken(lltok::comma, "expected ',' in argument list"))
2393 return true;
2394
2395 // Parse an ellipsis if this is a musttail call in a variadic function.
2396 if (Lex.getKind() == lltok::dotdotdot) {
2397 const char *Msg = "unexpected ellipsis in argument list for ";
2398 if (!IsMustTailCall)
2399 return TokError(Twine(Msg) + "non-musttail call");
2400 if (!InVarArgsFunc)
2401 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2402 Lex.Lex(); // Lex the '...', it is purely for readability.
2403 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2404 }
2405
2406 // Parse the argument.
2407 LocTy ArgLoc;
2408 Type *ArgTy = nullptr;
2409 AttrBuilder ArgAttrs;
2410 Value *V;
2411 if (ParseType(ArgTy, ArgLoc))
2412 return true;
2413
2414 if (ArgTy->isMetadataTy()) {
2415 if (ParseMetadataAsValue(V, PFS))
2416 return true;
2417 } else {
2418 // Otherwise, handle normal operands.
2419 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2420 return true;
2421 }
2422 ArgList.push_back(ParamInfo(
2423 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2424 }
2425
2426 if (IsMustTailCall && InVarArgsFunc)
2427 return TokError("expected '...' at end of argument list for musttail call "
2428 "in varargs function");
2429
2430 Lex.Lex(); // Lex the ')'.
2431 return false;
2432}
2433
2434/// ParseOptionalOperandBundles
2435/// ::= /*empty*/
2436/// ::= '[' OperandBundle [, OperandBundle ]* ']'
2437///
2438/// OperandBundle
2439/// ::= bundle-tag '(' ')'
2440/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2441///
2442/// bundle-tag ::= String Constant
2443bool LLParser::ParseOptionalOperandBundles(
2444 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2445 LocTy BeginLoc = Lex.getLoc();
2446 if (!EatIfPresent(lltok::lsquare))
2447 return false;
2448
2449 while (Lex.getKind() != lltok::rsquare) {
2450 // If this isn't the first operand bundle, we need a comma.
2451 if (!BundleList.empty() &&
2452 ParseToken(lltok::comma, "expected ',' in input list"))
2453 return true;
2454
2455 std::string Tag;
2456 if (ParseStringConstant(Tag))
2457 return true;
2458
2459 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2460 return true;
2461
2462 std::vector<Value *> Inputs;
2463 while (Lex.getKind() != lltok::rparen) {
2464 // If this isn't the first input, we need a comma.
2465 if (!Inputs.empty() &&
2466 ParseToken(lltok::comma, "expected ',' in input list"))
2467 return true;
2468
2469 Type *Ty = nullptr;
2470 Value *Input = nullptr;
2471 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2472 return true;
2473 Inputs.push_back(Input);
2474 }
2475
2476 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2477
2478 Lex.Lex(); // Lex the ')'.
2479 }
2480
2481 if (BundleList.empty())
2482 return Error(BeginLoc, "operand bundle set must not be empty");
2483
2484 Lex.Lex(); // Lex the ']'.
2485 return false;
2486}
2487
2488/// ParseArgumentList - Parse the argument list for a function type or function
2489/// prototype.
2490/// ::= '(' ArgTypeListI ')'
2491/// ArgTypeListI
2492/// ::= /*empty*/
2493/// ::= '...'
2494/// ::= ArgTypeList ',' '...'
2495/// ::= ArgType (',' ArgType)*
2496///
2497bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2498 bool &isVarArg){
2499 isVarArg = false;
2500 assert(Lex.getKind() == lltok::lparen)((Lex.getKind() == lltok::lparen) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::lparen", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 2500, __PRETTY_FUNCTION__))
;
2501 Lex.Lex(); // eat the (.
2502
2503 if (Lex.getKind() == lltok::rparen) {
2504 // empty
2505 } else if (Lex.getKind() == lltok::dotdotdot) {
2506 isVarArg = true;
2507 Lex.Lex();
2508 } else {
2509 LocTy TypeLoc = Lex.getLoc();
2510 Type *ArgTy = nullptr;
2511 AttrBuilder Attrs;
2512 std::string Name;
2513
2514 if (ParseType(ArgTy) ||
2515 ParseOptionalParamAttrs(Attrs)) return true;
2516
2517 if (ArgTy->isVoidTy())
2518 return Error(TypeLoc, "argument can not have void type");
2519
2520 if (Lex.getKind() == lltok::LocalVar) {
2521 Name = Lex.getStrVal();
2522 Lex.Lex();
2523 }
2524
2525 if (!FunctionType::isValidArgumentType(ArgTy))
2526 return Error(TypeLoc, "invalid type for function argument");
2527
2528 ArgList.emplace_back(TypeLoc, ArgTy,
2529 AttributeSet::get(ArgTy->getContext(), Attrs),
2530 std::move(Name));
2531
2532 while (EatIfPresent(lltok::comma)) {
2533 // Handle ... at end of arg list.
2534 if (EatIfPresent(lltok::dotdotdot)) {
2535 isVarArg = true;
2536 break;
2537 }
2538
2539 // Otherwise must be an argument type.
2540 TypeLoc = Lex.getLoc();
2541 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2542
2543 if (ArgTy->isVoidTy())
2544 return Error(TypeLoc, "argument can not have void type");
2545
2546 if (Lex.getKind() == lltok::LocalVar) {
2547 Name = Lex.getStrVal();
2548 Lex.Lex();
2549 } else {
2550 Name = "";
2551 }
2552
2553 if (!ArgTy->isFirstClassType())
2554 return Error(TypeLoc, "invalid type for function argument");
2555
2556 ArgList.emplace_back(TypeLoc, ArgTy,
2557 AttributeSet::get(ArgTy->getContext(), Attrs),
2558 std::move(Name));
2559 }
2560 }
2561
2562 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2563}
2564
2565/// ParseFunctionType
2566/// ::= Type ArgumentList OptionalAttrs
2567bool LLParser::ParseFunctionType(Type *&Result) {
2568 assert(Lex.getKind() == lltok::lparen)((Lex.getKind() == lltok::lparen) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::lparen", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 2568, __PRETTY_FUNCTION__))
;
2569
2570 if (!FunctionType::isValidReturnType(Result))
2571 return TokError("invalid function return type");
2572
2573 SmallVector<ArgInfo, 8> ArgList;
2574 bool isVarArg;
2575 if (ParseArgumentList(ArgList, isVarArg))
2576 return true;
2577
2578 // Reject names on the arguments lists.
2579 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2580 if (!ArgList[i].Name.empty())
2581 return Error(ArgList[i].Loc, "argument name invalid in function type");
2582 if (ArgList[i].Attrs.hasAttributes())
2583 return Error(ArgList[i].Loc,
2584 "argument attributes invalid in function type");
2585 }
2586
2587 SmallVector<Type*, 16> ArgListTy;
2588 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2589 ArgListTy.push_back(ArgList[i].Ty);
2590
2591 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2592 return false;
2593}
2594
2595/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2596/// other structs.
2597bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2598 SmallVector<Type*, 8> Elts;
2599 if (ParseStructBody(Elts)) return true;
2600
2601 Result = StructType::get(Context, Elts, Packed);
2602 return false;
2603}
2604
2605/// ParseStructDefinition - Parse a struct in a 'type' definition.
2606bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2607 std::pair<Type*, LocTy> &Entry,
2608 Type *&ResultTy) {
2609 // If the type was already defined, diagnose the redefinition.
2610 if (Entry.first && !Entry.second.isValid())
2611 return Error(TypeLoc, "redefinition of type");
2612
2613 // If we have opaque, just return without filling in the definition for the
2614 // struct. This counts as a definition as far as the .ll file goes.
2615 if (EatIfPresent(lltok::kw_opaque)) {
2616 // This type is being defined, so clear the location to indicate this.
2617 Entry.second = SMLoc();
2618
2619 // If this type number has never been uttered, create it.
2620 if (!Entry.first)
2621 Entry.first = StructType::create(Context, Name);
2622 ResultTy = Entry.first;
2623 return false;
2624 }
2625
2626 // If the type starts with '<', then it is either a packed struct or a vector.
2627 bool isPacked = EatIfPresent(lltok::less);
2628
2629 // If we don't have a struct, then we have a random type alias, which we
2630 // accept for compatibility with old files. These types are not allowed to be
2631 // forward referenced and not allowed to be recursive.
2632 if (Lex.getKind() != lltok::lbrace) {
2633 if (Entry.first)
2634 return Error(TypeLoc, "forward references to non-struct type");
2635
2636 ResultTy = nullptr;
2637 if (isPacked)
2638 return ParseArrayVectorType(ResultTy, true);
2639 return ParseType(ResultTy);
2640 }
2641
2642 // This type is being defined, so clear the location to indicate this.
2643 Entry.second = SMLoc();
2644
2645 // If this type number has never been uttered, create it.
2646 if (!Entry.first)
2647 Entry.first = StructType::create(Context, Name);
2648
2649 StructType *STy = cast<StructType>(Entry.first);
2650
2651 SmallVector<Type*, 8> Body;
2652 if (ParseStructBody(Body) ||
2653 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2654 return true;
2655
2656 STy->setBody(Body, isPacked);
2657 ResultTy = STy;
2658 return false;
2659}
2660
2661/// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2662/// StructType
2663/// ::= '{' '}'
2664/// ::= '{' Type (',' Type)* '}'
2665/// ::= '<' '{' '}' '>'
2666/// ::= '<' '{' Type (',' Type)* '}' '>'
2667bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2668 assert(Lex.getKind() == lltok::lbrace)((Lex.getKind() == lltok::lbrace) ? static_cast<void> (
0) : __assert_fail ("Lex.getKind() == lltok::lbrace", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 2668, __PRETTY_FUNCTION__))
;
2669 Lex.Lex(); // Consume the '{'
2670
2671 // Handle the empty struct.
2672 if (EatIfPresent(lltok::rbrace))
2673 return false;
2674
2675 LocTy EltTyLoc = Lex.getLoc();
2676 Type *Ty = nullptr;
2677 if (ParseType(Ty)) return true;
2678 Body.push_back(Ty);
2679
2680 if (!StructType::isValidElementType(Ty))
2681 return Error(EltTyLoc, "invalid element type for struct");
2682
2683 while (EatIfPresent(lltok::comma)) {
2684 EltTyLoc = Lex.getLoc();
2685 if (ParseType(Ty)) return true;
2686
2687 if (!StructType::isValidElementType(Ty))
2688 return Error(EltTyLoc, "invalid element type for struct");
2689
2690 Body.push_back(Ty);
2691 }
2692
2693 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2694}
2695
2696/// ParseArrayVectorType - Parse an array or vector type, assuming the first
2697/// token has already been consumed.
2698/// Type
2699/// ::= '[' APSINTVAL 'x' Types ']'
2700/// ::= '<' APSINTVAL 'x' Types '>'
2701bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2702 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2703 Lex.getAPSIntVal().getBitWidth() > 64)
2704 return TokError("expected number in address space");
2705
2706 LocTy SizeLoc = Lex.getLoc();
2707 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2708 Lex.Lex();
2709
2710 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2711 return true;
2712
2713 LocTy TypeLoc = Lex.getLoc();
2714 Type *EltTy = nullptr;
2715 if (ParseType(EltTy)) return true;
2716
2717 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2718 "expected end of sequential type"))
2719 return true;
2720
2721 if (isVector) {
2722 if (Size == 0)
2723 return Error(SizeLoc, "zero element vector is illegal");
2724 if ((unsigned)Size != Size)
2725 return Error(SizeLoc, "size too large for vector");
2726 if (!VectorType::isValidElementType(EltTy))
2727 return Error(TypeLoc, "invalid vector element type");
2728 Result = VectorType::get(EltTy, unsigned(Size));
2729 } else {
2730 if (!ArrayType::isValidElementType(EltTy))
2731 return Error(TypeLoc, "invalid array element type");
2732 Result = ArrayType::get(EltTy, Size);
2733 }
2734 return false;
2735}
2736
2737//===----------------------------------------------------------------------===//
2738// Function Semantic Analysis.
2739//===----------------------------------------------------------------------===//
2740
2741LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2742 int functionNumber)
2743 : P(p), F(f), FunctionNumber(functionNumber) {
2744
2745 // Insert unnamed arguments into the NumberedVals list.
2746 for (Argument &A : F.args())
2747 if (!A.hasName())
2748 NumberedVals.push_back(&A);
2749}
2750
2751LLParser::PerFunctionState::~PerFunctionState() {
2752 // If there were any forward referenced non-basicblock values, delete them.
2753
2754 for (const auto &P : ForwardRefVals) {
2755 if (isa<BasicBlock>(P.second.first))
2756 continue;
2757 P.second.first->replaceAllUsesWith(
2758 UndefValue::get(P.second.first->getType()));
2759 P.second.first->deleteValue();
2760 }
2761
2762 for (const auto &P : ForwardRefValIDs) {
2763 if (isa<BasicBlock>(P.second.first))
2764 continue;
2765 P.second.first->replaceAllUsesWith(
2766 UndefValue::get(P.second.first->getType()));
2767 P.second.first->deleteValue();
2768 }
2769}
2770
2771bool LLParser::PerFunctionState::FinishFunction() {
2772 if (!ForwardRefVals.empty())
2773 return P.Error(ForwardRefVals.begin()->second.second,
2774 "use of undefined value '%" + ForwardRefVals.begin()->first +
2775 "'");
2776 if (!ForwardRefValIDs.empty())
2777 return P.Error(ForwardRefValIDs.begin()->second.second,
2778 "use of undefined value '%" +
2779 Twine(ForwardRefValIDs.begin()->first) + "'");
2780 return false;
2781}
2782
2783/// GetVal - Get a value with the specified name or ID, creating a
2784/// forward reference record if needed. This can return null if the value
2785/// exists but does not have the right type.
2786Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2787 LocTy Loc, bool IsCall) {
2788 // Look this name up in the normal function symbol table.
2789 Value *Val = F.getValueSymbolTable()->lookup(Name);
2790
2791 // If this is a forward reference for the value, see if we already created a
2792 // forward ref record.
2793 if (!Val) {
2794 auto I = ForwardRefVals.find(Name);
2795 if (I != ForwardRefVals.end())
2796 Val = I->second.first;
2797 }
2798
2799 // If we have the value in the symbol table or fwd-ref table, return it.
2800 if (Val)
2801 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2802
2803 // Don't make placeholders with invalid type.
2804 if (!Ty->isFirstClassType()) {
2805 P.Error(Loc, "invalid use of a non-first-class type");
2806 return nullptr;
2807 }
2808
2809 // Otherwise, create a new forward reference for this value and remember it.
2810 Value *FwdVal;
2811 if (Ty->isLabelTy()) {
2812 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2813 } else {
2814 FwdVal = new Argument(Ty, Name);
2815 }
2816
2817 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2818 return FwdVal;
2819}
2820
2821Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2822 bool IsCall) {
2823 // Look this name up in the normal function symbol table.
2824 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2825
2826 // If this is a forward reference for the value, see if we already created a
2827 // forward ref record.
2828 if (!Val) {
2829 auto I = ForwardRefValIDs.find(ID);
2830 if (I != ForwardRefValIDs.end())
2831 Val = I->second.first;
2832 }
2833
2834 // If we have the value in the symbol table or fwd-ref table, return it.
2835 if (Val)
2836 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2837
2838 if (!Ty->isFirstClassType()) {
2839 P.Error(Loc, "invalid use of a non-first-class type");
2840 return nullptr;
2841 }
2842
2843 // Otherwise, create a new forward reference for this value and remember it.
2844 Value *FwdVal;
2845 if (Ty->isLabelTy()) {
2846 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2847 } else {
2848 FwdVal = new Argument(Ty);
2849 }
2850
2851 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2852 return FwdVal;
2853}
2854
2855/// SetInstName - After an instruction is parsed and inserted into its
2856/// basic block, this installs its name.
2857bool LLParser::PerFunctionState::SetInstName(int NameID,
2858 const std::string &NameStr,
2859 LocTy NameLoc, Instruction *Inst) {
2860 // If this instruction has void type, it cannot have a name or ID specified.
2861 if (Inst->getType()->isVoidTy()) {
2862 if (NameID != -1 || !NameStr.empty())
2863 return P.Error(NameLoc, "instructions returning void cannot have a name");
2864 return false;
2865 }
2866
2867 // If this was a numbered instruction, verify that the instruction is the
2868 // expected value and resolve any forward references.
2869 if (NameStr.empty()) {
2870 // If neither a name nor an ID was specified, just use the next ID.
2871 if (NameID == -1)
2872 NameID = NumberedVals.size();
2873
2874 if (unsigned(NameID) != NumberedVals.size())
2875 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2876 Twine(NumberedVals.size()) + "'");
2877
2878 auto FI = ForwardRefValIDs.find(NameID);
2879 if (FI != ForwardRefValIDs.end()) {
2880 Value *Sentinel = FI->second.first;
2881 if (Sentinel->getType() != Inst->getType())
2882 return P.Error(NameLoc, "instruction forward referenced with type '" +
2883 getTypeString(FI->second.first->getType()) + "'");
2884
2885 Sentinel->replaceAllUsesWith(Inst);
2886 Sentinel->deleteValue();
2887 ForwardRefValIDs.erase(FI);
2888 }
2889
2890 NumberedVals.push_back(Inst);
2891 return false;
2892 }
2893
2894 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2895 auto FI = ForwardRefVals.find(NameStr);
2896 if (FI != ForwardRefVals.end()) {
2897 Value *Sentinel = FI->second.first;
2898 if (Sentinel->getType() != Inst->getType())
2899 return P.Error(NameLoc, "instruction forward referenced with type '" +
2900 getTypeString(FI->second.first->getType()) + "'");
2901
2902 Sentinel->replaceAllUsesWith(Inst);
2903 Sentinel->deleteValue();
2904 ForwardRefVals.erase(FI);
2905 }
2906
2907 // Set the name on the instruction.
2908 Inst->setName(NameStr);
2909
2910 if (Inst->getName() != NameStr)
2911 return P.Error(NameLoc, "multiple definition of local value named '" +
2912 NameStr + "'");
2913 return false;
2914}
2915
2916/// GetBB - Get a basic block with the specified name or ID, creating a
2917/// forward reference record if needed.
2918BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2919 LocTy Loc) {
2920 return dyn_cast_or_null<BasicBlock>(
2921 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2922}
2923
2924BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2925 return dyn_cast_or_null<BasicBlock>(
2926 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2927}
2928
2929/// DefineBB - Define the specified basic block, which is either named or
2930/// unnamed. If there is an error, this returns null otherwise it returns
2931/// the block being defined.
2932BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2933 int NameID, LocTy Loc) {
2934 BasicBlock *BB;
2935 if (Name.empty()) {
2936 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
2937 P.Error(Loc, "label expected to be numbered '" +
2938 Twine(NumberedVals.size()) + "'");
2939 return nullptr;
2940 }
2941 BB = GetBB(NumberedVals.size(), Loc);
2942 if (!BB) {
2943 P.Error(Loc, "unable to create block numbered '" +
2944 Twine(NumberedVals.size()) + "'");
2945 return nullptr;
2946 }
2947 } else {
2948 BB = GetBB(Name, Loc);
2949 if (!BB) {
2950 P.Error(Loc, "unable to create block named '" + Name + "'");
2951 return nullptr;
2952 }
2953 }
2954
2955 // Move the block to the end of the function. Forward ref'd blocks are
2956 // inserted wherever they happen to be referenced.
2957 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2958
2959 // Remove the block from forward ref sets.
2960 if (Name.empty()) {
2961 ForwardRefValIDs.erase(NumberedVals.size());
2962 NumberedVals.push_back(BB);
2963 } else {
2964 // BB forward references are already in the function symbol table.
2965 ForwardRefVals.erase(Name);
2966 }
2967
2968 return BB;
2969}
2970
2971//===----------------------------------------------------------------------===//
2972// Constants.
2973//===----------------------------------------------------------------------===//
2974
2975/// ParseValID - Parse an abstract value that doesn't necessarily have a
2976/// type implied. For example, if we parse "4" we don't know what integer type
2977/// it has. The value will later be combined with its type and checked for
2978/// sanity. PFS is used to convert function-local operands of metadata (since
2979/// metadata operands are not just parsed here but also converted to values).
2980/// PFS can be null when we are not parsing metadata values inside a function.
2981bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2982 ID.Loc = Lex.getLoc();
2983 switch (Lex.getKind()) {
2984 default: return TokError("expected value token");
2985 case lltok::GlobalID: // @42
2986 ID.UIntVal = Lex.getUIntVal();
2987 ID.Kind = ValID::t_GlobalID;
2988 break;
2989 case lltok::GlobalVar: // @foo
2990 ID.StrVal = Lex.getStrVal();
2991 ID.Kind = ValID::t_GlobalName;
2992 break;
2993 case lltok::LocalVarID: // %42
2994 ID.UIntVal = Lex.getUIntVal();
2995 ID.Kind = ValID::t_LocalID;
2996 break;
2997 case lltok::LocalVar: // %foo
2998 ID.StrVal = Lex.getStrVal();
2999 ID.Kind = ValID::t_LocalName;
3000 break;
3001 case lltok::APSInt:
3002 ID.APSIntVal = Lex.getAPSIntVal();
3003 ID.Kind = ValID::t_APSInt;
3004 break;
3005 case lltok::APFloat:
3006 ID.APFloatVal = Lex.getAPFloatVal();
3007 ID.Kind = ValID::t_APFloat;
3008 break;
3009 case lltok::kw_true:
3010 ID.ConstantVal = ConstantInt::getTrue(Context);
3011 ID.Kind = ValID::t_Constant;
3012 break;
3013 case lltok::kw_false:
3014 ID.ConstantVal = ConstantInt::getFalse(Context);
3015 ID.Kind = ValID::t_Constant;
3016 break;
3017 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3018 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3019 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3020 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3021
3022 case lltok::lbrace: {
3023 // ValID ::= '{' ConstVector '}'
3024 Lex.Lex();
3025 SmallVector<Constant*, 16> Elts;
3026 if (ParseGlobalValueVector(Elts) ||
3027 ParseToken(lltok::rbrace, "expected end of struct constant"))
3028 return true;
3029
3030 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3031 ID.UIntVal = Elts.size();
3032 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3033 Elts.size() * sizeof(Elts[0]));
3034 ID.Kind = ValID::t_ConstantStruct;
3035 return false;
3036 }
3037 case lltok::less: {
3038 // ValID ::= '<' ConstVector '>' --> Vector.
3039 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3040 Lex.Lex();
3041 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3042
3043 SmallVector<Constant*, 16> Elts;
3044 LocTy FirstEltLoc = Lex.getLoc();
3045 if (ParseGlobalValueVector(Elts) ||
3046 (isPackedStruct &&
3047 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3048 ParseToken(lltok::greater, "expected end of constant"))
3049 return true;
3050
3051 if (isPackedStruct) {
3052 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3053 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3054 Elts.size() * sizeof(Elts[0]));
3055 ID.UIntVal = Elts.size();
3056 ID.Kind = ValID::t_PackedConstantStruct;
3057 return false;
3058 }
3059
3060 if (Elts.empty())
3061 return Error(ID.Loc, "constant vector must not be empty");
3062
3063 if (!Elts[0]->getType()->isIntegerTy() &&
3064 !Elts[0]->getType()->isFloatingPointTy() &&
3065 !Elts[0]->getType()->isPointerTy())
3066 return Error(FirstEltLoc,
3067 "vector elements must have integer, pointer or floating point type");
3068
3069 // Verify that all the vector elements have the same type.
3070 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3071 if (Elts[i]->getType() != Elts[0]->getType())
3072 return Error(FirstEltLoc,
3073 "vector element #" + Twine(i) +
3074 " is not of type '" + getTypeString(Elts[0]->getType()));
3075
3076 ID.ConstantVal = ConstantVector::get(Elts);
3077 ID.Kind = ValID::t_Constant;
3078 return false;
3079 }
3080 case lltok::lsquare: { // Array Constant
3081 Lex.Lex();
3082 SmallVector<Constant*, 16> Elts;
3083 LocTy FirstEltLoc = Lex.getLoc();
3084 if (ParseGlobalValueVector(Elts) ||
3085 ParseToken(lltok::rsquare, "expected end of array constant"))
3086 return true;
3087
3088 // Handle empty element.
3089 if (Elts.empty()) {
3090 // Use undef instead of an array because it's inconvenient to determine
3091 // the element type at this point, there being no elements to examine.
3092 ID.Kind = ValID::t_EmptyArray;
3093 return false;
3094 }
3095
3096 if (!Elts[0]->getType()->isFirstClassType())
3097 return Error(FirstEltLoc, "invalid array element type: " +
3098 getTypeString(Elts[0]->getType()));
3099
3100 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3101
3102 // Verify all elements are correct type!
3103 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3104 if (Elts[i]->getType() != Elts[0]->getType())
3105 return Error(FirstEltLoc,
3106 "array element #" + Twine(i) +
3107 " is not of type '" + getTypeString(Elts[0]->getType()));
3108 }
3109
3110 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3111 ID.Kind = ValID::t_Constant;
3112 return false;
3113 }
3114 case lltok::kw_c: // c "foo"
3115 Lex.Lex();
3116 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3117 false);
3118 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3119 ID.Kind = ValID::t_Constant;
3120 return false;
3121
3122 case lltok::kw_asm: {
3123 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3124 // STRINGCONSTANT
3125 bool HasSideEffect, AlignStack, AsmDialect;
3126 Lex.Lex();
3127 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3128 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3129 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3130 ParseStringConstant(ID.StrVal) ||
3131 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3132 ParseToken(lltok::StringConstant, "expected constraint string"))
3133 return true;
3134 ID.StrVal2 = Lex.getStrVal();
3135 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3136 (unsigned(AsmDialect)<<2);
3137 ID.Kind = ValID::t_InlineAsm;
3138 return false;
3139 }
3140
3141 case lltok::kw_blockaddress: {
3142 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3143 Lex.Lex();
3144
3145 ValID Fn, Label;
3146
3147 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3148 ParseValID(Fn) ||
3149 ParseToken(lltok::comma, "expected comma in block address expression")||
3150 ParseValID(Label) ||
3151 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3152 return true;
3153
3154 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3155 return Error(Fn.Loc, "expected function name in blockaddress");
3156 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3157 return Error(Label.Loc, "expected basic block name in blockaddress");
3158
3159 // Try to find the function (but skip it if it's forward-referenced).
3160 GlobalValue *GV = nullptr;
3161 if (Fn.Kind == ValID::t_GlobalID) {
3162 if (Fn.UIntVal < NumberedVals.size())
3163 GV = NumberedVals[Fn.UIntVal];
3164 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3165 GV = M->getNamedValue(Fn.StrVal);
3166 }
3167 Function *F = nullptr;
3168 if (GV) {
3169 // Confirm that it's actually a function with a definition.
3170 if (!isa<Function>(GV))
3171 return Error(Fn.Loc, "expected function name in blockaddress");
3172 F = cast<Function>(GV);
3173 if (F->isDeclaration())
3174 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3175 }
3176
3177 if (!F) {
3178 // Make a global variable as a placeholder for this reference.
3179 GlobalValue *&FwdRef =
3180 ForwardRefBlockAddresses.insert(std::make_pair(
3181 std::move(Fn),
3182 std::map<ValID, GlobalValue *>()))
3183 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3184 .first->second;
3185 if (!FwdRef)
3186 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3187 GlobalValue::InternalLinkage, nullptr, "");
3188 ID.ConstantVal = FwdRef;
3189 ID.Kind = ValID::t_Constant;
3190 return false;
3191 }
3192
3193 // We found the function; now find the basic block. Don't use PFS, since we
3194 // might be inside a constant expression.
3195 BasicBlock *BB;
3196 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3197 if (Label.Kind == ValID::t_LocalID)
3198 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3199 else
3200 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3201 if (!BB)
3202 return Error(Label.Loc, "referenced value is not a basic block");
3203 } else {
3204 if (Label.Kind == ValID::t_LocalID)
3205 return Error(Label.Loc, "cannot take address of numeric label after "
3206 "the function is defined");
3207 BB = dyn_cast_or_null<BasicBlock>(
3208 F->getValueSymbolTable()->lookup(Label.StrVal));
3209 if (!BB)
3210 return Error(Label.Loc, "referenced value is not a basic block");
3211 }
3212
3213 ID.ConstantVal = BlockAddress::get(F, BB);
3214 ID.Kind = ValID::t_Constant;
3215 return false;
3216 }
3217
3218 case lltok::kw_trunc:
3219 case lltok::kw_zext:
3220 case lltok::kw_sext:
3221 case lltok::kw_fptrunc:
3222 case lltok::kw_fpext:
3223 case lltok::kw_bitcast:
3224 case lltok::kw_addrspacecast:
3225 case lltok::kw_uitofp:
3226 case lltok::kw_sitofp:
3227 case lltok::kw_fptoui:
3228 case lltok::kw_fptosi:
3229 case lltok::kw_inttoptr:
3230 case lltok::kw_ptrtoint: {
3231 unsigned Opc = Lex.getUIntVal();
3232 Type *DestTy = nullptr;
3233 Constant *SrcVal;
3234 Lex.Lex();
3235 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3236 ParseGlobalTypeAndValue(SrcVal) ||
3237 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3238 ParseType(DestTy) ||
3239 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3240 return true;
3241 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3242 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3243 getTypeString(SrcVal->getType()) + "' to '" +
3244 getTypeString(DestTy) + "'");
3245 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3246 SrcVal, DestTy);
3247 ID.Kind = ValID::t_Constant;
3248 return false;
3249 }
3250 case lltok::kw_extractvalue: {
3251 Lex.Lex();
3252 Constant *Val;
3253 SmallVector<unsigned, 4> Indices;
3254 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3255 ParseGlobalTypeAndValue(Val) ||
3256 ParseIndexList(Indices) ||
3257 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3258 return true;
3259
3260 if (!Val->getType()->isAggregateType())
3261 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3262 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3263 return Error(ID.Loc, "invalid indices for extractvalue");
3264 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3265 ID.Kind = ValID::t_Constant;
3266 return false;
3267 }
3268 case lltok::kw_insertvalue: {
3269 Lex.Lex();
3270 Constant *Val0, *Val1;
3271 SmallVector<unsigned, 4> Indices;
3272 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3273 ParseGlobalTypeAndValue(Val0) ||
3274 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3275 ParseGlobalTypeAndValue(Val1) ||
3276 ParseIndexList(Indices) ||
3277 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3278 return true;
3279 if (!Val0->getType()->isAggregateType())
3280 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3281 Type *IndexedType =
3282 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3283 if (!IndexedType)
3284 return Error(ID.Loc, "invalid indices for insertvalue");
3285 if (IndexedType != Val1->getType())
3286 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3287 getTypeString(Val1->getType()) +
3288 "' instead of '" + getTypeString(IndexedType) +
3289 "'");
3290 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3291 ID.Kind = ValID::t_Constant;
3292 return false;
3293 }
3294 case lltok::kw_icmp:
3295 case lltok::kw_fcmp: {
3296 unsigned PredVal, Opc = Lex.getUIntVal();
3297 Constant *Val0, *Val1;
3298 Lex.Lex();
3299 if (ParseCmpPredicate(PredVal, Opc) ||
3300 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3301 ParseGlobalTypeAndValue(Val0) ||
3302 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3303 ParseGlobalTypeAndValue(Val1) ||
3304 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3305 return true;
3306
3307 if (Val0->getType() != Val1->getType())
3308 return Error(ID.Loc, "compare operands must have the same type");
3309
3310 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3311
3312 if (Opc == Instruction::FCmp) {
3313 if (!Val0->getType()->isFPOrFPVectorTy())
3314 return Error(ID.Loc, "fcmp requires floating point operands");
3315 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3316 } else {
3317 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!")((Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"
) ? static_cast<void> (0) : __assert_fail ("Opc == Instruction::ICmp && \"Unexpected opcode for CmpInst!\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3317, __PRETTY_FUNCTION__))
;
3318 if (!Val0->getType()->isIntOrIntVectorTy() &&
3319 !Val0->getType()->isPtrOrPtrVectorTy())
3320 return Error(ID.Loc, "icmp requires pointer or integer operands");
3321 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3322 }
3323 ID.Kind = ValID::t_Constant;
3324 return false;
3325 }
3326
3327 // Unary Operators.
3328 case lltok::kw_fneg: {
3329 unsigned Opc = Lex.getUIntVal();
3330 Constant *Val;
3331 Lex.Lex();
3332 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3333 ParseGlobalTypeAndValue(Val) ||
3334 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3335 return true;
3336
3337 // Check that the type is valid for the operator.
3338 switch (Opc) {
3339 case Instruction::FNeg:
3340 if (!Val->getType()->isFPOrFPVectorTy())
3341 return Error(ID.Loc, "constexpr requires fp operands");
3342 break;
3343 default: llvm_unreachable("Unknown unary operator!")::llvm::llvm_unreachable_internal("Unknown unary operator!", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3343)
;
3344 }
3345 unsigned Flags = 0;
3346 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3347 ID.ConstantVal = C;
3348 ID.Kind = ValID::t_Constant;
3349 return false;
3350 }
3351 // Binary Operators.
3352 case lltok::kw_add:
3353 case lltok::kw_fadd:
3354 case lltok::kw_sub:
3355 case lltok::kw_fsub:
3356 case lltok::kw_mul:
3357 case lltok::kw_fmul:
3358 case lltok::kw_udiv:
3359 case lltok::kw_sdiv:
3360 case lltok::kw_fdiv:
3361 case lltok::kw_urem:
3362 case lltok::kw_srem:
3363 case lltok::kw_frem:
3364 case lltok::kw_shl:
3365 case lltok::kw_lshr:
3366 case lltok::kw_ashr: {
3367 bool NUW = false;
3368 bool NSW = false;
3369 bool Exact = false;
3370 unsigned Opc = Lex.getUIntVal();
3371 Constant *Val0, *Val1;
3372 Lex.Lex();
3373 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3374 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3375 if (EatIfPresent(lltok::kw_nuw))
3376 NUW = true;
3377 if (EatIfPresent(lltok::kw_nsw)) {
3378 NSW = true;
3379 if (EatIfPresent(lltok::kw_nuw))
3380 NUW = true;
3381 }
3382 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3383 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3384 if (EatIfPresent(lltok::kw_exact))
3385 Exact = true;
3386 }
3387 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3388 ParseGlobalTypeAndValue(Val0) ||
3389 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3390 ParseGlobalTypeAndValue(Val1) ||
3391 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3392 return true;
3393 if (Val0->getType() != Val1->getType())
3394 return Error(ID.Loc, "operands of constexpr must have same type");
3395 // Check that the type is valid for the operator.
3396 switch (Opc) {
3397 case Instruction::Add:
3398 case Instruction::Sub:
3399 case Instruction::Mul:
3400 case Instruction::UDiv:
3401 case Instruction::SDiv:
3402 case Instruction::URem:
3403 case Instruction::SRem:
3404 case Instruction::Shl:
3405 case Instruction::AShr:
3406 case Instruction::LShr:
3407 if (!Val0->getType()->isIntOrIntVectorTy())
3408 return Error(ID.Loc, "constexpr requires integer operands");
3409 break;
3410 case Instruction::FAdd:
3411 case Instruction::FSub:
3412 case Instruction::FMul:
3413 case Instruction::FDiv:
3414 case Instruction::FRem:
3415 if (!Val0->getType()->isFPOrFPVectorTy())
3416 return Error(ID.Loc, "constexpr requires fp operands");
3417 break;
3418 default: llvm_unreachable("Unknown binary operator!")::llvm::llvm_unreachable_internal("Unknown binary operator!",
"/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3418)
;
3419 }
3420 unsigned Flags = 0;
3421 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3422 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3423 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3424 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3425 ID.ConstantVal = C;
3426 ID.Kind = ValID::t_Constant;
3427 return false;
3428 }
3429
3430 // Logical Operations
3431 case lltok::kw_and:
3432 case lltok::kw_or:
3433 case lltok::kw_xor: {
3434 unsigned Opc = Lex.getUIntVal();
3435 Constant *Val0, *Val1;
3436 Lex.Lex();
3437 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3438 ParseGlobalTypeAndValue(Val0) ||
3439 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3440 ParseGlobalTypeAndValue(Val1) ||
3441 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3442 return true;
3443 if (Val0->getType() != Val1->getType())
3444 return Error(ID.Loc, "operands of constexpr must have same type");
3445 if (!Val0->getType()->isIntOrIntVectorTy())
3446 return Error(ID.Loc,
3447 "constexpr requires integer or integer vector operands");
3448 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3449 ID.Kind = ValID::t_Constant;
3450 return false;
3451 }
3452
3453 case lltok::kw_getelementptr:
3454 case lltok::kw_shufflevector:
3455 case lltok::kw_insertelement:
3456 case lltok::kw_extractelement:
3457 case lltok::kw_select: {
3458 unsigned Opc = Lex.getUIntVal();
3459 SmallVector<Constant*, 16> Elts;
3460 bool InBounds = false;
3461 Type *Ty;
3462 Lex.Lex();
3463
3464 if (Opc == Instruction::GetElementPtr)
3465 InBounds = EatIfPresent(lltok::kw_inbounds);
3466
3467 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3468 return true;
3469
3470 LocTy ExplicitTypeLoc = Lex.getLoc();
3471 if (Opc == Instruction::GetElementPtr) {
3472 if (ParseType(Ty) ||
3473 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3474 return true;
3475 }
3476
3477 Optional<unsigned> InRangeOp;
3478 if (ParseGlobalValueVector(
3479 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3480 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3481 return true;
3482
3483 if (Opc == Instruction::GetElementPtr) {
3484 if (Elts.size() == 0 ||
3485 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3486 return Error(ID.Loc, "base of getelementptr must be a pointer");
3487
3488 Type *BaseType = Elts[0]->getType();
3489 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3490 if (Ty != BasePointerType->getElementType())
3491 return Error(
3492 ExplicitTypeLoc,
3493 "explicit pointee type doesn't match operand's pointee type");
3494
3495 unsigned GEPWidth =
3496 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3497
3498 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3499 for (Constant *Val : Indices) {
3500 Type *ValTy = Val->getType();
3501 if (!ValTy->isIntOrIntVectorTy())
3502 return Error(ID.Loc, "getelementptr index must be an integer");
3503 if (ValTy->isVectorTy()) {
3504 unsigned ValNumEl = ValTy->getVectorNumElements();
3505 if (GEPWidth && (ValNumEl != GEPWidth))
3506 return Error(
3507 ID.Loc,
3508 "getelementptr vector index has a wrong number of elements");
3509 // GEPWidth may have been unknown because the base is a scalar,
3510 // but it is known now.
3511 GEPWidth = ValNumEl;
3512 }
3513 }
3514
3515 SmallPtrSet<Type*, 4> Visited;
3516 if (!Indices.empty() && !Ty->isSized(&Visited))
3517 return Error(ID.Loc, "base element of getelementptr must be sized");
3518
3519 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3520 return Error(ID.Loc, "invalid getelementptr indices");
3521
3522 if (InRangeOp) {
3523 if (*InRangeOp == 0)
3524 return Error(ID.Loc,
3525 "inrange keyword may not appear on pointer operand");
3526 --*InRangeOp;
3527 }
3528
3529 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3530 InBounds, InRangeOp);
3531 } else if (Opc == Instruction::Select) {
3532 if (Elts.size() != 3)
3533 return Error(ID.Loc, "expected three operands to select");
3534 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3535 Elts[2]))
3536 return Error(ID.Loc, Reason);
3537 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3538 } else if (Opc == Instruction::ShuffleVector) {
3539 if (Elts.size() != 3)
3540 return Error(ID.Loc, "expected three operands to shufflevector");
3541 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3542 return Error(ID.Loc, "invalid operands to shufflevector");
3543 ID.ConstantVal =
3544 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3545 } else if (Opc == Instruction::ExtractElement) {
3546 if (Elts.size() != 2)
3547 return Error(ID.Loc, "expected two operands to extractelement");
3548 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3549 return Error(ID.Loc, "invalid extractelement operands");
3550 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3551 } else {
3552 assert(Opc == Instruction::InsertElement && "Unknown opcode")((Opc == Instruction::InsertElement && "Unknown opcode"
) ? static_cast<void> (0) : __assert_fail ("Opc == Instruction::InsertElement && \"Unknown opcode\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3552, __PRETTY_FUNCTION__))
;
3553 if (Elts.size() != 3)
3554 return Error(ID.Loc, "expected three operands to insertelement");
3555 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3556 return Error(ID.Loc, "invalid insertelement operands");
3557 ID.ConstantVal =
3558 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3559 }
3560
3561 ID.Kind = ValID::t_Constant;
3562 return false;
3563 }
3564 }
3565
3566 Lex.Lex();
3567 return false;
3568}
3569
3570/// ParseGlobalValue - Parse a global value with the specified type.
3571bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3572 C = nullptr;
3573 ValID ID;
3574 Value *V = nullptr;
3575 bool Parsed = ParseValID(ID) ||
3576 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3577 if (V && !(C = dyn_cast<Constant>(V)))
3578 return Error(ID.Loc, "global values must be constants");
3579 return Parsed;
3580}
3581
3582bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3583 Type *Ty = nullptr;
3584 return ParseType(Ty) ||
3585 ParseGlobalValue(Ty, V);
3586}
3587
3588bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3589 C = nullptr;
3590
3591 LocTy KwLoc = Lex.getLoc();
3592 if (!EatIfPresent(lltok::kw_comdat))
3593 return false;
3594
3595 if (EatIfPresent(lltok::lparen)) {
3596 if (Lex.getKind() != lltok::ComdatVar)
3597 return TokError("expected comdat variable");
3598 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3599 Lex.Lex();
3600 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3601 return true;
3602 } else {
3603 if (GlobalName.empty())
3604 return TokError("comdat cannot be unnamed");
3605 C = getComdat(GlobalName, KwLoc);
3606 }
3607
3608 return false;
3609}
3610
3611/// ParseGlobalValueVector
3612/// ::= /*empty*/
3613/// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3614bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3615 Optional<unsigned> *InRangeOp) {
3616 // Empty list.
3617 if (Lex.getKind() == lltok::rbrace ||
3618 Lex.getKind() == lltok::rsquare ||
3619 Lex.getKind() == lltok::greater ||
3620 Lex.getKind() == lltok::rparen)
3621 return false;
3622
3623 do {
3624 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3625 *InRangeOp = Elts.size();
3626
3627 Constant *C;
3628 if (ParseGlobalTypeAndValue(C)) return true;
3629 Elts.push_back(C);
3630 } while (EatIfPresent(lltok::comma));
3631
3632 return false;
3633}
3634
3635bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3636 SmallVector<Metadata *, 16> Elts;
3637 if (ParseMDNodeVector(Elts))
3638 return true;
3639
3640 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3641 return false;
3642}
3643
3644/// MDNode:
3645/// ::= !{ ... }
3646/// ::= !7
3647/// ::= !DILocation(...)
3648bool LLParser::ParseMDNode(MDNode *&N) {
3649 if (Lex.getKind() == lltok::MetadataVar)
3650 return ParseSpecializedMDNode(N);
3651
3652 return ParseToken(lltok::exclaim, "expected '!' here") ||
3653 ParseMDNodeTail(N);
3654}
3655
3656bool LLParser::ParseMDNodeTail(MDNode *&N) {
3657 // !{ ... }
3658 if (Lex.getKind() == lltok::lbrace)
3659 return ParseMDTuple(N);
3660
3661 // !42
3662 return ParseMDNodeID(N);
3663}
3664
3665namespace {
3666
3667/// Structure to represent an optional metadata field.
3668template <class FieldTy> struct MDFieldImpl {
3669 typedef MDFieldImpl ImplTy;
3670 FieldTy Val;
3671 bool Seen;
3672
3673 void assign(FieldTy Val) {
3674 Seen = true;
3675 this->Val = std::move(Val);
3676 }
3677
3678 explicit MDFieldImpl(FieldTy Default)
3679 : Val(std::move(Default)), Seen(false) {}
3680};
3681
3682/// Structure to represent an optional metadata field that
3683/// can be of either type (A or B) and encapsulates the
3684/// MD<typeofA>Field and MD<typeofB>Field structs, so not
3685/// to reimplement the specifics for representing each Field.
3686template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3687 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3688 FieldTypeA A;
3689 FieldTypeB B;
3690 bool Seen;
3691
3692 enum {
3693 IsInvalid = 0,
3694 IsTypeA = 1,
3695 IsTypeB = 2
3696 } WhatIs;
3697
3698 void assign(FieldTypeA A) {
3699 Seen = true;
3700 this->A = std::move(A);
3701 WhatIs = IsTypeA;
3702 }
3703
3704 void assign(FieldTypeB B) {
3705 Seen = true;
3706 this->B = std::move(B);
3707 WhatIs = IsTypeB;
3708 }
3709
3710 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3711 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3712 WhatIs(IsInvalid) {}
3713};
3714
3715struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3716 uint64_t Max;
3717
3718 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX(18446744073709551615UL))
3719 : ImplTy(Default), Max(Max) {}
3720};
3721
3722struct LineField : public MDUnsignedField {
3723 LineField() : MDUnsignedField(0, UINT32_MAX(4294967295U)) {}
3724};
3725
3726struct ColumnField : public MDUnsignedField {
3727 ColumnField() : MDUnsignedField(0, UINT16_MAX(65535)) {}
3728};
3729
3730struct DwarfTagField : public MDUnsignedField {
3731 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3732 DwarfTagField(dwarf::Tag DefaultTag)
3733 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3734};
3735
3736struct DwarfMacinfoTypeField : public MDUnsignedField {
3737 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3738 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3739 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3740};
3741
3742struct DwarfAttEncodingField : public MDUnsignedField {
3743 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3744};
3745
3746struct DwarfVirtualityField : public MDUnsignedField {
3747 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3748};
3749
3750struct DwarfLangField : public MDUnsignedField {
3751 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3752};
3753
3754struct DwarfCCField : public MDUnsignedField {
3755 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3756};
3757
3758struct EmissionKindField : public MDUnsignedField {
3759 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3760};
3761
3762struct NameTableKindField : public MDUnsignedField {
3763 NameTableKindField()
3764 : MDUnsignedField(
3765 0, (unsigned)
3766 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3767};
3768
3769struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3770 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3771};
3772
3773struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3774 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3775};
3776
3777struct MDSignedField : public MDFieldImpl<int64_t> {
3778 int64_t Min;
3779 int64_t Max;
3780
3781 MDSignedField(int64_t Default = 0)
3782 : ImplTy(Default), Min(INT64_MIN(-9223372036854775807L -1)), Max(INT64_MAX(9223372036854775807L)) {}
3783 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3784 : ImplTy(Default), Min(Min), Max(Max) {}
3785};
3786
3787struct MDBoolField : public MDFieldImpl<bool> {
3788 MDBoolField(bool Default = false) : ImplTy(Default) {}
3789};
3790
3791struct MDField : public MDFieldImpl<Metadata *> {
3792 bool AllowNull;
3793
3794 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3795};
3796
3797struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3798 MDConstant() : ImplTy(nullptr) {}
3799};
3800
3801struct MDStringField : public MDFieldImpl<MDString *> {
3802 bool AllowEmpty;
3803 MDStringField(bool AllowEmpty = true)
3804 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3805};
3806
3807struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3808 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3809};
3810
3811struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3812 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3813};
3814
3815struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3816 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3817 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3818
3819 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3820 bool AllowNull = true)
3821 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3822
3823 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3824 bool isMDField() const { return WhatIs == IsTypeB; }
3825 int64_t getMDSignedValue() const {
3826 assert(isMDSignedField() && "Wrong field type")((isMDSignedField() && "Wrong field type") ? static_cast
<void> (0) : __assert_fail ("isMDSignedField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3826, __PRETTY_FUNCTION__))
;
3827 return A.Val;
3828 }
3829 Metadata *getMDFieldValue() const {
3830 assert(isMDField() && "Wrong field type")((isMDField() && "Wrong field type") ? static_cast<
void> (0) : __assert_fail ("isMDField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3830, __PRETTY_FUNCTION__))
;
3831 return B.Val;
3832 }
3833};
3834
3835struct MDSignedOrUnsignedField
3836 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3837 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3838
3839 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3840 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3841 int64_t getMDSignedValue() const {
3842 assert(isMDSignedField() && "Wrong field type")((isMDSignedField() && "Wrong field type") ? static_cast
<void> (0) : __assert_fail ("isMDSignedField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3842, __PRETTY_FUNCTION__))
;
3843 return A.Val;
3844 }
3845 uint64_t getMDUnsignedValue() const {
3846 assert(isMDUnsignedField() && "Wrong field type")((isMDUnsignedField() && "Wrong field type") ? static_cast
<void> (0) : __assert_fail ("isMDUnsignedField() && \"Wrong field type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3846, __PRETTY_FUNCTION__))
;
3847 return B.Val;
3848 }
3849};
3850
3851} // end anonymous namespace
3852
3853namespace llvm {
3854
3855template <>
3856bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3857 MDUnsignedField &Result) {
3858 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3859 return TokError("expected unsigned integer");
3860
3861 auto &U = Lex.getAPSIntVal();
3862 if (U.ugt(Result.Max))
3863 return TokError("value for '" + Name + "' too large, limit is " +
3864 Twine(Result.Max));
3865 Result.assign(U.getZExtValue());
3866 assert(Result.Val <= Result.Max && "Expected value in range")((Result.Val <= Result.Max && "Expected value in range"
) ? static_cast<void> (0) : __assert_fail ("Result.Val <= Result.Max && \"Expected value in range\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3866, __PRETTY_FUNCTION__))
;
3867 Lex.Lex();
3868 return false;
3869}
3870
3871template <>
3872bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3873 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3874}
3875template <>
3876bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3877 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3878}
3879
3880template <>
3881bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3882 if (Lex.getKind() == lltok::APSInt)
3883 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3884
3885 if (Lex.getKind() != lltok::DwarfTag)
3886 return TokError("expected DWARF tag");
3887
3888 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3889 if (Tag == dwarf::DW_TAG_invalid)
3890 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3891 assert(Tag <= Result.Max && "Expected valid DWARF tag")((Tag <= Result.Max && "Expected valid DWARF tag")
? static_cast<void> (0) : __assert_fail ("Tag <= Result.Max && \"Expected valid DWARF tag\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3891, __PRETTY_FUNCTION__))
;
3892
3893 Result.assign(Tag);
3894 Lex.Lex();
3895 return false;
3896}
3897
3898template <>
3899bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3900 DwarfMacinfoTypeField &Result) {
3901 if (Lex.getKind() == lltok::APSInt)
3902 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3903
3904 if (Lex.getKind() != lltok::DwarfMacinfo)
3905 return TokError("expected DWARF macinfo type");
3906
3907 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3908 if (Macinfo == dwarf::DW_MACINFO_invalid)
3909 return TokError(
3910 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3911 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type")((Macinfo <= Result.Max && "Expected valid DWARF macinfo type"
) ? static_cast<void> (0) : __assert_fail ("Macinfo <= Result.Max && \"Expected valid DWARF macinfo type\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3911, __PRETTY_FUNCTION__))
;
3912
3913 Result.assign(Macinfo);
3914 Lex.Lex();
3915 return false;
3916}
3917
3918template <>
3919bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3920 DwarfVirtualityField &Result) {
3921 if (Lex.getKind() == lltok::APSInt)
3922 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3923
3924 if (Lex.getKind() != lltok::DwarfVirtuality)
3925 return TokError("expected DWARF virtuality code");
3926
3927 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3928 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3929 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3930 Lex.getStrVal() + "'");
3931 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code")((Virtuality <= Result.Max && "Expected valid DWARF virtuality code"
) ? static_cast<void> (0) : __assert_fail ("Virtuality <= Result.Max && \"Expected valid DWARF virtuality code\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3931, __PRETTY_FUNCTION__))
;
3932 Result.assign(Virtuality);
3933 Lex.Lex();
3934 return false;
3935}
3936
3937template <>
3938bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3939 if (Lex.getKind() == lltok::APSInt)
3940 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3941
3942 if (Lex.getKind() != lltok::DwarfLang)
3943 return TokError("expected DWARF language");
3944
3945 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3946 if (!Lang)
3947 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3948 "'");
3949 assert(Lang <= Result.Max && "Expected valid DWARF language")((Lang <= Result.Max && "Expected valid DWARF language"
) ? static_cast<void> (0) : __assert_fail ("Lang <= Result.Max && \"Expected valid DWARF language\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3949, __PRETTY_FUNCTION__))
;
3950 Result.assign(Lang);
3951 Lex.Lex();
3952 return false;
3953}
3954
3955template <>
3956bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3957 if (Lex.getKind() == lltok::APSInt)
3958 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3959
3960 if (Lex.getKind() != lltok::DwarfCC)
3961 return TokError("expected DWARF calling convention");
3962
3963 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3964 if (!CC)
3965 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3966 "'");
3967 assert(CC <= Result.Max && "Expected valid DWARF calling convention")((CC <= Result.Max && "Expected valid DWARF calling convention"
) ? static_cast<void> (0) : __assert_fail ("CC <= Result.Max && \"Expected valid DWARF calling convention\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3967, __PRETTY_FUNCTION__))
;
3968 Result.assign(CC);
3969 Lex.Lex();
3970 return false;
3971}
3972
3973template <>
3974bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3975 if (Lex.getKind() == lltok::APSInt)
3976 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3977
3978 if (Lex.getKind() != lltok::EmissionKind)
3979 return TokError("expected emission kind");
3980
3981 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3982 if (!Kind)
3983 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3984 "'");
3985 assert(*Kind <= Result.Max && "Expected valid emission kind")((*Kind <= Result.Max && "Expected valid emission kind"
) ? static_cast<void> (0) : __assert_fail ("*Kind <= Result.Max && \"Expected valid emission kind\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 3985, __PRETTY_FUNCTION__))
;
3986 Result.assign(*Kind);
3987 Lex.Lex();
3988 return false;
3989}
3990
3991template <>
3992bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3993 NameTableKindField &Result) {
3994 if (Lex.getKind() == lltok::APSInt)
3995 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3996
3997 if (Lex.getKind() != lltok::NameTableKind)
3998 return TokError("expected nameTable kind");
3999
4000 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4001 if (!Kind)
4002 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4003 "'");
4004 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind")((((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"
) ? static_cast<void> (0) : __assert_fail ("((unsigned)*Kind) <= Result.Max && \"Expected valid nameTable kind\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4004, __PRETTY_FUNCTION__))
;
4005 Result.assign((unsigned)*Kind);
4006 Lex.Lex();
4007 return false;
4008}
4009
4010template <>
4011bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4012 DwarfAttEncodingField &Result) {
4013 if (Lex.getKind() == lltok::APSInt)
4014 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4015
4016 if (Lex.getKind() != lltok::DwarfAttEncoding)
4017 return TokError("expected DWARF type attribute encoding");
4018
4019 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4020 if (!Encoding)
4021 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4022 Lex.getStrVal() + "'");
4023 assert(Encoding <= Result.Max && "Expected valid DWARF language")((Encoding <= Result.Max && "Expected valid DWARF language"
) ? static_cast<void> (0) : __assert_fail ("Encoding <= Result.Max && \"Expected valid DWARF language\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4023, __PRETTY_FUNCTION__))
;
4024 Result.assign(Encoding);
4025 Lex.Lex();
4026 return false;
4027}
4028
4029/// DIFlagField
4030/// ::= uint32
4031/// ::= DIFlagVector
4032/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4033template <>
4034bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4035
4036 // Parser for a single flag.
4037 auto parseFlag = [&](DINode::DIFlags &Val) {
4038 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4039 uint32_t TempVal = static_cast<uint32_t>(Val);
4040 bool Res = ParseUInt32(TempVal);
4041 Val = static_cast<DINode::DIFlags>(TempVal);
4042 return Res;
4043 }
4044
4045 if (Lex.getKind() != lltok::DIFlag)
4046 return TokError("expected debug info flag");
4047
4048 Val = DINode::getFlag(Lex.getStrVal());
4049 if (!Val)
4050 return TokError(Twine("invalid debug info flag flag '") +
4051 Lex.getStrVal() + "'");
4052 Lex.Lex();
4053 return false;
4054 };
4055
4056 // Parse the flags and combine them together.
4057 DINode::DIFlags Combined = DINode::FlagZero;
4058 do {
4059 DINode::DIFlags Val;
4060 if (parseFlag(Val))
4061 return true;
4062 Combined |= Val;
4063 } while (EatIfPresent(lltok::bar));
4064
4065 Result.assign(Combined);
4066 return false;
4067}
4068
4069/// DISPFlagField
4070/// ::= uint32
4071/// ::= DISPFlagVector
4072/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4073template <>
4074bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4075
4076 // Parser for a single flag.
4077 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4078 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4079 uint32_t TempVal = static_cast<uint32_t>(Val);
4080 bool Res = ParseUInt32(TempVal);
4081 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4082 return Res;
4083 }
4084
4085 if (Lex.getKind() != lltok::DISPFlag)
4086 return TokError("expected debug info flag");
4087
4088 Val = DISubprogram::getFlag(Lex.getStrVal());
4089 if (!Val)
4090 return TokError(Twine("invalid subprogram debug info flag '") +
4091 Lex.getStrVal() + "'");
4092 Lex.Lex();
4093 return false;
4094 };
4095
4096 // Parse the flags and combine them together.
4097 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4098 do {
4099 DISubprogram::DISPFlags Val;
4100 if (parseFlag(Val))
4101 return true;
4102 Combined |= Val;
4103 } while (EatIfPresent(lltok::bar));
4104
4105 Result.assign(Combined);
4106 return false;
4107}
4108
4109template <>
4110bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4111 MDSignedField &Result) {
4112 if (Lex.getKind() != lltok::APSInt)
4113 return TokError("expected signed integer");
4114
4115 auto &S = Lex.getAPSIntVal();
4116 if (S < Result.Min)
4117 return TokError("value for '" + Name + "' too small, limit is " +
4118 Twine(Result.Min));
4119 if (S > Result.Max)
4120 return TokError("value for '" + Name + "' too large, limit is " +
4121 Twine(Result.Max));
4122 Result.assign(S.getExtValue());
4123 assert(Result.Val >= Result.Min && "Expected value in range")((Result.Val >= Result.Min && "Expected value in range"
) ? static_cast<void> (0) : __assert_fail ("Result.Val >= Result.Min && \"Expected value in range\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4123, __PRETTY_FUNCTION__))
;
4124 assert(Result.Val <= Result.Max && "Expected value in range")((Result.Val <= Result.Max && "Expected value in range"
) ? static_cast<void> (0) : __assert_fail ("Result.Val <= Result.Max && \"Expected value in range\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4124, __PRETTY_FUNCTION__))
;
4125 Lex.Lex();
4126 return false;
4127}
4128
4129template <>
4130bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4131 switch (Lex.getKind()) {
4132 default:
4133 return TokError("expected 'true' or 'false'");
4134 case lltok::kw_true:
4135 Result.assign(true);
4136 break;
4137 case lltok::kw_false:
4138 Result.assign(false);
4139 break;
4140 }
4141 Lex.Lex();
4142 return false;
4143}
4144
4145template <>
4146bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4147 if (Lex.getKind() == lltok::kw_null) {
4148 if (!Result.AllowNull)
4149 return TokError("'" + Name + "' cannot be null");
4150 Lex.Lex();
4151 Result.assign(nullptr);
4152 return false;
4153 }
4154
4155 Metadata *MD;
4156 if (ParseMetadata(MD, nullptr))
4157 return true;
4158
4159 Result.assign(MD);
4160 return false;
4161}
4162
4163template <>
4164bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4165 MDSignedOrMDField &Result) {
4166 // Try to parse a signed int.
4167 if (Lex.getKind() == lltok::APSInt) {
4168 MDSignedField Res = Result.A;
4169 if (!ParseMDField(Loc, Name, Res)) {
4170 Result.assign(Res);
4171 return false;
4172 }
4173 return true;
4174 }
4175
4176 // Otherwise, try to parse as an MDField.
4177 MDField Res = Result.B;
4178 if (!ParseMDField(Loc, Name, Res)) {
4179 Result.assign(Res);
4180 return false;
4181 }
4182
4183 return true;
4184}
4185
4186template <>
4187bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4188 MDSignedOrUnsignedField &Result) {
4189 if (Lex.getKind() != lltok::APSInt)
4190 return false;
4191
4192 if (Lex.getAPSIntVal().isSigned()) {
4193 MDSignedField Res = Result.A;
4194 if (ParseMDField(Loc, Name, Res))
4195 return true;
4196 Result.assign(Res);
4197 return false;
4198 }
4199
4200 MDUnsignedField Res = Result.B;
4201 if (ParseMDField(Loc, Name, Res))
4202 return true;
4203 Result.assign(Res);
4204 return false;
4205}
4206
4207template <>
4208bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4209 LocTy ValueLoc = Lex.getLoc();
4210 std::string S;
4211 if (ParseStringConstant(S))
4212 return true;
4213
4214 if (!Result.AllowEmpty && S.empty())
4215 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4216
4217 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4218 return false;
4219}
4220
4221template <>
4222bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4223 SmallVector<Metadata *, 4> MDs;
4224 if (ParseMDNodeVector(MDs))
4225 return true;
4226
4227 Result.assign(std::move(MDs));
4228 return false;
4229}
4230
4231template <>
4232bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4233 ChecksumKindField &Result) {
4234 Optional<DIFile::ChecksumKind> CSKind =
4235 DIFile::getChecksumKind(Lex.getStrVal());
4236
4237 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4238 return TokError(
4239 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4240
4241 Result.assign(*CSKind);
4242 Lex.Lex();
4243 return false;
4244}
4245
4246} // end namespace llvm
4247
4248template <class ParserTy>
4249bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4250 do {
4251 if (Lex.getKind() != lltok::LabelStr)
4252 return TokError("expected field label here");
4253
4254 if (parseField())
4255 return true;
4256 } while (EatIfPresent(lltok::comma));
4257
4258 return false;
4259}
4260
4261template <class ParserTy>
4262bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4263 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata type name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4263, __PRETTY_FUNCTION__))
;
4264 Lex.Lex();
4265
4266 if (ParseToken(lltok::lparen, "expected '(' here"))
4267 return true;
4268 if (Lex.getKind() != lltok::rparen)
4269 if (ParseMDFieldsImplBody(parseField))
4270 return true;
4271
4272 ClosingLoc = Lex.getLoc();
4273 return ParseToken(lltok::rparen, "expected ')' here");
4274}
4275
4276template <class FieldTy>
4277bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4278 if (Result.Seen)
4279 return TokError("field '" + Name + "' cannot be specified more than once");
4280
4281 LocTy Loc = Lex.getLoc();
4282 Lex.Lex();
4283 return ParseMDField(Loc, Name, Result);
4284}
4285
4286bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4287 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata type name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4287, __PRETTY_FUNCTION__))
;
4288
4289#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4290 if (Lex.getStrVal() == #CLASS) \
4291 return Parse##CLASS(N, IsDistinct);
4292#include "llvm/IR/Metadata.def"
4293
4294 return TokError("expected metadata type");
4295}
4296
4297#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4298#define NOP_FIELD(NAME, TYPE, INIT)
4299#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4300 if (!NAME.Seen) \
4301 return Error(ClosingLoc, "missing required field '" #NAME "'");
4302#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4303 if (Lex.getStrVal() == #NAME) \
4304 return ParseMDField(#NAME, NAME);
4305#define PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
\
4306 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4307 do { \
4308 LocTy ClosingLoc; \
4309 if (ParseMDFieldsImpl([&]() -> bool { \
4310 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4311 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4312 }, ClosingLoc)) \
4313 return true; \
4314 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4315 } while (false)
4316#define GET_OR_DISTINCT(CLASS, ARGS)(IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) \
4317 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4318
4319/// ParseDILocationFields:
4320/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4321/// isImplicitCode: true)
4322bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4323#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4324 OPTIONAL(line, LineField, ); \
4325 OPTIONAL(column, ColumnField, ); \
4326 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4327 OPTIONAL(inlinedAt, MDField, ); \
4328 OPTIONAL(isImplicitCode, MDBoolField, (false));
4329 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4330#undef VISIT_MD_FIELDS
4331
4332 Result =
4333 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
4334 inlinedAt.Val, isImplicitCode.Val))(IsDistinct ? DILocation::getDistinct (Context, line.Val, column
.Val, scope.Val, inlinedAt.Val, isImplicitCode.Val) : DILocation
::get (Context, line.Val, column.Val, scope.Val, inlinedAt.Val
, isImplicitCode.Val))
;
4335 return false;
4336}
4337
4338/// ParseGenericDINode:
4339/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4340bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4341#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4342 REQUIRED(tag, DwarfTagField, ); \
4343 OPTIONAL(header, MDStringField, ); \
4344 OPTIONAL(operands, MDFieldList, );
4345 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4346#undef VISIT_MD_FIELDS
4347
4348 Result = GET_OR_DISTINCT(GenericDINode,(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
4349 (Context, tag.Val, header.Val, operands.Val))(IsDistinct ? GenericDINode::getDistinct (Context, tag.Val, header
.Val, operands.Val) : GenericDINode::get (Context, tag.Val, header
.Val, operands.Val))
;
4350 return false;
4351}
4352
4353/// ParseDISubrange:
4354/// ::= !DISubrange(count: 30, lowerBound: 2)
4355/// ::= !DISubrange(count: !node, lowerBound: 2)
4356bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4357#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4358 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX(9223372036854775807L), false)); \
4359 OPTIONAL(lowerBound, MDSignedField, );
4360 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4361#undef VISIT_MD_FIELDS
4362
4363 if (count.isMDSignedField())
4364 Result = GET_OR_DISTINCT((IsDistinct ? DISubrange::getDistinct (Context, count.getMDSignedValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDSignedValue
(), lowerBound.Val))
4365 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val))(IsDistinct ? DISubrange::getDistinct (Context, count.getMDSignedValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDSignedValue
(), lowerBound.Val))
;
4366 else if (count.isMDField())
4367 Result = GET_OR_DISTINCT((IsDistinct ? DISubrange::getDistinct (Context, count.getMDFieldValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDFieldValue
(), lowerBound.Val))
4368 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val))(IsDistinct ? DISubrange::getDistinct (Context, count.getMDFieldValue
(), lowerBound.Val) : DISubrange::get (Context, count.getMDFieldValue
(), lowerBound.Val))
;
4369 else
4370 return true;
4371
4372 return false;
4373}
4374
4375/// ParseDIEnumerator:
4376/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4377bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4378#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4379 REQUIRED(name, MDStringField, ); \
4380 REQUIRED(value, MDSignedOrUnsignedField, ); \
4381 OPTIONAL(isUnsigned, MDBoolField, (false));
4382 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4383#undef VISIT_MD_FIELDS
4384
4385 if (isUnsigned.Val && value.isMDSignedField())
4386 return TokError("unsigned enumerator with negative value");
4387
4388 int64_t Value = value.isMDSignedField()
4389 ? value.getMDSignedValue()
4390 : static_cast<int64_t>(value.getMDUnsignedValue());
4391 Result =
4392 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val))(IsDistinct ? DIEnumerator::getDistinct (Context, Value, isUnsigned
.Val, name.Val) : DIEnumerator::get (Context, Value, isUnsigned
.Val, name.Val))
;
4393
4394 return false;
4395}
4396
4397/// ParseDIBasicType:
4398/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4399/// encoding: DW_ATE_encoding, flags: 0)
4400bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4401#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4402 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4403 OPTIONAL(name, MDStringField, ); \
4404 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4405 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4406 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4407 OPTIONAL(flags, DIFlagField, );
4408 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4409#undef VISIT_MD_FIELDS
4410
4411 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
4412 align.Val, encoding.Val, flags.Val))(IsDistinct ? DIBasicType::getDistinct (Context, tag.Val, name
.Val, size.Val, align.Val, encoding.Val, flags.Val) : DIBasicType
::get (Context, tag.Val, name.Val, size.Val, align.Val, encoding
.Val, flags.Val))
;
4413 return false;
4414}
4415
4416/// ParseDIDerivedType:
4417/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4418/// line: 7, scope: !1, baseType: !2, size: 32,
4419/// align: 32, offset: 0, flags: 0, extraData: !3,
4420/// dwarfAddressSpace: 3)
4421bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4422#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4423 REQUIRED(tag, DwarfTagField, ); \
4424 OPTIONAL(name, MDStringField, ); \
4425 OPTIONAL(file, MDField, ); \
4426 OPTIONAL(line, LineField, ); \
4427 OPTIONAL(scope, MDField, ); \
4428 REQUIRED(baseType, MDField, ); \
4429 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4430 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4431 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4432 OPTIONAL(flags, DIFlagField, ); \
4433 OPTIONAL(extraData, MDField, ); \
4434 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX(4294967295U), UINT32_MAX(4294967295U)));
4435 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4436#undef VISIT_MD_FIELDS
4437
4438 Optional<unsigned> DWARFAddressSpace;
4439 if (dwarfAddressSpace.Val != UINT32_MAX(4294967295U))
4440 DWARFAddressSpace = dwarfAddressSpace.Val;
4441
4442 Result = GET_OR_DISTINCT(DIDerivedType,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4443 (Context, tag.Val, name.Val, file.Val, line.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4444 scope.Val, baseType.Val, size.Val, align.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4445 offset.Val, DWARFAddressSpace, flags.Val,(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
4446 extraData.Val))(IsDistinct ? DIDerivedType::getDistinct (Context, tag.Val, name
.Val, file.Val, line.Val, scope.Val, baseType.Val, size.Val, align
.Val, offset.Val, DWARFAddressSpace, flags.Val, extraData.Val
) : DIDerivedType::get (Context, tag.Val, name.Val, file.Val,
line.Val, scope.Val, baseType.Val, size.Val, align.Val, offset
.Val, DWARFAddressSpace, flags.Val, extraData.Val))
;
4447 return false;
4448}
4449
4450bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4451#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4452 REQUIRED(tag, DwarfTagField, ); \
4453 OPTIONAL(name, MDStringField, ); \
4454 OPTIONAL(file, MDField, ); \
4455 OPTIONAL(line, LineField, ); \
4456 OPTIONAL(scope, MDField, ); \
4457 OPTIONAL(baseType, MDField, ); \
4458 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4459 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4460 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX(18446744073709551615UL))); \
4461 OPTIONAL(flags, DIFlagField, ); \
4462 OPTIONAL(elements, MDField, ); \
4463 OPTIONAL(runtimeLang, DwarfLangField, ); \
4464 OPTIONAL(vtableHolder, MDField, ); \
4465 OPTIONAL(templateParams, MDField, ); \
4466 OPTIONAL(identifier, MDStringField, ); \
4467 OPTIONAL(discriminator, MDField, );
4468 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4469#undef VISIT_MD_FIELDS
4470
4471 // If this has an identifier try to build an ODR type.
4472 if (identifier.Val)
4473 if (auto *CT = DICompositeType::buildODRType(
4474 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4475 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4476 elements.Val, runtimeLang.Val, vtableHolder.Val,
4477 templateParams.Val, discriminator.Val)) {
4478 Result = CT;
4479 return false;
4480 }
4481
4482 // Create a new node, and save it in the context if it belongs in the type
4483 // map.
4484 Result = GET_OR_DISTINCT((IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4485 DICompositeType,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4486 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4487 size.Val, align.Val, offset.Val, flags.Val, elements.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4488 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
4489 discriminator.Val))(IsDistinct ? DICompositeType::getDistinct (Context, tag.Val,
name.Val, file.Val, line.Val, scope.Val, baseType.Val, size.
Val, align.Val, offset.Val, flags.Val, elements.Val, runtimeLang
.Val, vtableHolder.Val, templateParams.Val, identifier.Val, discriminator
.Val) : DICompositeType::get (Context, tag.Val, name.Val, file
.Val, line.Val, scope.Val, baseType.Val, size.Val, align.Val,
offset.Val, flags.Val, elements.Val, runtimeLang.Val, vtableHolder
.Val, templateParams.Val, identifier.Val, discriminator.Val))
;
4490 return false;
4491}
4492
4493bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4494#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4495 OPTIONAL(flags, DIFlagField, ); \
4496 OPTIONAL(cc, DwarfCCField, ); \
4497 REQUIRED(types, MDField, );
4498 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4499#undef VISIT_MD_FIELDS
4500
4501 Result = GET_OR_DISTINCT(DISubroutineType,(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
4502 (Context, flags.Val, cc.Val, types.Val))(IsDistinct ? DISubroutineType::getDistinct (Context, flags.Val
, cc.Val, types.Val) : DISubroutineType::get (Context, flags.
Val, cc.Val, types.Val))
;
4503 return false;
4504}
4505
4506/// ParseDIFileType:
4507/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4508/// checksumkind: CSK_MD5,
4509/// checksum: "000102030405060708090a0b0c0d0e0f",
4510/// source: "source file contents")
4511bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4512 // The default constructed value for checksumkind is required, but will never
4513 // be used, as the parser checks if the field was actually Seen before using
4514 // the Val.
4515#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4516 REQUIRED(filename, MDStringField, ); \
4517 REQUIRED(directory, MDStringField, ); \
4518 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4519 OPTIONAL(checksum, MDStringField, ); \
4520 OPTIONAL(source, MDStringField, );
4521 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4522#undef VISIT_MD_FIELDS
4523
4524 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4525 if (checksumkind.Seen && checksum.Seen)
4526 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4527 else if (checksumkind.Seen || checksum.Seen)
4528 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4529
4530 Optional<MDString *> OptSource;
4531 if (source.Seen)
4532 OptSource = source.Val;
4533 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
4534 OptChecksum, OptSource))(IsDistinct ? DIFile::getDistinct (Context, filename.Val, directory
.Val, OptChecksum, OptSource) : DIFile::get (Context, filename
.Val, directory.Val, OptChecksum, OptSource))
;
4535 return false;
4536}
4537
4538/// ParseDICompileUnit:
4539/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4540/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4541/// splitDebugFilename: "abc.debug",
4542/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4543/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4544bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4545 if (!IsDistinct)
4546 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4547
4548#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4549 REQUIRED(language, DwarfLangField, ); \
4550 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4551 OPTIONAL(producer, MDStringField, ); \
4552 OPTIONAL(isOptimized, MDBoolField, ); \
4553 OPTIONAL(flags, MDStringField, ); \
4554 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4555 OPTIONAL(splitDebugFilename, MDStringField, ); \
4556 OPTIONAL(emissionKind, EmissionKindField, ); \
4557 OPTIONAL(enums, MDField, ); \
4558 OPTIONAL(retainedTypes, MDField, ); \
4559 OPTIONAL(globals, MDField, ); \
4560 OPTIONAL(imports, MDField, ); \
4561 OPTIONAL(macros, MDField, ); \
4562 OPTIONAL(dwoId, MDUnsignedField, ); \
4563 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4564 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4565 OPTIONAL(nameTableKind, NameTableKindField, ); \
4566 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4567 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4568#undef VISIT_MD_FIELDS
4569
4570 Result = DICompileUnit::getDistinct(
4571 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4572 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4573 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4574 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4575 debugBaseAddress.Val);
4576 return false;
4577}
4578
4579/// ParseDISubprogram:
4580/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4581/// file: !1, line: 7, type: !2, isLocal: false,
4582/// isDefinition: true, scopeLine: 8, containingType: !3,
4583/// virtuality: DW_VIRTUALTIY_pure_virtual,
4584/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4585/// spFlags: 10, isOptimized: false, templateParams: !4,
4586/// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4587bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4588 auto Loc = Lex.getLoc();
4589#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4590 OPTIONAL(scope, MDField, ); \
4591 OPTIONAL(name, MDStringField, ); \
4592 OPTIONAL(linkageName, MDStringField, ); \
4593 OPTIONAL(file, MDField, ); \
4594 OPTIONAL(line, LineField, ); \
4595 OPTIONAL(type, MDField, ); \
4596 OPTIONAL(isLocal, MDBoolField, ); \
4597 OPTIONAL(isDefinition, MDBoolField, (true)); \
4598 OPTIONAL(scopeLine, LineField, ); \
4599 OPTIONAL(containingType, MDField, ); \
4600 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4601 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4602 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN(-2147483647-1), INT32_MAX(2147483647))); \
4603 OPTIONAL(flags, DIFlagField, ); \
4604 OPTIONAL(spFlags, DISPFlagField, ); \
4605 OPTIONAL(isOptimized, MDBoolField, ); \
4606 OPTIONAL(unit, MDField, ); \
4607 OPTIONAL(templateParams, MDField, ); \
4608 OPTIONAL(declaration, MDField, ); \
4609 OPTIONAL(retainedNodes, MDField, ); \
4610 OPTIONAL(thrownTypes, MDField, );
4611 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4612#undef VISIT_MD_FIELDS
4613
4614 // An explicit spFlags field takes precedence over individual fields in
4615 // older IR versions.
4616 DISubprogram::DISPFlags SPFlags =
4617 spFlags.Seen ? spFlags.Val
4618 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4619 isOptimized.Val, virtuality.Val);
4620 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4621 return Lex.Error(
4622 Loc,
4623 "missing 'distinct', required for !DISubprogram that is a Definition");
4624 Result = GET_OR_DISTINCT((IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4625 DISubprogram,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4626 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4627 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4628 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
4629 declaration.Val, retainedNodes.Val, thrownTypes.Val))(IsDistinct ? DISubprogram::getDistinct (Context, scope.Val, name
.Val, linkageName.Val, file.Val, line.Val, type.Val, scopeLine
.Val, containingType.Val, virtualIndex.Val, thisAdjustment.Val
, flags.Val, SPFlags, unit.Val, templateParams.Val, declaration
.Val, retainedNodes.Val, thrownTypes.Val) : DISubprogram::get
(Context, scope.Val, name.Val, linkageName.Val, file.Val, line
.Val, type.Val, scopeLine.Val, containingType.Val, virtualIndex
.Val, thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams
.Val, declaration.Val, retainedNodes.Val, thrownTypes.Val))
;
4630 return false;
4631}
4632
4633/// ParseDILexicalBlock:
4634/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4635bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4636#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4637 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4638 OPTIONAL(file, MDField, ); \
4639 OPTIONAL(line, LineField, ); \
4640 OPTIONAL(column, ColumnField, );
4641 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4642#undef VISIT_MD_FIELDS
4643
4644 Result = GET_OR_DISTINCT((IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
4645 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val))(IsDistinct ? DILexicalBlock::getDistinct (Context, scope.Val
, file.Val, line.Val, column.Val) : DILexicalBlock::get (Context
, scope.Val, file.Val, line.Val, column.Val))
;
4646 return false;
4647}
4648
4649/// ParseDILexicalBlockFile:
4650/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4651bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4652#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4653 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4654 OPTIONAL(file, MDField, ); \
4655 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX(4294967295U)));
4656 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4657#undef VISIT_MD_FIELDS
4658
4659 Result = GET_OR_DISTINCT(DILexicalBlockFile,(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
4660 (Context, scope.Val, file.Val, discriminator.Val))(IsDistinct ? DILexicalBlockFile::getDistinct (Context, scope
.Val, file.Val, discriminator.Val) : DILexicalBlockFile::get (
Context, scope.Val, file.Val, discriminator.Val))
;
4661 return false;
4662}
4663
4664/// ParseDICommonBlock:
4665/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4666bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4667#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4668 REQUIRED(scope, MDField, ); \
4669 OPTIONAL(declaration, MDField, ); \
4670 OPTIONAL(name, MDStringField, ); \
4671 OPTIONAL(file, MDField, ); \
4672 OPTIONAL(line, LineField, );
4673 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4674#undef VISIT_MD_FIELDS
4675
4676 Result = GET_OR_DISTINCT(DICommonBlock,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4677 (Context, scope.Val, declaration.Val, name.Val,(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
4678 file.Val, line.Val))(IsDistinct ? DICommonBlock::getDistinct (Context, scope.Val,
declaration.Val, name.Val, file.Val, line.Val) : DICommonBlock
::get (Context, scope.Val, declaration.Val, name.Val, file.Val
, line.Val))
;
4679 return false;
4680}
4681
4682/// ParseDINamespace:
4683/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4684bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4685#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4686 REQUIRED(scope, MDField, ); \
4687 OPTIONAL(name, MDStringField, ); \
4688 OPTIONAL(exportSymbols, MDBoolField, );
4689 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4690#undef VISIT_MD_FIELDS
4691
4692 Result = GET_OR_DISTINCT(DINamespace,(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
4693 (Context, scope.Val, name.Val, exportSymbols.Val))(IsDistinct ? DINamespace::getDistinct (Context, scope.Val, name
.Val, exportSymbols.Val) : DINamespace::get (Context, scope.Val
, name.Val, exportSymbols.Val))
;
4694 return false;
4695}
4696
4697/// ParseDIMacro:
4698/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4699bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4700#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4701 REQUIRED(type, DwarfMacinfoTypeField, ); \
4702 OPTIONAL(line, LineField, ); \
4703 REQUIRED(name, MDStringField, ); \
4704 OPTIONAL(value, MDStringField, );
4705 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4706#undef VISIT_MD_FIELDS
4707
4708 Result = GET_OR_DISTINCT(DIMacro,(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
4709 (Context, type.Val, line.Val, name.Val, value.Val))(IsDistinct ? DIMacro::getDistinct (Context, type.Val, line.Val
, name.Val, value.Val) : DIMacro::get (Context, type.Val, line
.Val, name.Val, value.Val))
;
4710 return false;
4711}
4712
4713/// ParseDIMacroFile:
4714/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4715bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4716#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4717 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4718 OPTIONAL(line, LineField, ); \
4719 REQUIRED(file, MDField, ); \
4720 OPTIONAL(nodes, MDField, );
4721 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4722#undef VISIT_MD_FIELDS
4723
4724 Result = GET_OR_DISTINCT(DIMacroFile,(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
4725 (Context, type.Val, line.Val, file.Val, nodes.Val))(IsDistinct ? DIMacroFile::getDistinct (Context, type.Val, line
.Val, file.Val, nodes.Val) : DIMacroFile::get (Context, type.
Val, line.Val, file.Val, nodes.Val))
;
4726 return false;
4727}
4728
4729/// ParseDIModule:
4730/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4731/// includePath: "/usr/include", isysroot: "/")
4732bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4733#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4734 REQUIRED(scope, MDField, ); \
4735 REQUIRED(name, MDStringField, ); \
4736 OPTIONAL(configMacros, MDStringField, ); \
4737 OPTIONAL(includePath, MDStringField, ); \
4738 OPTIONAL(isysroot, MDStringField, );
4739 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4740#undef VISIT_MD_FIELDS
4741
4742 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,(IsDistinct ? DIModule::getDistinct (Context, scope.Val, name
.Val, configMacros.Val, includePath.Val, isysroot.Val) : DIModule
::get (Context, scope.Val, name.Val, configMacros.Val, includePath
.Val, isysroot.Val))
4743 configMacros.Val, includePath.Val, isysroot.Val))(IsDistinct ? DIModule::getDistinct (Context, scope.Val, name
.Val, configMacros.Val, includePath.Val, isysroot.Val) : DIModule
::get (Context, scope.Val, name.Val, configMacros.Val, includePath
.Val, isysroot.Val))
;
4744 return false;
4745}
4746
4747/// ParseDITemplateTypeParameter:
4748/// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4749bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4750#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4751 OPTIONAL(name, MDStringField, ); \
4752 REQUIRED(type, MDField, );
4753 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4754#undef VISIT_MD_FIELDS
4755
4756 Result =
4757 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val))(IsDistinct ? DITemplateTypeParameter::getDistinct (Context, name
.Val, type.Val) : DITemplateTypeParameter::get (Context, name
.Val, type.Val))
;
4758 return false;
4759}
4760
4761/// ParseDITemplateValueParameter:
4762/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4763/// name: "V", type: !1, value: i32 7)
4764bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4765#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4766 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4767 OPTIONAL(name, MDStringField, ); \
4768 OPTIONAL(type, MDField, ); \
4769 REQUIRED(value, MDField, );
4770 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4771#undef VISIT_MD_FIELDS
4772
4773 Result = GET_OR_DISTINCT(DITemplateValueParameter,(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, value.Val))
4774 (Context, tag.Val, name.Val, type.Val, value.Val))(IsDistinct ? DITemplateValueParameter::getDistinct (Context,
tag.Val, name.Val, type.Val, value.Val) : DITemplateValueParameter
::get (Context, tag.Val, name.Val, type.Val, value.Val))
;
4775 return false;
4776}
4777
4778/// ParseDIGlobalVariable:
4779/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4780/// file: !1, line: 7, type: !2, isLocal: false,
4781/// isDefinition: true, templateParams: !3,
4782/// declaration: !4, align: 8)
4783bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4784#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4785 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4786 OPTIONAL(scope, MDField, ); \
4787 OPTIONAL(linkageName, MDStringField, ); \
4788 OPTIONAL(file, MDField, ); \
4789 OPTIONAL(line, LineField, ); \
4790 OPTIONAL(type, MDField, ); \
4791 OPTIONAL(isLocal, MDBoolField, ); \
4792 OPTIONAL(isDefinition, MDBoolField, (true)); \
4793 OPTIONAL(templateParams, MDField, ); \
4794 OPTIONAL(declaration, MDField, ); \
4795 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U)));
4796 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4797#undef VISIT_MD_FIELDS
4798
4799 Result =
4800 GET_OR_DISTINCT(DIGlobalVariable,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4801 (Context, scope.Val, name.Val, linkageName.Val, file.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4802 line.Val, type.Val, isLocal.Val, isDefinition.Val,(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
4803 declaration.Val, templateParams.Val, align.Val))(IsDistinct ? DIGlobalVariable::getDistinct (Context, scope.Val
, name.Val, linkageName.Val, file.Val, line.Val, type.Val, isLocal
.Val, isDefinition.Val, declaration.Val, templateParams.Val, align
.Val) : DIGlobalVariable::get (Context, scope.Val, name.Val, linkageName
.Val, file.Val, line.Val, type.Val, isLocal.Val, isDefinition
.Val, declaration.Val, templateParams.Val, align.Val))
;
4804 return false;
4805}
4806
4807/// ParseDILocalVariable:
4808/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4809/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4810/// align: 8)
4811/// ::= !DILocalVariable(scope: !0, name: "foo",
4812/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4813/// align: 8)
4814bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4815#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4816 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4817 OPTIONAL(name, MDStringField, ); \
4818 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX(65535))); \
4819 OPTIONAL(file, MDField, ); \
4820 OPTIONAL(line, LineField, ); \
4821 OPTIONAL(type, MDField, ); \
4822 OPTIONAL(flags, DIFlagField, ); \
4823 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX(4294967295U)));
4824 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4825#undef VISIT_MD_FIELDS
4826
4827 Result = GET_OR_DISTINCT(DILocalVariable,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
4828 (Context, scope.Val, name.Val, file.Val, line.Val,(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
4829 type.Val, arg.Val, flags.Val, align.Val))(IsDistinct ? DILocalVariable::getDistinct (Context, scope.Val
, name.Val, file.Val, line.Val, type.Val, arg.Val, flags.Val,
align.Val) : DILocalVariable::get (Context, scope.Val, name.
Val, file.Val, line.Val, type.Val, arg.Val, flags.Val, align.
Val))
;
4830 return false;
4831}
4832
4833/// ParseDILabel:
4834/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4835bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4836#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4837 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4838 REQUIRED(name, MDStringField, ); \
4839 REQUIRED(file, MDField, ); \
4840 REQUIRED(line, LineField, );
4841 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4842#undef VISIT_MD_FIELDS
4843
4844 Result = GET_OR_DISTINCT(DILabel,(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
4845 (Context, scope.Val, name.Val, file.Val, line.Val))(IsDistinct ? DILabel::getDistinct (Context, scope.Val, name.
Val, file.Val, line.Val) : DILabel::get (Context, scope.Val, name
.Val, file.Val, line.Val))
;
4846 return false;
4847}
4848
4849/// ParseDIExpression:
4850/// ::= !DIExpression(0, 7, -1)
4851bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4852 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name")((Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::MetadataVar && \"Expected metadata type name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 4852, __PRETTY_FUNCTION__))
;
4853 Lex.Lex();
4854
4855 if (ParseToken(lltok::lparen, "expected '(' here"))
4856 return true;
4857
4858 SmallVector<uint64_t, 8> Elements;
4859 if (Lex.getKind() != lltok::rparen)
4860 do {
4861 if (Lex.getKind() == lltok::DwarfOp) {
4862 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4863 Lex.Lex();
4864 Elements.push_back(Op);
4865 continue;
4866 }
4867 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4868 }
4869
4870 if (Lex.getKind() == lltok::DwarfAttEncoding) {
4871 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
4872 Lex.Lex();
4873 Elements.push_back(Op);
4874 continue;
4875 }
4876 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'");
4877 }
4878
4879 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4880 return TokError("expected unsigned integer");
4881
4882 auto &U = Lex.getAPSIntVal();
4883 if (U.ugt(UINT64_MAX(18446744073709551615UL)))
4884 return TokError("element too large, limit is " + Twine(UINT64_MAX(18446744073709551615UL)));
4885 Elements.push_back(U.getZExtValue());
4886 Lex.Lex();
4887 } while (EatIfPresent(lltok::comma));
4888
4889 if (ParseToken(lltok::rparen, "expected ')' here"))
4890 return true;
4891
4892 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements))(IsDistinct ? DIExpression::getDistinct (Context, Elements) :
DIExpression::get (Context, Elements))
;
4893 return false;
4894}
4895
4896/// ParseDIGlobalVariableExpression:
4897/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4898bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4899 bool IsDistinct) {
4900#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4901 REQUIRED(var, MDField, ); \
4902 REQUIRED(expr, MDField, );
4903 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4904#undef VISIT_MD_FIELDS
4905
4906 Result =
4907 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val))(IsDistinct ? DIGlobalVariableExpression::getDistinct (Context
, var.Val, expr.Val) : DIGlobalVariableExpression::get (Context
, var.Val, expr.Val))
;
4908 return false;
4909}
4910
4911/// ParseDIObjCProperty:
4912/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4913/// getter: "getFoo", attributes: 7, type: !2)
4914bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4915#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4916 OPTIONAL(name, MDStringField, ); \
4917 OPTIONAL(file, MDField, ); \
4918 OPTIONAL(line, LineField, ); \
4919 OPTIONAL(setter, MDStringField, ); \
4920 OPTIONAL(getter, MDStringField, ); \
4921 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX(4294967295U))); \
4922 OPTIONAL(type, MDField, );
4923 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4924#undef VISIT_MD_FIELDS
4925
4926 Result = GET_OR_DISTINCT(DIObjCProperty,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
4927 (Context, name.Val, file.Val, line.Val, setter.Val,(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
4928 getter.Val, attributes.Val, type.Val))(IsDistinct ? DIObjCProperty::getDistinct (Context, name.Val,
file.Val, line.Val, setter.Val, getter.Val, attributes.Val, type
.Val) : DIObjCProperty::get (Context, name.Val, file.Val, line
.Val, setter.Val, getter.Val, attributes.Val, type.Val))
;
4929 return false;
4930}
4931
4932/// ParseDIImportedEntity:
4933/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4934/// line: 7, name: "foo")
4935bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4937 REQUIRED(tag, DwarfTagField, ); \
4938 REQUIRED(scope, MDField, ); \
4939 OPTIONAL(entity, MDField, ); \
4940 OPTIONAL(file, MDField, ); \
4941 OPTIONAL(line, LineField, ); \
4942 OPTIONAL(name, MDStringField, );
4943 PARSE_MD_FIELDS()VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) do { LocTy ClosingLoc
; if (ParseMDFieldsImpl([&]() -> bool { VISIT_MD_FIELDS
(PARSE_MD_FIELD, PARSE_MD_FIELD) return TokError(Twine("invalid field '"
) + Lex.getStrVal() + "'"); }, ClosingLoc)) return true; VISIT_MD_FIELDS
(NOP_FIELD, REQUIRE_FIELD) } while (false)
;
4944#undef VISIT_MD_FIELDS
4945
4946 Result = GET_OR_DISTINCT((IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
4947 DIImportedEntity,(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
4948 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val))(IsDistinct ? DIImportedEntity::getDistinct (Context, tag.Val
, scope.Val, entity.Val, file.Val, line.Val, name.Val) : DIImportedEntity
::get (Context, tag.Val, scope.Val, entity.Val, file.Val, line
.Val, name.Val))
;
4949 return false;
4950}
4951
4952#undef PARSE_MD_FIELD
4953#undef NOP_FIELD
4954#undef REQUIRE_FIELD
4955#undef DECLARE_FIELD
4956
4957/// ParseMetadataAsValue
4958/// ::= metadata i32 %local
4959/// ::= metadata i32 @global
4960/// ::= metadata i32 7
4961/// ::= metadata !0
4962/// ::= metadata !{...}
4963/// ::= metadata !"string"
4964bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4965 // Note: the type 'metadata' has already been parsed.
4966 Metadata *MD;
4967 if (ParseMetadata(MD, &PFS))
4968 return true;
4969
4970 V = MetadataAsValue::get(Context, MD);
4971 return false;
4972}
4973
4974/// ParseValueAsMetadata
4975/// ::= i32 %local
4976/// ::= i32 @global
4977/// ::= i32 7
4978bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4979 PerFunctionState *PFS) {
4980 Type *Ty;
4981 LocTy Loc;
4982 if (ParseType(Ty, TypeMsg, Loc))
4983 return true;
4984 if (Ty->isMetadataTy())
4985 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4986
4987 Value *V;
4988 if (ParseValue(Ty, V, PFS))
4989 return true;
4990
4991 MD = ValueAsMetadata::get(V);
4992 return false;
4993}
4994
4995/// ParseMetadata
4996/// ::= i32 %local
4997/// ::= i32 @global
4998/// ::= i32 7
4999/// ::= !42
5000/// ::= !{...}
5001/// ::= !"string"
5002/// ::= !DILocation(...)
5003bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5004 if (Lex.getKind() == lltok::MetadataVar) {
5005 MDNode *N;
5006 if (ParseSpecializedMDNode(N))
5007 return true;
5008 MD = N;
5009 return false;
5010 }
5011
5012 // ValueAsMetadata:
5013 // <type> <value>
5014 if (Lex.getKind() != lltok::exclaim)
5015 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
5016
5017 // '!'.
5018 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here")((Lex.getKind() == lltok::exclaim && "Expected '!' here"
) ? static_cast<void> (0) : __assert_fail ("Lex.getKind() == lltok::exclaim && \"Expected '!' here\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5018, __PRETTY_FUNCTION__))
;
5019 Lex.Lex();
5020
5021 // MDString:
5022 // ::= '!' STRINGCONSTANT
5023 if (Lex.getKind() == lltok::StringConstant) {
5024 MDString *S;
5025 if (ParseMDString(S))
5026 return true;
5027 MD = S;
5028 return false;
5029 }
5030
5031 // MDNode:
5032 // !{ ... }
5033 // !7
5034 MDNode *N;
5035 if (ParseMDNodeTail(N))
5036 return true;
5037 MD = N;
5038 return false;
5039}
5040
5041//===----------------------------------------------------------------------===//
5042// Function Parsing.
5043//===----------------------------------------------------------------------===//
5044
5045bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5046 PerFunctionState *PFS, bool IsCall) {
5047 if (Ty->isFunctionTy())
5048 return Error(ID.Loc, "functions are not values, refer to them as pointers");
5049
5050 switch (ID.Kind) {
5051 case ValID::t_LocalID:
5052 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5053 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5054 return V == nullptr;
5055 case ValID::t_LocalName:
5056 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5057 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5058 return V == nullptr;
5059 case ValID::t_InlineAsm: {
5060 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5061 return Error(ID.Loc, "invalid type for inline asm constraint string");
5062 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5063 (ID.UIntVal >> 1) & 1,
5064 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5065 return false;
5066 }
5067 case ValID::t_GlobalName:
5068 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5069 return V == nullptr;
5070 case ValID::t_GlobalID:
5071 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5072 return V == nullptr;
5073 case ValID::t_APSInt:
5074 if (!Ty->isIntegerTy())
5075 return Error(ID.Loc, "integer constant must have integer type");
5076 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5077 V = ConstantInt::get(Context, ID.APSIntVal);
5078 return false;
5079 case ValID::t_APFloat:
5080 if (!Ty->isFloatingPointTy() ||
5081 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5082 return Error(ID.Loc, "floating point constant invalid for type");
5083
5084 // The lexer has no type info, so builds all half, float, and double FP
5085 // constants as double. Fix this here. Long double does not need this.
5086 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5087 bool Ignored;
5088 if (Ty->isHalfTy())
5089 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5090 &Ignored);
5091 else if (Ty->isFloatTy())
5092 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5093 &Ignored);
5094 }
5095 V = ConstantFP::get(Context, ID.APFloatVal);
5096
5097 if (V->getType() != Ty)
5098 return Error(ID.Loc, "floating point constant does not have type '" +
5099 getTypeString(Ty) + "'");
5100
5101 return false;
5102 case ValID::t_Null:
5103 if (!Ty->isPointerTy())
5104 return Error(ID.Loc, "null must be a pointer type");
5105 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5106 return false;
5107 case ValID::t_Undef:
5108 // FIXME: LabelTy should not be a first-class type.
5109 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5110 return Error(ID.Loc, "invalid type for undef constant");
5111 V = UndefValue::get(Ty);
5112 return false;
5113 case ValID::t_EmptyArray:
5114 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5115 return Error(ID.Loc, "invalid empty array initializer");
5116 V = UndefValue::get(Ty);
5117 return false;
5118 case ValID::t_Zero:
5119 // FIXME: LabelTy should not be a first-class type.
5120 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5121 return Error(ID.Loc, "invalid type for null constant");
5122 V = Constant::getNullValue(Ty);
5123 return false;
5124 case ValID::t_None:
5125 if (!Ty->isTokenTy())
5126 return Error(ID.Loc, "invalid type for none constant");
5127 V = Constant::getNullValue(Ty);
5128 return false;
5129 case ValID::t_Constant:
5130 if (ID.ConstantVal->getType() != Ty)
5131 return Error(ID.Loc, "constant expression type mismatch");
5132
5133 V = ID.ConstantVal;
5134 return false;
5135 case ValID::t_ConstantStruct:
5136 case ValID::t_PackedConstantStruct:
5137 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5138 if (ST->getNumElements() != ID.UIntVal)
5139 return Error(ID.Loc,
5140 "initializer with struct type has wrong # elements");
5141 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5142 return Error(ID.Loc, "packed'ness of initializer and type don't match");
5143
5144 // Verify that the elements are compatible with the structtype.
5145 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5146 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5147 return Error(ID.Loc, "element " + Twine(i) +
5148 " of struct initializer doesn't match struct element type");
5149
5150 V = ConstantStruct::get(
5151 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5152 } else
5153 return Error(ID.Loc, "constant expression type mismatch");
5154 return false;
5155 }
5156 llvm_unreachable("Invalid ValID")::llvm::llvm_unreachable_internal("Invalid ValID", "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5156)
;
5157}
5158
5159bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5160 C = nullptr;
5161 ValID ID;
5162 auto Loc = Lex.getLoc();
5163 if (ParseValID(ID, /*PFS=*/nullptr))
5164 return true;
5165 switch (ID.Kind) {
5166 case ValID::t_APSInt:
5167 case ValID::t_APFloat:
5168 case ValID::t_Undef:
5169 case ValID::t_Constant:
5170 case ValID::t_ConstantStruct:
5171 case ValID::t_PackedConstantStruct: {
5172 Value *V;
5173 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5174 return true;
5175 assert(isa<Constant>(V) && "Expected a constant value")((isa<Constant>(V) && "Expected a constant value"
) ? static_cast<void> (0) : __assert_fail ("isa<Constant>(V) && \"Expected a constant value\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5175, __PRETTY_FUNCTION__))
;
5176 C = cast<Constant>(V);
5177 return false;
5178 }
5179 case ValID::t_Null:
5180 C = Constant::getNullValue(Ty);
5181 return false;
5182 default:
5183 return Error(Loc, "expected a constant value");
5184 }
5185}
5186
5187bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5188 V = nullptr;
5189 ValID ID;
5190 return ParseValID(ID, PFS) ||
5191 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5192}
5193
5194bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5195 Type *Ty = nullptr;
5196 return ParseType(Ty) ||
5197 ParseValue(Ty, V, PFS);
5198}
5199
5200bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5201 PerFunctionState &PFS) {
5202 Value *V;
5203 Loc = Lex.getLoc();
5204 if (ParseTypeAndValue(V, PFS)) return true;
5205 if (!isa<BasicBlock>(V))
5206 return Error(Loc, "expected a basic block");
5207 BB = cast<BasicBlock>(V);
5208 return false;
5209}
5210
5211/// FunctionHeader
5212/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5213/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5214/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5215/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5216bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5217 // Parse the linkage.
5218 LocTy LinkageLoc = Lex.getLoc();
5219 unsigned Linkage;
5220 unsigned Visibility;
5221 unsigned DLLStorageClass;
5222 bool DSOLocal;
5223 AttrBuilder RetAttrs;
5224 unsigned CC;
5225 bool HasLinkage;
5226 Type *RetType = nullptr;
5227 LocTy RetTypeLoc = Lex.getLoc();
5228 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5229 DSOLocal) ||
5230 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5231 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5232 return true;
5233
5234 // Verify that the linkage is ok.
5235 switch ((GlobalValue::LinkageTypes)Linkage) {
5236 case GlobalValue::ExternalLinkage:
5237 break; // always ok.
5238 case GlobalValue::ExternalWeakLinkage:
5239 if (isDefine)
5240 return Error(LinkageLoc, "invalid linkage for function definition");
5241 break;
5242 case GlobalValue::PrivateLinkage:
5243 case GlobalValue::InternalLinkage:
5244 case GlobalValue::AvailableExternallyLinkage:
5245 case GlobalValue::LinkOnceAnyLinkage:
5246 case GlobalValue::LinkOnceODRLinkage:
5247 case GlobalValue::WeakAnyLinkage:
5248 case GlobalValue::WeakODRLinkage:
5249 if (!isDefine)
5250 return Error(LinkageLoc, "invalid linkage for function declaration");
5251 break;
5252 case GlobalValue::AppendingLinkage:
5253 case GlobalValue::CommonLinkage:
5254 return Error(LinkageLoc, "invalid function linkage type");
5255 }
5256
5257 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5258 return Error(LinkageLoc,
5259 "symbol with local linkage must have default visibility");
5260
5261 if (!FunctionType::isValidReturnType(RetType))
5262 return Error(RetTypeLoc, "invalid function return type");
5263
5264 LocTy NameLoc = Lex.getLoc();
5265
5266 std::string FunctionName;
5267 if (Lex.getKind() == lltok::GlobalVar) {
5268 FunctionName = Lex.getStrVal();
5269 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5270 unsigned NameID = Lex.getUIntVal();
5271
5272 if (NameID != NumberedVals.size())
5273 return TokError("function expected to be numbered '%" +
5274 Twine(NumberedVals.size()) + "'");
5275 } else {
5276 return TokError("expected function name");
5277 }
5278
5279 Lex.Lex();
5280
5281 if (Lex.getKind() != lltok::lparen)
5282 return TokError("expected '(' in function argument list");
5283
5284 SmallVector<ArgInfo, 8> ArgList;
5285 bool isVarArg;
5286 AttrBuilder FuncAttrs;
5287 std::vector<unsigned> FwdRefAttrGrps;
5288 LocTy BuiltinLoc;
5289 std::string Section;
5290 unsigned Alignment;
5291 std::string GC;
5292 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5293 unsigned AddrSpace = 0;
5294 Constant *Prefix = nullptr;
5295 Constant *Prologue = nullptr;
5296 Constant *PersonalityFn = nullptr;
5297 Comdat *C;
5298
5299 if (ParseArgumentList(ArgList, isVarArg) ||
5300 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5301 ParseOptionalProgramAddrSpace(AddrSpace) ||
5302 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5303 BuiltinLoc) ||
5304 (EatIfPresent(lltok::kw_section) &&
5305 ParseStringConstant(Section)) ||
5306 parseOptionalComdat(FunctionName, C) ||
5307 ParseOptionalAlignment(Alignment) ||
5308 (EatIfPresent(lltok::kw_gc) &&
5309 ParseStringConstant(GC)) ||
5310 (EatIfPresent(lltok::kw_prefix) &&
5311 ParseGlobalTypeAndValue(Prefix)) ||
5312 (EatIfPresent(lltok::kw_prologue) &&
5313 ParseGlobalTypeAndValue(Prologue)) ||
5314 (EatIfPresent(lltok::kw_personality) &&
5315 ParseGlobalTypeAndValue(PersonalityFn)))
5316 return true;
5317
5318 if (FuncAttrs.contains(Attribute::Builtin))
5319 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5320
5321 // If the alignment was parsed as an attribute, move to the alignment field.
5322 if (FuncAttrs.hasAlignmentAttr()) {
5323 Alignment = FuncAttrs.getAlignment();
5324 FuncAttrs.removeAttribute(Attribute::Alignment);
5325 }
5326
5327 // Okay, if we got here, the function is syntactically valid. Convert types
5328 // and do semantic checks.
5329 std::vector<Type*> ParamTypeList;
5330 SmallVector<AttributeSet, 8> Attrs;
5331
5332 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5333 ParamTypeList.push_back(ArgList[i].Ty);
5334 Attrs.push_back(ArgList[i].Attrs);
5335 }
5336
5337 AttributeList PAL =
5338 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5339 AttributeSet::get(Context, RetAttrs), Attrs);
5340
5341 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5342 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5343
5344 FunctionType *FT =
5345 FunctionType::get(RetType, ParamTypeList, isVarArg);
5346 PointerType *PFT = PointerType::get(FT, AddrSpace);
5347
5348 Fn = nullptr;
5349 if (!FunctionName.empty()) {
5350 // If this was a definition of a forward reference, remove the definition
5351 // from the forward reference table and fill in the forward ref.
5352 auto FRVI = ForwardRefVals.find(FunctionName);
5353 if (FRVI != ForwardRefVals.end()) {
5354 Fn = M->getFunction(FunctionName);
5355 if (!Fn)
5356 return Error(FRVI->second.second, "invalid forward reference to "
5357 "function as global value!");
5358 if (Fn->getType() != PFT)
5359 return Error(FRVI->second.second, "invalid forward reference to "
5360 "function '" + FunctionName + "' with wrong type: "
5361 "expected '" + getTypeString(PFT) + "' but was '" +
5362 getTypeString(Fn->getType()) + "'");
5363 ForwardRefVals.erase(FRVI);
5364 } else if ((Fn = M->getFunction(FunctionName))) {
5365 // Reject redefinitions.
5366 return Error(NameLoc, "invalid redefinition of function '" +
5367 FunctionName + "'");
5368 } else if (M->getNamedValue(FunctionName)) {
5369 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5370 }
5371
5372 } else {
5373 // If this is a definition of a forward referenced function, make sure the
5374 // types agree.
5375 auto I = ForwardRefValIDs.find(NumberedVals.size());
5376 if (I != ForwardRefValIDs.end()) {
5377 Fn = cast<Function>(I->second.first);
5378 if (Fn->getType() != PFT)
5379 return Error(NameLoc, "type of definition and forward reference of '@" +
5380 Twine(NumberedVals.size()) + "' disagree: "
5381 "expected '" + getTypeString(PFT) + "' but was '" +
5382 getTypeString(Fn->getType()) + "'");
5383 ForwardRefValIDs.erase(I);
5384 }
5385 }
5386
5387 if (!Fn)
5388 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5389 FunctionName, M);
5390 else // Move the forward-reference to the correct spot in the module.
5391 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5392
5393 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS")((Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"
) ? static_cast<void> (0) : __assert_fail ("Fn->getAddressSpace() == AddrSpace && \"Created function in wrong AS\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5393, __PRETTY_FUNCTION__))
;
5394
5395 if (FunctionName.empty())
5396 NumberedVals.push_back(Fn);
5397
5398 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5399 maybeSetDSOLocal(DSOLocal, *Fn);
5400 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5401 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5402 Fn->setCallingConv(CC);
5403 Fn->setAttributes(PAL);
5404 Fn->setUnnamedAddr(UnnamedAddr);
5405 Fn->setAlignment(Alignment);
5406 Fn->setSection(Section);
5407 Fn->setComdat(C);
5408 Fn->setPersonalityFn(PersonalityFn);
5409 if (!GC.empty()) Fn->setGC(GC);
5410 Fn->setPrefixData(Prefix);
5411 Fn->setPrologueData(Prologue);
5412 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5413
5414 // Add all of the arguments we parsed to the function.
5415 Function::arg_iterator ArgIt = Fn->arg_begin();
5416 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5417 // If the argument has a name, insert it into the argument symbol table.
5418 if (ArgList[i].Name.empty()) continue;
5419
5420 // Set the name, if it conflicted, it will be auto-renamed.
5421 ArgIt->setName(ArgList[i].Name);
5422
5423 if (ArgIt->getName() != ArgList[i].Name)
5424 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5425 ArgList[i].Name + "'");
5426 }
5427
5428 if (isDefine)
5429 return false;
5430
5431 // Check the declaration has no block address forward references.
5432 ValID ID;
5433 if (FunctionName.empty()) {
5434 ID.Kind = ValID::t_GlobalID;
5435 ID.UIntVal = NumberedVals.size() - 1;
5436 } else {
5437 ID.Kind = ValID::t_GlobalName;
5438 ID.StrVal = FunctionName;
5439 }
5440 auto Blocks = ForwardRefBlockAddresses.find(ID);
5441 if (Blocks != ForwardRefBlockAddresses.end())
5442 return Error(Blocks->first.Loc,
5443 "cannot take blockaddress inside a declaration");
5444 return false;
5445}
5446
5447bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5448 ValID ID;
5449 if (FunctionNumber == -1) {
5450 ID.Kind = ValID::t_GlobalName;
5451 ID.StrVal = F.getName();
5452 } else {
5453 ID.Kind = ValID::t_GlobalID;
5454 ID.UIntVal = FunctionNumber;
5455 }
5456
5457 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5458 if (Blocks == P.ForwardRefBlockAddresses.end())
5459 return false;
5460
5461 for (const auto &I : Blocks->second) {
5462 const ValID &BBID = I.first;
5463 GlobalValue *GV = I.second;
5464
5465 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&(((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName
) && "Expected local id or name") ? static_cast<void
> (0) : __assert_fail ("(BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && \"Expected local id or name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5466, __PRETTY_FUNCTION__))
5466 "Expected local id or name")(((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName
) && "Expected local id or name") ? static_cast<void
> (0) : __assert_fail ("(BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && \"Expected local id or name\""
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5466, __PRETTY_FUNCTION__))
;
5467 BasicBlock *BB;
5468 if (BBID.Kind == ValID::t_LocalName)
5469 BB = GetBB(BBID.StrVal, BBID.Loc);
5470 else
5471 BB = GetBB(BBID.UIntVal, BBID.Loc);
5472 if (!BB)
5473 return P.Error(BBID.Loc, "referenced value is not a basic block");
5474
5475 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5476 GV->eraseFromParent();
5477 }
5478
5479 P.ForwardRefBlockAddresses.erase(Blocks);
5480 return false;
5481}
5482
5483/// ParseFunctionBody
5484/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5485bool LLParser::ParseFunctionBody(Function &Fn) {
5486 if (Lex.getKind() != lltok::lbrace)
5487 return TokError("expected '{' in function body");
5488 Lex.Lex(); // eat the {.
5489
5490 int FunctionNumber = -1;
5491 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5492
5493 PerFunctionState PFS(*this, Fn, FunctionNumber);
5494
5495 // Resolve block addresses and allow basic blocks to be forward-declared
5496 // within this function.
5497 if (PFS.resolveForwardRefBlockAddresses())
5498 return true;
5499 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5500
5501 // We need at least one basic block.
5502 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5503 return TokError("function body requires at least one basic block");
5504
5505 while (Lex.getKind() != lltok::rbrace &&
5506 Lex.getKind() != lltok::kw_uselistorder)
5507 if (ParseBasicBlock(PFS)) return true;
5508
5509 while (Lex.getKind() != lltok::rbrace)
5510 if (ParseUseListOrder(&PFS))
5511 return true;
5512
5513 // Eat the }.
5514 Lex.Lex();
5515
5516 // Verify function is ok.
5517 return PFS.FinishFunction();
5518}
5519
5520/// ParseBasicBlock
5521/// ::= (LabelStr|LabelID)? Instruction*
5522bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5523 // If this basic block starts out with a name, remember it.
5524 std::string Name;
5525 int NameID = -1;
5526 LocTy NameLoc = Lex.getLoc();
5527 if (Lex.getKind() == lltok::LabelStr) {
5528 Name = Lex.getStrVal();
5529 Lex.Lex();
5530 } else if (Lex.getKind() == lltok::LabelID) {
5531 NameID = Lex.getUIntVal();
5532 Lex.Lex();
5533 }
5534
5535 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc);
5536 if (!BB)
5537 return true;
5538
5539 std::string NameStr;
5540
5541 // Parse the instructions in this block until we get a terminator.
5542 Instruction *Inst;
5543 do {
5544 // This instruction may have three possibilities for a name: a) none
5545 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5546 LocTy NameLoc = Lex.getLoc();
5547 int NameID = -1;
5548 NameStr = "";
5549
5550 if (Lex.getKind() == lltok::LocalVarID) {
5551 NameID = Lex.getUIntVal();
5552 Lex.Lex();
5553 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5554 return true;
5555 } else if (Lex.getKind() == lltok::LocalVar) {
5556 NameStr = Lex.getStrVal();
5557 Lex.Lex();
5558 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5559 return true;
5560 }
5561
5562 switch (ParseInstruction(Inst, BB, PFS)) {
5563 default: llvm_unreachable("Unknown ParseInstruction result!")::llvm::llvm_unreachable_internal("Unknown ParseInstruction result!"
, "/build/llvm-toolchain-snapshot-9~svn360410/lib/AsmParser/LLParser.cpp"
, 5563)
;
5564 case InstError: return true;
5565 case InstNormal:
5566 BB->getInstList().push_back(Inst);
5567
5568 // With a normal result, we check to see if the instruction is followed by
5569 // a comma and metadata.
5570 if (EatIfPresent(lltok::comma))
5571 if (ParseInstructionMetadata(*Inst))
5572 return true;
5573 break;
5574 case InstExtraComma:
5575 BB->getInstList().push_back(Inst);
5576
5577 // If the instruction parser ate an extra comma at the end of it, it
5578 // *must* be followed by metadata.
5579 if (ParseInstructionMetadata(*Inst))
5580 return true;
5581 break;
5582 }
5583
5584 // Set the name on the instruction.
5585 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5586 } while (!Inst->isTerminator());
5587
5588 return false;
5589}
5590
5591//===----------------------------------------------------------------------===//
5592// Instruction Parsing.
5593//===----------------------------------------------------------------------===//
5594
5595/// ParseInstruction - Parse one of the many different instructions.
5596///
5597int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5598 PerFunctionState &PFS) {
5599 lltok::Kind Token = Lex.getKind();
5600 if (Token == lltok::Eof)
5601 return TokError("found end of file when expecting more instructions");
5602 LocTy Loc = Lex.getLoc();
5603 unsigned KeywordVal = Lex.getUIntVal();
5604 Lex.Lex(); // Eat the keyword.
5605
5606 switch (Token) {
5607 default: return Error(Loc, "expected instruction opcode");
5608 // Terminator Instructions.
5609 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5610 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5611 case lltok::kw_br: return ParseBr(Inst, PFS);
5612 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5613 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5614 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5615 case lltok::kw_resume: return ParseResume(Inst, PFS);
5616 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5617 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5618 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5619 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5620 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5621 case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
5622 // Unary Operators.
5623 case lltok::kw_fneg: {
5624 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5625 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true);
5626 if (Res != 0)
5627 return Res;
5628 if (FMF.any())
5629 Inst->setFastMathFlags(FMF);
5630 return false;
5631 }
5632 // Binary Operators.
5633 case lltok::kw_add:
5634 case lltok::kw_sub:
5635 case lltok::kw_mul:
5636 case lltok::kw_shl: {
5637 bool NUW = EatIfPresent(lltok::kw_nuw);
5638 bool NSW = EatIfPresent(lltok::kw_nsw);
5639 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5640
5641 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5642
5643 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5644 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5645 return false;
5646 }
5647 case lltok::kw_fadd:
5648 case lltok::kw_fsub:
5649 case lltok::kw_fmul:
5650 case lltok::kw_fdiv:
5651 case lltok::kw_frem: {
5652 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5653 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true);
5654 if (Res != 0)
5655 return Res;
5656 if (FMF.any())
5657 Inst->setFastMathFlags(FMF);
5658 return 0;
5659 }
5660
5661 case lltok::kw_sdiv:
5662 case lltok::kw_udiv:
5663 case lltok::kw_lshr:
5664 case lltok::kw_ashr: {
5665 bool Exact = EatIfPresent(lltok::kw_exact);
5666
5667 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5668 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5669 return false;
5670 }
5671
5672 case lltok::kw_urem:
5673 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal,
5674 /*IsFP*/false);
5675 case lltok::kw_and:
5676 case lltok::kw_or:
5677 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5678 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5679 case lltok::kw_fcmp: {
5680 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5681 int Res = ParseCompare(Inst, PFS, KeywordVal);
5682 if (Res != 0)
5683 return Res;
5684 if (FMF.any())
5685 Inst->setFastMathFlags(FMF);
5686 return 0;
5687 }
5688
5689 // Casts.
5690 case lltok::kw_trunc:
5691 case lltok::kw_zext:
5692 case lltok::kw_sext:
5693 case lltok::kw_fptrunc:
5694 case lltok::kw_fpext:
5695 case lltok::kw_bitcast:
5696 case lltok::kw_addrspacecast:
5697 case lltok::kw_uitofp:
5698 case lltok::kw_sitofp:
5699 case lltok::kw_fptoui:
5700 case lltok::kw_fptosi:
5701 case lltok::kw_inttoptr:
5702 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5703 // Other.
5704 case lltok::kw_select: return ParseSelect(Inst, PFS);
5705 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5706 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5707 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5708 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5709 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5710 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5711 // Call.
5712 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5713 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5714 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5715 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5716 // Memory.
5717 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5718 case lltok::kw_load: return ParseLoad(Inst, PFS);
5719 case lltok::kw_store: return ParseStore(Inst, PFS);
5720 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5721 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5722 case lltok::kw_fence: return ParseFence(Inst, PFS);
5723 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5724 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5725 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5726 }
5727}
5728
5729/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5730bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5731 if (Opc == Instruction::FCmp) {
5732 switch (Lex.getKind()) {
5733 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5734 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5735 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5736 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5737 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5738 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5739 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5740 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5741 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5742 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5743 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5744 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5745 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5746 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5747 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5748 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5749 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5750 }
5751 } else {
5752 switch (Lex.getKind()) {
5753 default: return TokError("expected icmp predicate (e.g. 'eq')");
5754 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5755 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5756 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5757 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5758 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5759 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5760 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5761 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5762 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5763 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5764 }
5765 }
5766 Lex.Lex();
5767 return false;
5768}
5769
5770//===----------------------------------------------------------------------===//
5771// Terminator Instructions.
5772//===----------------------------------------------------------------------===//
5773
5774/// ParseRet - Parse a return instruction.
5775/// ::= 'ret' void (',' !dbg, !1)*
5776/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5777bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5778 PerFunctionState &PFS) {
5779 SMLoc TypeLoc = Lex.getLoc();
5780 Type *Ty = nullptr;
5781 if (ParseType(Ty, true /*void allowed*/)) return true;
5782
5783 Type *ResType = PFS.getFunction().getReturnType();
5784
5785 if (Ty->isVoidTy()) {
5786 if (!ResType->isVoidTy())
5787 return Error(TypeLoc, "value doesn't match function result type '" +
5788 getTypeString(ResType) + "'");
5789
5790 Inst = ReturnInst::Create(Context);
5791 return false;
5792 }
5793
5794 Value *RV;
5795 if (ParseValue(Ty, RV, PFS)) return true;
5796
5797 if (ResType != RV->getType())
5798 return Error(TypeLoc, "value doesn't match function result type '" +
5799 getTypeString(ResType) + "'");
5800
5801 Inst = ReturnInst::Create(Context, RV);
5802 return false;
5803}
5804
5805/// ParseBr
5806/// ::= 'br' TypeAndValue
5807/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5808bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5809 LocTy Loc, Loc2;
5810 Value *Op0;
5811 BasicBlock *Op1, *Op2;
5812 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5813
5814 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5815 Inst = BranchInst::Create(BB);
5816 return false;
5817 }
5818
5819 if (Op0->getType() != Type::getInt1Ty(Context))
5820 return Error(Loc, "branch condition must have 'i1' type");
5821
5822 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5823 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5824 ParseToken(lltok::comma, "expected ',' after true destination") ||
5825 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5826 return true;
5827
5828 Inst = BranchInst::Create(Op1, Op2, Op0);
5829 return false;
5830}
5831
5832/// ParseSwitch
5833/// Instruction
5834/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5835/// JumpTable
5836/// ::= (TypeAndValue ',' TypeAndValue)*
5837bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5838 LocTy CondLoc, BBLoc;
5839 Value *Cond;
5840 BasicBlock *DefaultBB;
5841 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5842 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5843 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5844 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5845 return true;
5846
5847 if (!Cond->getType()->isIntegerTy())
5848 return Error(CondLoc, "switch condition must have integer type");
5849
5850 // Parse the jump table pairs.
5851 SmallPtrSet<Value*, 32> SeenCases;
5852 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5853 while (Lex.getKind() != lltok::rsquare) {
5854 Value *Constant;
5855 BasicBlock *DestBB;
5856