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 "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/ValueSymbolTable.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/SaveAndRestore.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstring>
50 #include <iterator>
51 #include <vector>
52
53 using namespace llvm;
54
getTypeString(Type * T)55 static std::string getTypeString(Type *T) {
56 std::string Result;
57 raw_string_ostream Tmp(Result);
58 Tmp << *T;
59 return Tmp.str();
60 }
61
62 /// Run: module ::= toplevelentity*
Run(bool UpgradeDebugInfo,DataLayoutCallbackTy DataLayoutCallback)63 bool LLParser::Run(bool UpgradeDebugInfo,
64 DataLayoutCallbackTy DataLayoutCallback) {
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 if (M) {
74 if (parseTargetDefinitions())
75 return true;
76
77 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
78 M->setDataLayout(*LayoutOverride);
79 }
80
81 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
82 validateEndOfIndex();
83 }
84
parseStandaloneConstantValue(Constant * & C,const SlotMapping * Slots)85 bool LLParser::parseStandaloneConstantValue(Constant *&C,
86 const SlotMapping *Slots) {
87 restoreParsingState(Slots);
88 Lex.Lex();
89
90 Type *Ty = nullptr;
91 if (parseType(Ty) || parseConstantValue(Ty, C))
92 return true;
93 if (Lex.getKind() != lltok::Eof)
94 return error(Lex.getLoc(), "expected end of string");
95 return false;
96 }
97
parseTypeAtBeginning(Type * & Ty,unsigned & Read,const SlotMapping * Slots)98 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
99 const SlotMapping *Slots) {
100 restoreParsingState(Slots);
101 Lex.Lex();
102
103 Read = 0;
104 SMLoc Start = Lex.getLoc();
105 Ty = nullptr;
106 if (parseType(Ty))
107 return true;
108 SMLoc End = Lex.getLoc();
109 Read = End.getPointer() - Start.getPointer();
110
111 return false;
112 }
113
restoreParsingState(const SlotMapping * Slots)114 void LLParser::restoreParsingState(const SlotMapping *Slots) {
115 if (!Slots)
116 return;
117 NumberedVals = Slots->GlobalValues;
118 NumberedMetadata = Slots->MetadataNodes;
119 for (const auto &I : Slots->NamedTypes)
120 NamedTypes.insert(
121 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
122 for (const auto &I : Slots->Types)
123 NumberedTypes.insert(
124 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
125 }
126
127 /// validateEndOfModule - Do final validity and sanity checks at the end of the
128 /// module.
validateEndOfModule(bool UpgradeDebugInfo)129 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
130 if (!M)
131 return false;
132 // Handle any function attribute group forward references.
133 for (const auto &RAG : ForwardRefAttrGroups) {
134 Value *V = RAG.first;
135 const std::vector<unsigned> &Attrs = RAG.second;
136 AttrBuilder B;
137
138 for (const auto &Attr : Attrs)
139 B.merge(NumberedAttrBuilders[Attr]);
140
141 if (Function *Fn = dyn_cast<Function>(V)) {
142 AttributeList AS = Fn->getAttributes();
143 AttrBuilder FnAttrs(AS.getFnAttributes());
144 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
145
146 FnAttrs.merge(B);
147
148 // If the alignment was parsed as an attribute, move to the alignment
149 // field.
150 if (FnAttrs.hasAlignmentAttr()) {
151 Fn->setAlignment(FnAttrs.getAlignment());
152 FnAttrs.removeAttribute(Attribute::Alignment);
153 }
154
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 Fn->setAttributes(AS);
158 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
159 AttributeList AS = CI->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 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeList AS = II->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 II->setAttributes(AS);
174 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
175 AttributeList AS = CBI->getAttributes();
176 AttrBuilder FnAttrs(AS.getFnAttributes());
177 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
178 FnAttrs.merge(B);
179 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
180 AttributeSet::get(Context, FnAttrs));
181 CBI->setAttributes(AS);
182 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
183 AttrBuilder Attrs(GV->getAttributes());
184 Attrs.merge(B);
185 GV->setAttributes(AttributeSet::get(Context,Attrs));
186 } else {
187 llvm_unreachable("invalid object with forward attribute group reference");
188 }
189 }
190
191 // If there are entries in ForwardRefBlockAddresses at this point, the
192 // function was never defined.
193 if (!ForwardRefBlockAddresses.empty())
194 return error(ForwardRefBlockAddresses.begin()->first.Loc,
195 "expected function name in blockaddress");
196
197 for (const auto &NT : NumberedTypes)
198 if (NT.second.second.isValid())
199 return error(NT.second.second,
200 "use of undefined type '%" + Twine(NT.first) + "'");
201
202 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
203 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
204 if (I->second.second.isValid())
205 return error(I->second.second,
206 "use of undefined type named '" + I->getKey() + "'");
207
208 if (!ForwardRefComdats.empty())
209 return error(ForwardRefComdats.begin()->second,
210 "use of undefined comdat '$" +
211 ForwardRefComdats.begin()->first + "'");
212
213 if (!ForwardRefVals.empty())
214 return error(ForwardRefVals.begin()->second.second,
215 "use of undefined value '@" + ForwardRefVals.begin()->first +
216 "'");
217
218 if (!ForwardRefValIDs.empty())
219 return error(ForwardRefValIDs.begin()->second.second,
220 "use of undefined value '@" +
221 Twine(ForwardRefValIDs.begin()->first) + "'");
222
223 if (!ForwardRefMDNodes.empty())
224 return error(ForwardRefMDNodes.begin()->second.second,
225 "use of undefined metadata '!" +
226 Twine(ForwardRefMDNodes.begin()->first) + "'");
227
228 // Resolve metadata cycles.
229 for (auto &N : NumberedMetadata) {
230 if (N.second && !N.second->isResolved())
231 N.second->resolveCycles();
232 }
233
234 for (auto *Inst : InstsWithTBAATag) {
235 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
236 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
237 auto *UpgradedMD = UpgradeTBAANode(*MD);
238 if (MD != UpgradedMD)
239 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
240 }
241
242 // Look for intrinsic functions and CallInst that need to be upgraded
243 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
244 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
245
246 // Some types could be renamed during loading if several modules are
247 // loaded in the same LLVMContext (LTO scenario). In this case we should
248 // remangle intrinsics names as well.
249 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
250 Function *F = &*FI++;
251 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
252 F->replaceAllUsesWith(Remangled.getValue());
253 F->eraseFromParent();
254 }
255 }
256
257 if (UpgradeDebugInfo)
258 llvm::UpgradeDebugInfo(*M);
259
260 UpgradeModuleFlags(*M);
261 UpgradeSectionAttributes(*M);
262
263 if (!Slots)
264 return false;
265 // Initialize the slot mapping.
266 // Because by this point we've parsed and validated everything, we can "steal"
267 // the mapping from LLParser as it doesn't need it anymore.
268 Slots->GlobalValues = std::move(NumberedVals);
269 Slots->MetadataNodes = std::move(NumberedMetadata);
270 for (const auto &I : NamedTypes)
271 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
272 for (const auto &I : NumberedTypes)
273 Slots->Types.insert(std::make_pair(I.first, I.second.first));
274
275 return false;
276 }
277
278 /// Do final validity and sanity checks at the end of the index.
validateEndOfIndex()279 bool LLParser::validateEndOfIndex() {
280 if (!Index)
281 return false;
282
283 if (!ForwardRefValueInfos.empty())
284 return error(ForwardRefValueInfos.begin()->second.front().second,
285 "use of undefined summary '^" +
286 Twine(ForwardRefValueInfos.begin()->first) + "'");
287
288 if (!ForwardRefAliasees.empty())
289 return error(ForwardRefAliasees.begin()->second.front().second,
290 "use of undefined summary '^" +
291 Twine(ForwardRefAliasees.begin()->first) + "'");
292
293 if (!ForwardRefTypeIds.empty())
294 return error(ForwardRefTypeIds.begin()->second.front().second,
295 "use of undefined type id summary '^" +
296 Twine(ForwardRefTypeIds.begin()->first) + "'");
297
298 return false;
299 }
300
301 //===----------------------------------------------------------------------===//
302 // Top-Level Entities
303 //===----------------------------------------------------------------------===//
304
parseTargetDefinitions()305 bool LLParser::parseTargetDefinitions() {
306 while (true) {
307 switch (Lex.getKind()) {
308 case lltok::kw_target:
309 if (parseTargetDefinition())
310 return true;
311 break;
312 case lltok::kw_source_filename:
313 if (parseSourceFileName())
314 return true;
315 break;
316 default:
317 return false;
318 }
319 }
320 }
321
parseTopLevelEntities()322 bool LLParser::parseTopLevelEntities() {
323 // If there is no Module, then parse just the summary index entries.
324 if (!M) {
325 while (true) {
326 switch (Lex.getKind()) {
327 case lltok::Eof:
328 return false;
329 case lltok::SummaryID:
330 if (parseSummaryEntry())
331 return true;
332 break;
333 case lltok::kw_source_filename:
334 if (parseSourceFileName())
335 return true;
336 break;
337 default:
338 // Skip everything else
339 Lex.Lex();
340 }
341 }
342 }
343 while (true) {
344 switch (Lex.getKind()) {
345 default:
346 return tokError("expected top-level entity");
347 case lltok::Eof: return false;
348 case lltok::kw_declare:
349 if (parseDeclare())
350 return true;
351 break;
352 case lltok::kw_define:
353 if (parseDefine())
354 return true;
355 break;
356 case lltok::kw_module:
357 if (parseModuleAsm())
358 return true;
359 break;
360 case lltok::kw_deplibs:
361 if (parseDepLibs())
362 return true;
363 break;
364 case lltok::LocalVarID:
365 if (parseUnnamedType())
366 return true;
367 break;
368 case lltok::LocalVar:
369 if (parseNamedType())
370 return true;
371 break;
372 case lltok::GlobalID:
373 if (parseUnnamedGlobal())
374 return true;
375 break;
376 case lltok::GlobalVar:
377 if (parseNamedGlobal())
378 return true;
379 break;
380 case lltok::ComdatVar: if (parseComdat()) return true; break;
381 case lltok::exclaim:
382 if (parseStandaloneMetadata())
383 return true;
384 break;
385 case lltok::SummaryID:
386 if (parseSummaryEntry())
387 return true;
388 break;
389 case lltok::MetadataVar:
390 if (parseNamedMetadata())
391 return true;
392 break;
393 case lltok::kw_attributes:
394 if (parseUnnamedAttrGrp())
395 return true;
396 break;
397 case lltok::kw_uselistorder:
398 if (parseUseListOrder())
399 return true;
400 break;
401 case lltok::kw_uselistorder_bb:
402 if (parseUseListOrderBB())
403 return true;
404 break;
405 }
406 }
407 }
408
409 /// toplevelentity
410 /// ::= 'module' 'asm' STRINGCONSTANT
parseModuleAsm()411 bool LLParser::parseModuleAsm() {
412 assert(Lex.getKind() == lltok::kw_module);
413 Lex.Lex();
414
415 std::string AsmStr;
416 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
417 parseStringConstant(AsmStr))
418 return true;
419
420 M->appendModuleInlineAsm(AsmStr);
421 return false;
422 }
423
424 /// toplevelentity
425 /// ::= 'target' 'triple' '=' STRINGCONSTANT
426 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
parseTargetDefinition()427 bool LLParser::parseTargetDefinition() {
428 assert(Lex.getKind() == lltok::kw_target);
429 std::string Str;
430 switch (Lex.Lex()) {
431 default:
432 return tokError("unknown target property");
433 case lltok::kw_triple:
434 Lex.Lex();
435 if (parseToken(lltok::equal, "expected '=' after target triple") ||
436 parseStringConstant(Str))
437 return true;
438 M->setTargetTriple(Str);
439 return false;
440 case lltok::kw_datalayout:
441 Lex.Lex();
442 if (parseToken(lltok::equal, "expected '=' after target datalayout") ||
443 parseStringConstant(Str))
444 return true;
445 M->setDataLayout(Str);
446 return false;
447 }
448 }
449
450 /// toplevelentity
451 /// ::= 'source_filename' '=' STRINGCONSTANT
parseSourceFileName()452 bool LLParser::parseSourceFileName() {
453 assert(Lex.getKind() == lltok::kw_source_filename);
454 Lex.Lex();
455 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
456 parseStringConstant(SourceFileName))
457 return true;
458 if (M)
459 M->setSourceFileName(SourceFileName);
460 return false;
461 }
462
463 /// toplevelentity
464 /// ::= 'deplibs' '=' '[' ']'
465 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
466 /// FIXME: Remove in 4.0. Currently parse, but ignore.
parseDepLibs()467 bool LLParser::parseDepLibs() {
468 assert(Lex.getKind() == lltok::kw_deplibs);
469 Lex.Lex();
470 if (parseToken(lltok::equal, "expected '=' after deplibs") ||
471 parseToken(lltok::lsquare, "expected '=' after deplibs"))
472 return true;
473
474 if (EatIfPresent(lltok::rsquare))
475 return false;
476
477 do {
478 std::string Str;
479 if (parseStringConstant(Str))
480 return true;
481 } while (EatIfPresent(lltok::comma));
482
483 return parseToken(lltok::rsquare, "expected ']' at end of list");
484 }
485
486 /// parseUnnamedType:
487 /// ::= LocalVarID '=' 'type' type
parseUnnamedType()488 bool LLParser::parseUnnamedType() {
489 LocTy TypeLoc = Lex.getLoc();
490 unsigned TypeID = Lex.getUIntVal();
491 Lex.Lex(); // eat LocalVarID;
492
493 if (parseToken(lltok::equal, "expected '=' after name") ||
494 parseToken(lltok::kw_type, "expected 'type' after '='"))
495 return true;
496
497 Type *Result = nullptr;
498 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
499 return true;
500
501 if (!isa<StructType>(Result)) {
502 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
503 if (Entry.first)
504 return error(TypeLoc, "non-struct types may not be recursive");
505 Entry.first = Result;
506 Entry.second = SMLoc();
507 }
508
509 return false;
510 }
511
512 /// toplevelentity
513 /// ::= LocalVar '=' 'type' type
parseNamedType()514 bool LLParser::parseNamedType() {
515 std::string Name = Lex.getStrVal();
516 LocTy NameLoc = Lex.getLoc();
517 Lex.Lex(); // eat LocalVar.
518
519 if (parseToken(lltok::equal, "expected '=' after name") ||
520 parseToken(lltok::kw_type, "expected 'type' after name"))
521 return true;
522
523 Type *Result = nullptr;
524 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
525 return true;
526
527 if (!isa<StructType>(Result)) {
528 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
529 if (Entry.first)
530 return error(NameLoc, "non-struct types may not be recursive");
531 Entry.first = Result;
532 Entry.second = SMLoc();
533 }
534
535 return false;
536 }
537
538 /// toplevelentity
539 /// ::= 'declare' FunctionHeader
parseDeclare()540 bool LLParser::parseDeclare() {
541 assert(Lex.getKind() == lltok::kw_declare);
542 Lex.Lex();
543
544 std::vector<std::pair<unsigned, MDNode *>> MDs;
545 while (Lex.getKind() == lltok::MetadataVar) {
546 unsigned MDK;
547 MDNode *N;
548 if (parseMetadataAttachment(MDK, N))
549 return true;
550 MDs.push_back({MDK, N});
551 }
552
553 Function *F;
554 if (parseFunctionHeader(F, false))
555 return true;
556 for (auto &MD : MDs)
557 F->addMetadata(MD.first, *MD.second);
558 return false;
559 }
560
561 /// toplevelentity
562 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
parseDefine()563 bool LLParser::parseDefine() {
564 assert(Lex.getKind() == lltok::kw_define);
565 Lex.Lex();
566
567 Function *F;
568 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
569 parseFunctionBody(*F);
570 }
571
572 /// parseGlobalType
573 /// ::= 'constant'
574 /// ::= 'global'
parseGlobalType(bool & IsConstant)575 bool LLParser::parseGlobalType(bool &IsConstant) {
576 if (Lex.getKind() == lltok::kw_constant)
577 IsConstant = true;
578 else if (Lex.getKind() == lltok::kw_global)
579 IsConstant = false;
580 else {
581 IsConstant = false;
582 return tokError("expected 'global' or 'constant'");
583 }
584 Lex.Lex();
585 return false;
586 }
587
parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr & UnnamedAddr)588 bool LLParser::parseOptionalUnnamedAddr(
589 GlobalVariable::UnnamedAddr &UnnamedAddr) {
590 if (EatIfPresent(lltok::kw_unnamed_addr))
591 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
592 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
593 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
594 else
595 UnnamedAddr = GlobalValue::UnnamedAddr::None;
596 return false;
597 }
598
599 /// parseUnnamedGlobal:
600 /// OptionalVisibility (ALIAS | IFUNC) ...
601 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
602 /// OptionalDLLStorageClass
603 /// ... -> global variable
604 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
605 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
606 /// OptionalVisibility
607 /// OptionalDLLStorageClass
608 /// ... -> global variable
parseUnnamedGlobal()609 bool LLParser::parseUnnamedGlobal() {
610 unsigned VarID = NumberedVals.size();
611 std::string Name;
612 LocTy NameLoc = Lex.getLoc();
613
614 // Handle the GlobalID form.
615 if (Lex.getKind() == lltok::GlobalID) {
616 if (Lex.getUIntVal() != VarID)
617 return error(Lex.getLoc(),
618 "variable expected to be numbered '%" + Twine(VarID) + "'");
619 Lex.Lex(); // eat GlobalID;
620
621 if (parseToken(lltok::equal, "expected '=' after name"))
622 return true;
623 }
624
625 bool HasLinkage;
626 unsigned Linkage, Visibility, DLLStorageClass;
627 bool DSOLocal;
628 GlobalVariable::ThreadLocalMode TLM;
629 GlobalVariable::UnnamedAddr UnnamedAddr;
630 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
631 DSOLocal) ||
632 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
633 return true;
634
635 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
636 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
637 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
638
639 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
640 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
641 }
642
643 /// parseNamedGlobal:
644 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
645 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
646 /// OptionalVisibility OptionalDLLStorageClass
647 /// ... -> global variable
parseNamedGlobal()648 bool LLParser::parseNamedGlobal() {
649 assert(Lex.getKind() == lltok::GlobalVar);
650 LocTy NameLoc = Lex.getLoc();
651 std::string Name = Lex.getStrVal();
652 Lex.Lex();
653
654 bool HasLinkage;
655 unsigned Linkage, Visibility, DLLStorageClass;
656 bool DSOLocal;
657 GlobalVariable::ThreadLocalMode TLM;
658 GlobalVariable::UnnamedAddr UnnamedAddr;
659 if (parseToken(lltok::equal, "expected '=' in global variable") ||
660 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
661 DSOLocal) ||
662 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
663 return true;
664
665 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
666 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
667 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
668
669 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
670 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
671 }
672
parseComdat()673 bool LLParser::parseComdat() {
674 assert(Lex.getKind() == lltok::ComdatVar);
675 std::string Name = Lex.getStrVal();
676 LocTy NameLoc = Lex.getLoc();
677 Lex.Lex();
678
679 if (parseToken(lltok::equal, "expected '=' here"))
680 return true;
681
682 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
683 return tokError("expected comdat type");
684
685 Comdat::SelectionKind SK;
686 switch (Lex.getKind()) {
687 default:
688 return tokError("unknown selection kind");
689 case lltok::kw_any:
690 SK = Comdat::Any;
691 break;
692 case lltok::kw_exactmatch:
693 SK = Comdat::ExactMatch;
694 break;
695 case lltok::kw_largest:
696 SK = Comdat::Largest;
697 break;
698 case lltok::kw_noduplicates:
699 SK = Comdat::NoDuplicates;
700 break;
701 case lltok::kw_samesize:
702 SK = Comdat::SameSize;
703 break;
704 }
705 Lex.Lex();
706
707 // See if the comdat was forward referenced, if so, use the comdat.
708 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
709 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
710 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
711 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
712
713 Comdat *C;
714 if (I != ComdatSymTab.end())
715 C = &I->second;
716 else
717 C = M->getOrInsertComdat(Name);
718 C->setSelectionKind(SK);
719
720 return false;
721 }
722
723 // MDString:
724 // ::= '!' STRINGCONSTANT
parseMDString(MDString * & Result)725 bool LLParser::parseMDString(MDString *&Result) {
726 std::string Str;
727 if (parseStringConstant(Str))
728 return true;
729 Result = MDString::get(Context, Str);
730 return false;
731 }
732
733 // MDNode:
734 // ::= '!' MDNodeNumber
parseMDNodeID(MDNode * & Result)735 bool LLParser::parseMDNodeID(MDNode *&Result) {
736 // !{ ..., !42, ... }
737 LocTy IDLoc = Lex.getLoc();
738 unsigned MID = 0;
739 if (parseUInt32(MID))
740 return true;
741
742 // If not a forward reference, just return it now.
743 if (NumberedMetadata.count(MID)) {
744 Result = NumberedMetadata[MID];
745 return false;
746 }
747
748 // Otherwise, create MDNode forward reference.
749 auto &FwdRef = ForwardRefMDNodes[MID];
750 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
751
752 Result = FwdRef.first.get();
753 NumberedMetadata[MID].reset(Result);
754 return false;
755 }
756
757 /// parseNamedMetadata:
758 /// !foo = !{ !1, !2 }
parseNamedMetadata()759 bool LLParser::parseNamedMetadata() {
760 assert(Lex.getKind() == lltok::MetadataVar);
761 std::string Name = Lex.getStrVal();
762 Lex.Lex();
763
764 if (parseToken(lltok::equal, "expected '=' here") ||
765 parseToken(lltok::exclaim, "Expected '!' here") ||
766 parseToken(lltok::lbrace, "Expected '{' here"))
767 return true;
768
769 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
770 if (Lex.getKind() != lltok::rbrace)
771 do {
772 MDNode *N = nullptr;
773 // parse DIExpressions inline as a special case. They are still MDNodes,
774 // so they can still appear in named metadata. Remove this logic if they
775 // become plain Metadata.
776 if (Lex.getKind() == lltok::MetadataVar &&
777 Lex.getStrVal() == "DIExpression") {
778 if (parseDIExpression(N, /*IsDistinct=*/false))
779 return true;
780 // DIArgLists should only appear inline in a function, as they may
781 // contain LocalAsMetadata arguments which require a function context.
782 } else if (Lex.getKind() == lltok::MetadataVar &&
783 Lex.getStrVal() == "DIArgList") {
784 return tokError("found DIArgList outside of function");
785 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
786 parseMDNodeID(N)) {
787 return true;
788 }
789 NMD->addOperand(N);
790 } while (EatIfPresent(lltok::comma));
791
792 return parseToken(lltok::rbrace, "expected end of metadata node");
793 }
794
795 /// parseStandaloneMetadata:
796 /// !42 = !{...}
parseStandaloneMetadata()797 bool LLParser::parseStandaloneMetadata() {
798 assert(Lex.getKind() == lltok::exclaim);
799 Lex.Lex();
800 unsigned MetadataID = 0;
801
802 MDNode *Init;
803 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
804 return true;
805
806 // Detect common error, from old metadata syntax.
807 if (Lex.getKind() == lltok::Type)
808 return tokError("unexpected type in metadata definition");
809
810 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
811 if (Lex.getKind() == lltok::MetadataVar) {
812 if (parseSpecializedMDNode(Init, IsDistinct))
813 return true;
814 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
815 parseMDTuple(Init, IsDistinct))
816 return true;
817
818 // See if this was forward referenced, if so, handle it.
819 auto FI = ForwardRefMDNodes.find(MetadataID);
820 if (FI != ForwardRefMDNodes.end()) {
821 FI->second.first->replaceAllUsesWith(Init);
822 ForwardRefMDNodes.erase(FI);
823
824 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
825 } else {
826 if (NumberedMetadata.count(MetadataID))
827 return tokError("Metadata id is already used");
828 NumberedMetadata[MetadataID].reset(Init);
829 }
830
831 return false;
832 }
833
834 // Skips a single module summary entry.
skipModuleSummaryEntry()835 bool LLParser::skipModuleSummaryEntry() {
836 // Each module summary entry consists of a tag for the entry
837 // type, followed by a colon, then the fields which may be surrounded by
838 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
839 // support is in place we will look for the tokens corresponding to the
840 // expected tags.
841 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
842 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
843 Lex.getKind() != lltok::kw_blockcount)
844 return tokError(
845 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
846 "start of summary entry");
847 if (Lex.getKind() == lltok::kw_flags)
848 return parseSummaryIndexFlags();
849 if (Lex.getKind() == lltok::kw_blockcount)
850 return parseBlockCount();
851 Lex.Lex();
852 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
853 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
854 return true;
855 // Now walk through the parenthesized entry, until the number of open
856 // parentheses goes back down to 0 (the first '(' was parsed above).
857 unsigned NumOpenParen = 1;
858 do {
859 switch (Lex.getKind()) {
860 case lltok::lparen:
861 NumOpenParen++;
862 break;
863 case lltok::rparen:
864 NumOpenParen--;
865 break;
866 case lltok::Eof:
867 return tokError("found end of file while parsing summary entry");
868 default:
869 // Skip everything in between parentheses.
870 break;
871 }
872 Lex.Lex();
873 } while (NumOpenParen > 0);
874 return false;
875 }
876
877 /// SummaryEntry
878 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
parseSummaryEntry()879 bool LLParser::parseSummaryEntry() {
880 assert(Lex.getKind() == lltok::SummaryID);
881 unsigned SummaryID = Lex.getUIntVal();
882
883 // For summary entries, colons should be treated as distinct tokens,
884 // not an indication of the end of a label token.
885 Lex.setIgnoreColonInIdentifiers(true);
886
887 Lex.Lex();
888 if (parseToken(lltok::equal, "expected '=' here"))
889 return true;
890
891 // If we don't have an index object, skip the summary entry.
892 if (!Index)
893 return skipModuleSummaryEntry();
894
895 bool result = false;
896 switch (Lex.getKind()) {
897 case lltok::kw_gv:
898 result = parseGVEntry(SummaryID);
899 break;
900 case lltok::kw_module:
901 result = parseModuleEntry(SummaryID);
902 break;
903 case lltok::kw_typeid:
904 result = parseTypeIdEntry(SummaryID);
905 break;
906 case lltok::kw_typeidCompatibleVTable:
907 result = parseTypeIdCompatibleVtableEntry(SummaryID);
908 break;
909 case lltok::kw_flags:
910 result = parseSummaryIndexFlags();
911 break;
912 case lltok::kw_blockcount:
913 result = parseBlockCount();
914 break;
915 default:
916 result = error(Lex.getLoc(), "unexpected summary kind");
917 break;
918 }
919 Lex.setIgnoreColonInIdentifiers(false);
920 return result;
921 }
922
isValidVisibilityForLinkage(unsigned V,unsigned L)923 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
924 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
925 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
926 }
927
928 // If there was an explicit dso_local, update GV. In the absence of an explicit
929 // dso_local we keep the default value.
maybeSetDSOLocal(bool DSOLocal,GlobalValue & GV)930 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
931 if (DSOLocal)
932 GV.setDSOLocal(true);
933 }
934
typeComparisonErrorMessage(StringRef Message,Type * Ty1,Type * Ty2)935 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
936 Type *Ty2) {
937 std::string ErrString;
938 raw_string_ostream ErrOS(ErrString);
939 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
940 return ErrOS.str();
941 }
942
943 /// parseIndirectSymbol:
944 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
945 /// OptionalVisibility OptionalDLLStorageClass
946 /// OptionalThreadLocal OptionalUnnamedAddr
947 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
948 ///
949 /// IndirectSymbol
950 /// ::= TypeAndValue
951 ///
952 /// IndirectSymbolAttr
953 /// ::= ',' 'partition' StringConstant
954 ///
955 /// Everything through OptionalUnnamedAddr has already been parsed.
956 ///
parseIndirectSymbol(const std::string & Name,LocTy NameLoc,unsigned L,unsigned Visibility,unsigned DLLStorageClass,bool DSOLocal,GlobalVariable::ThreadLocalMode TLM,GlobalVariable::UnnamedAddr UnnamedAddr)957 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
958 unsigned L, unsigned Visibility,
959 unsigned DLLStorageClass, bool DSOLocal,
960 GlobalVariable::ThreadLocalMode TLM,
961 GlobalVariable::UnnamedAddr UnnamedAddr) {
962 bool IsAlias;
963 if (Lex.getKind() == lltok::kw_alias)
964 IsAlias = true;
965 else if (Lex.getKind() == lltok::kw_ifunc)
966 IsAlias = false;
967 else
968 llvm_unreachable("Not an alias or ifunc!");
969 Lex.Lex();
970
971 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
972
973 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
974 return error(NameLoc, "invalid linkage type for alias");
975
976 if (!isValidVisibilityForLinkage(Visibility, L))
977 return error(NameLoc,
978 "symbol with local linkage must have default visibility");
979
980 Type *Ty;
981 LocTy ExplicitTypeLoc = Lex.getLoc();
982 if (parseType(Ty) ||
983 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
984 return true;
985
986 Constant *Aliasee;
987 LocTy AliaseeLoc = Lex.getLoc();
988 if (Lex.getKind() != lltok::kw_bitcast &&
989 Lex.getKind() != lltok::kw_getelementptr &&
990 Lex.getKind() != lltok::kw_addrspacecast &&
991 Lex.getKind() != lltok::kw_inttoptr) {
992 if (parseGlobalTypeAndValue(Aliasee))
993 return true;
994 } else {
995 // The bitcast dest type is not present, it is implied by the dest type.
996 ValID ID;
997 if (parseValID(ID))
998 return true;
999 if (ID.Kind != ValID::t_Constant)
1000 return error(AliaseeLoc, "invalid aliasee");
1001 Aliasee = ID.ConstantVal;
1002 }
1003
1004 Type *AliaseeType = Aliasee->getType();
1005 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1006 if (!PTy)
1007 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1008 unsigned AddrSpace = PTy->getAddressSpace();
1009
1010 if (IsAlias && Ty != PTy->getElementType()) {
1011 return error(
1012 ExplicitTypeLoc,
1013 typeComparisonErrorMessage(
1014 "explicit pointee type doesn't match operand's pointee type", Ty,
1015 PTy->getElementType()));
1016 }
1017
1018 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) {
1019 return error(ExplicitTypeLoc,
1020 "explicit pointee type should be a function type");
1021 }
1022
1023 GlobalValue *GVal = nullptr;
1024
1025 // See if the alias was forward referenced, if so, prepare to replace the
1026 // forward reference.
1027 if (!Name.empty()) {
1028 GVal = M->getNamedValue(Name);
1029 if (GVal) {
1030 if (!ForwardRefVals.erase(Name))
1031 return error(NameLoc, "redefinition of global '@" + Name + "'");
1032 }
1033 } else {
1034 auto I = ForwardRefValIDs.find(NumberedVals.size());
1035 if (I != ForwardRefValIDs.end()) {
1036 GVal = I->second.first;
1037 ForwardRefValIDs.erase(I);
1038 }
1039 }
1040
1041 // Okay, create the alias but do not insert it into the module yet.
1042 std::unique_ptr<GlobalIndirectSymbol> GA;
1043 if (IsAlias)
1044 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1045 (GlobalValue::LinkageTypes)Linkage, Name,
1046 Aliasee, /*Parent*/ nullptr));
1047 else
1048 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
1049 (GlobalValue::LinkageTypes)Linkage, Name,
1050 Aliasee, /*Parent*/ nullptr));
1051 GA->setThreadLocalMode(TLM);
1052 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1053 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1054 GA->setUnnamedAddr(UnnamedAddr);
1055 maybeSetDSOLocal(DSOLocal, *GA);
1056
1057 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1058 // Now parse them if there are any.
1059 while (Lex.getKind() == lltok::comma) {
1060 Lex.Lex();
1061
1062 if (Lex.getKind() == lltok::kw_partition) {
1063 Lex.Lex();
1064 GA->setPartition(Lex.getStrVal());
1065 if (parseToken(lltok::StringConstant, "expected partition string"))
1066 return true;
1067 } else {
1068 return tokError("unknown alias or ifunc property!");
1069 }
1070 }
1071
1072 if (Name.empty())
1073 NumberedVals.push_back(GA.get());
1074
1075 if (GVal) {
1076 // Verify that types agree.
1077 if (GVal->getType() != GA->getType())
1078 return error(
1079 ExplicitTypeLoc,
1080 "forward reference and definition of alias have different types");
1081
1082 // If they agree, just RAUW the old value with the alias and remove the
1083 // forward ref info.
1084 GVal->replaceAllUsesWith(GA.get());
1085 GVal->eraseFromParent();
1086 }
1087
1088 // Insert into the module, we know its name won't collide now.
1089 if (IsAlias)
1090 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1091 else
1092 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1093 assert(GA->getName() == Name && "Should not be a name conflict!");
1094
1095 // The module owns this now
1096 GA.release();
1097
1098 return false;
1099 }
1100
1101 /// parseGlobal
1102 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1103 /// OptionalVisibility OptionalDLLStorageClass
1104 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1105 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1106 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1107 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1108 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1109 /// Const OptionalAttrs
1110 ///
1111 /// Everything up to and including OptionalUnnamedAddr has been parsed
1112 /// already.
1113 ///
parseGlobal(const std::string & Name,LocTy NameLoc,unsigned Linkage,bool HasLinkage,unsigned Visibility,unsigned DLLStorageClass,bool DSOLocal,GlobalVariable::ThreadLocalMode TLM,GlobalVariable::UnnamedAddr UnnamedAddr)1114 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1115 unsigned Linkage, bool HasLinkage,
1116 unsigned Visibility, unsigned DLLStorageClass,
1117 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1118 GlobalVariable::UnnamedAddr UnnamedAddr) {
1119 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1120 return error(NameLoc,
1121 "symbol with local linkage must have default visibility");
1122
1123 unsigned AddrSpace;
1124 bool IsConstant, IsExternallyInitialized;
1125 LocTy IsExternallyInitializedLoc;
1126 LocTy TyLoc;
1127
1128 Type *Ty = nullptr;
1129 if (parseOptionalAddrSpace(AddrSpace) ||
1130 parseOptionalToken(lltok::kw_externally_initialized,
1131 IsExternallyInitialized,
1132 &IsExternallyInitializedLoc) ||
1133 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1134 return true;
1135
1136 // If the linkage is specified and is external, then no initializer is
1137 // present.
1138 Constant *Init = nullptr;
1139 if (!HasLinkage ||
1140 !GlobalValue::isValidDeclarationLinkage(
1141 (GlobalValue::LinkageTypes)Linkage)) {
1142 if (parseGlobalValue(Ty, Init))
1143 return true;
1144 }
1145
1146 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1147 return error(TyLoc, "invalid type for global variable");
1148
1149 GlobalValue *GVal = nullptr;
1150
1151 // See if the global was forward referenced, if so, use the global.
1152 if (!Name.empty()) {
1153 GVal = M->getNamedValue(Name);
1154 if (GVal) {
1155 if (!ForwardRefVals.erase(Name))
1156 return error(NameLoc, "redefinition of global '@" + Name + "'");
1157 }
1158 } else {
1159 auto I = ForwardRefValIDs.find(NumberedVals.size());
1160 if (I != ForwardRefValIDs.end()) {
1161 GVal = I->second.first;
1162 ForwardRefValIDs.erase(I);
1163 }
1164 }
1165
1166 GlobalVariable *GV;
1167 if (!GVal) {
1168 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1169 Name, nullptr, GlobalVariable::NotThreadLocal,
1170 AddrSpace);
1171 } else {
1172 if (GVal->getValueType() != Ty)
1173 return error(
1174 TyLoc,
1175 "forward reference and definition of global have different types");
1176
1177 GV = cast<GlobalVariable>(GVal);
1178
1179 // Move the forward-reference to the correct spot in the module.
1180 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1181 }
1182
1183 if (Name.empty())
1184 NumberedVals.push_back(GV);
1185
1186 // Set the parsed properties on the global.
1187 if (Init)
1188 GV->setInitializer(Init);
1189 GV->setConstant(IsConstant);
1190 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1191 maybeSetDSOLocal(DSOLocal, *GV);
1192 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1193 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1194 GV->setExternallyInitialized(IsExternallyInitialized);
1195 GV->setThreadLocalMode(TLM);
1196 GV->setUnnamedAddr(UnnamedAddr);
1197
1198 // parse attributes on the global.
1199 while (Lex.getKind() == lltok::comma) {
1200 Lex.Lex();
1201
1202 if (Lex.getKind() == lltok::kw_section) {
1203 Lex.Lex();
1204 GV->setSection(Lex.getStrVal());
1205 if (parseToken(lltok::StringConstant, "expected global section string"))
1206 return true;
1207 } else if (Lex.getKind() == lltok::kw_partition) {
1208 Lex.Lex();
1209 GV->setPartition(Lex.getStrVal());
1210 if (parseToken(lltok::StringConstant, "expected partition string"))
1211 return true;
1212 } else if (Lex.getKind() == lltok::kw_align) {
1213 MaybeAlign Alignment;
1214 if (parseOptionalAlignment(Alignment))
1215 return true;
1216 GV->setAlignment(Alignment);
1217 } else if (Lex.getKind() == lltok::MetadataVar) {
1218 if (parseGlobalObjectMetadataAttachment(*GV))
1219 return true;
1220 } else {
1221 Comdat *C;
1222 if (parseOptionalComdat(Name, C))
1223 return true;
1224 if (C)
1225 GV->setComdat(C);
1226 else
1227 return tokError("unknown global variable property!");
1228 }
1229 }
1230
1231 AttrBuilder Attrs;
1232 LocTy BuiltinLoc;
1233 std::vector<unsigned> FwdRefAttrGrps;
1234 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1235 return true;
1236 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1237 GV->setAttributes(AttributeSet::get(Context, Attrs));
1238 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1239 }
1240
1241 return false;
1242 }
1243
1244 /// parseUnnamedAttrGrp
1245 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
parseUnnamedAttrGrp()1246 bool LLParser::parseUnnamedAttrGrp() {
1247 assert(Lex.getKind() == lltok::kw_attributes);
1248 LocTy AttrGrpLoc = Lex.getLoc();
1249 Lex.Lex();
1250
1251 if (Lex.getKind() != lltok::AttrGrpID)
1252 return tokError("expected attribute group id");
1253
1254 unsigned VarID = Lex.getUIntVal();
1255 std::vector<unsigned> unused;
1256 LocTy BuiltinLoc;
1257 Lex.Lex();
1258
1259 if (parseToken(lltok::equal, "expected '=' here") ||
1260 parseToken(lltok::lbrace, "expected '{' here") ||
1261 parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1262 BuiltinLoc) ||
1263 parseToken(lltok::rbrace, "expected end of attribute group"))
1264 return true;
1265
1266 if (!NumberedAttrBuilders[VarID].hasAttributes())
1267 return error(AttrGrpLoc, "attribute group has no attributes");
1268
1269 return false;
1270 }
1271
1272 /// parseFnAttributeValuePairs
1273 /// ::= <attr> | <attr> '=' <value>
parseFnAttributeValuePairs(AttrBuilder & B,std::vector<unsigned> & FwdRefAttrGrps,bool inAttrGrp,LocTy & BuiltinLoc)1274 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1275 std::vector<unsigned> &FwdRefAttrGrps,
1276 bool inAttrGrp, LocTy &BuiltinLoc) {
1277 bool HaveError = false;
1278
1279 B.clear();
1280
1281 while (true) {
1282 lltok::Kind Token = Lex.getKind();
1283 if (Token == lltok::kw_builtin)
1284 BuiltinLoc = Lex.getLoc();
1285 switch (Token) {
1286 default:
1287 if (!inAttrGrp) return HaveError;
1288 return error(Lex.getLoc(), "unterminated attribute group");
1289 case lltok::rbrace:
1290 // Finished.
1291 return false;
1292
1293 case lltok::AttrGrpID: {
1294 // Allow a function to reference an attribute group:
1295 //
1296 // define void @foo() #1 { ... }
1297 if (inAttrGrp)
1298 HaveError |= error(
1299 Lex.getLoc(),
1300 "cannot have an attribute group reference in an attribute group");
1301
1302 unsigned AttrGrpNum = Lex.getUIntVal();
1303 if (inAttrGrp) break;
1304
1305 // Save the reference to the attribute group. We'll fill it in later.
1306 FwdRefAttrGrps.push_back(AttrGrpNum);
1307 break;
1308 }
1309 // Target-dependent attributes:
1310 case lltok::StringConstant: {
1311 if (parseStringAttribute(B))
1312 return true;
1313 continue;
1314 }
1315
1316 // Target-independent attributes:
1317 case lltok::kw_align: {
1318 // As a hack, we allow function alignment to be initially parsed as an
1319 // attribute on a function declaration/definition or added to an attribute
1320 // group and later moved to the alignment field.
1321 MaybeAlign Alignment;
1322 if (inAttrGrp) {
1323 Lex.Lex();
1324 uint32_t Value = 0;
1325 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1326 return true;
1327 Alignment = Align(Value);
1328 } else {
1329 if (parseOptionalAlignment(Alignment))
1330 return true;
1331 }
1332 B.addAlignmentAttr(Alignment);
1333 continue;
1334 }
1335 case lltok::kw_alignstack: {
1336 unsigned Alignment;
1337 if (inAttrGrp) {
1338 Lex.Lex();
1339 if (parseToken(lltok::equal, "expected '=' here") ||
1340 parseUInt32(Alignment))
1341 return true;
1342 } else {
1343 if (parseOptionalStackAlignment(Alignment))
1344 return true;
1345 }
1346 B.addStackAlignmentAttr(Alignment);
1347 continue;
1348 }
1349 case lltok::kw_allocsize: {
1350 unsigned ElemSizeArg;
1351 Optional<unsigned> NumElemsArg;
1352 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1353 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1354 return true;
1355 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1356 continue;
1357 }
1358 case lltok::kw_vscale_range: {
1359 unsigned MinValue, MaxValue;
1360 // inAttrGrp doesn't matter; we only support vscale_range(a[, b])
1361 if (parseVScaleRangeArguments(MinValue, MaxValue))
1362 return true;
1363 B.addVScaleRangeAttr(MinValue, MaxValue);
1364 continue;
1365 }
1366 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1367 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1368 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1369 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1370 case lltok::kw_hot: B.addAttribute(Attribute::Hot); break;
1371 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1372 case lltok::kw_inaccessiblememonly:
1373 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1374 case lltok::kw_inaccessiblemem_or_argmemonly:
1375 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1376 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1377 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1378 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1379 case lltok::kw_mustprogress:
1380 B.addAttribute(Attribute::MustProgress);
1381 break;
1382 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1383 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1384 case lltok::kw_nocallback:
1385 B.addAttribute(Attribute::NoCallback);
1386 break;
1387 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1388 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1389 case lltok::kw_noimplicitfloat:
1390 B.addAttribute(Attribute::NoImplicitFloat); break;
1391 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1392 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1393 case lltok::kw_nomerge: B.addAttribute(Attribute::NoMerge); break;
1394 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1395 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1396 case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1397 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1398 case lltok::kw_noprofile: B.addAttribute(Attribute::NoProfile); break;
1399 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1400 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1401 case lltok::kw_null_pointer_is_valid:
1402 B.addAttribute(Attribute::NullPointerIsValid); break;
1403 case lltok::kw_optforfuzzing:
1404 B.addAttribute(Attribute::OptForFuzzing); break;
1405 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1406 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1407 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1408 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1409 case lltok::kw_returns_twice:
1410 B.addAttribute(Attribute::ReturnsTwice); break;
1411 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1412 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1413 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1414 case lltok::kw_sspstrong:
1415 B.addAttribute(Attribute::StackProtectStrong); break;
1416 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1417 case lltok::kw_shadowcallstack:
1418 B.addAttribute(Attribute::ShadowCallStack); break;
1419 case lltok::kw_sanitize_address:
1420 B.addAttribute(Attribute::SanitizeAddress); break;
1421 case lltok::kw_sanitize_hwaddress:
1422 B.addAttribute(Attribute::SanitizeHWAddress); break;
1423 case lltok::kw_sanitize_memtag:
1424 B.addAttribute(Attribute::SanitizeMemTag); break;
1425 case lltok::kw_sanitize_thread:
1426 B.addAttribute(Attribute::SanitizeThread); break;
1427 case lltok::kw_sanitize_memory:
1428 B.addAttribute(Attribute::SanitizeMemory); break;
1429 case lltok::kw_speculative_load_hardening:
1430 B.addAttribute(Attribute::SpeculativeLoadHardening);
1431 break;
1432 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1433 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1434 case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1435 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1436 case lltok::kw_preallocated: {
1437 Type *Ty;
1438 if (parsePreallocated(Ty))
1439 return true;
1440 B.addPreallocatedAttr(Ty);
1441 break;
1442 }
1443
1444 // error handling.
1445 case lltok::kw_inreg:
1446 case lltok::kw_signext:
1447 case lltok::kw_zeroext:
1448 HaveError |=
1449 error(Lex.getLoc(), "invalid use of attribute on a function");
1450 break;
1451 case lltok::kw_byval:
1452 case lltok::kw_dereferenceable:
1453 case lltok::kw_dereferenceable_or_null:
1454 case lltok::kw_inalloca:
1455 case lltok::kw_nest:
1456 case lltok::kw_noalias:
1457 case lltok::kw_noundef:
1458 case lltok::kw_nocapture:
1459 case lltok::kw_nonnull:
1460 case lltok::kw_returned:
1461 case lltok::kw_sret:
1462 case lltok::kw_swifterror:
1463 case lltok::kw_swiftself:
1464 case lltok::kw_swiftasync:
1465 case lltok::kw_immarg:
1466 case lltok::kw_byref:
1467 HaveError |=
1468 error(Lex.getLoc(),
1469 "invalid use of parameter-only attribute on a function");
1470 break;
1471 }
1472
1473 // parsePreallocated() consumes token
1474 if (Token != lltok::kw_preallocated)
1475 Lex.Lex();
1476 }
1477 }
1478
1479 //===----------------------------------------------------------------------===//
1480 // GlobalValue Reference/Resolution Routines.
1481 //===----------------------------------------------------------------------===//
1482
createGlobalFwdRef(Module * M,PointerType * PTy,const std::string & Name)1483 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1484 const std::string &Name) {
1485 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1486 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1487 PTy->getAddressSpace(), Name, M);
1488 else
1489 return new GlobalVariable(*M, PTy->getElementType(), false,
1490 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1491 nullptr, GlobalVariable::NotThreadLocal,
1492 PTy->getAddressSpace());
1493 }
1494
checkValidVariableType(LocTy Loc,const Twine & Name,Type * Ty,Value * Val,bool IsCall)1495 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1496 Value *Val, bool IsCall) {
1497 if (Val->getType() == Ty)
1498 return Val;
1499 // For calls we also accept variables in the program address space.
1500 Type *SuggestedTy = Ty;
1501 if (IsCall && isa<PointerType>(Ty)) {
1502 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1503 M->getDataLayout().getProgramAddressSpace());
1504 SuggestedTy = TyInProgAS;
1505 if (Val->getType() == TyInProgAS)
1506 return Val;
1507 }
1508 if (Ty->isLabelTy())
1509 error(Loc, "'" + Name + "' is not a basic block");
1510 else
1511 error(Loc, "'" + Name + "' defined with type '" +
1512 getTypeString(Val->getType()) + "' but expected '" +
1513 getTypeString(SuggestedTy) + "'");
1514 return nullptr;
1515 }
1516
1517 /// getGlobalVal - Get a value with the specified name or ID, creating a
1518 /// forward reference record if needed. This can return null if the value
1519 /// exists but does not have the right type.
getGlobalVal(const std::string & Name,Type * Ty,LocTy Loc,bool IsCall)1520 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1521 LocTy Loc, bool IsCall) {
1522 PointerType *PTy = dyn_cast<PointerType>(Ty);
1523 if (!PTy) {
1524 error(Loc, "global variable reference must have pointer type");
1525 return nullptr;
1526 }
1527
1528 // Look this name up in the normal function symbol table.
1529 GlobalValue *Val =
1530 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1531
1532 // If this is a forward reference for the value, see if we already created a
1533 // forward ref record.
1534 if (!Val) {
1535 auto I = ForwardRefVals.find(Name);
1536 if (I != ForwardRefVals.end())
1537 Val = I->second.first;
1538 }
1539
1540 // If we have the value in the symbol table or fwd-ref table, return it.
1541 if (Val)
1542 return cast_or_null<GlobalValue>(
1543 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1544
1545 // Otherwise, create a new forward reference for this value and remember it.
1546 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1547 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1548 return FwdVal;
1549 }
1550
getGlobalVal(unsigned ID,Type * Ty,LocTy Loc,bool IsCall)1551 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1552 bool IsCall) {
1553 PointerType *PTy = dyn_cast<PointerType>(Ty);
1554 if (!PTy) {
1555 error(Loc, "global variable reference must have pointer type");
1556 return nullptr;
1557 }
1558
1559 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1560
1561 // If this is a forward reference for the value, see if we already created a
1562 // forward ref record.
1563 if (!Val) {
1564 auto I = ForwardRefValIDs.find(ID);
1565 if (I != ForwardRefValIDs.end())
1566 Val = I->second.first;
1567 }
1568
1569 // If we have the value in the symbol table or fwd-ref table, return it.
1570 if (Val)
1571 return cast_or_null<GlobalValue>(
1572 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1573
1574 // Otherwise, create a new forward reference for this value and remember it.
1575 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1576 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1577 return FwdVal;
1578 }
1579
1580 //===----------------------------------------------------------------------===//
1581 // Comdat Reference/Resolution Routines.
1582 //===----------------------------------------------------------------------===//
1583
getComdat(const std::string & Name,LocTy Loc)1584 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1585 // Look this name up in the comdat symbol table.
1586 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1587 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1588 if (I != ComdatSymTab.end())
1589 return &I->second;
1590
1591 // Otherwise, create a new forward reference for this value and remember it.
1592 Comdat *C = M->getOrInsertComdat(Name);
1593 ForwardRefComdats[Name] = Loc;
1594 return C;
1595 }
1596
1597 //===----------------------------------------------------------------------===//
1598 // Helper Routines.
1599 //===----------------------------------------------------------------------===//
1600
1601 /// parseToken - If the current token has the specified kind, eat it and return
1602 /// success. Otherwise, emit the specified error and return failure.
parseToken(lltok::Kind T,const char * ErrMsg)1603 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1604 if (Lex.getKind() != T)
1605 return tokError(ErrMsg);
1606 Lex.Lex();
1607 return false;
1608 }
1609
1610 /// parseStringConstant
1611 /// ::= StringConstant
parseStringConstant(std::string & Result)1612 bool LLParser::parseStringConstant(std::string &Result) {
1613 if (Lex.getKind() != lltok::StringConstant)
1614 return tokError("expected string constant");
1615 Result = Lex.getStrVal();
1616 Lex.Lex();
1617 return false;
1618 }
1619
1620 /// parseUInt32
1621 /// ::= uint32
parseUInt32(uint32_t & Val)1622 bool LLParser::parseUInt32(uint32_t &Val) {
1623 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1624 return tokError("expected integer");
1625 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1626 if (Val64 != unsigned(Val64))
1627 return tokError("expected 32-bit integer (too large)");
1628 Val = Val64;
1629 Lex.Lex();
1630 return false;
1631 }
1632
1633 /// parseUInt64
1634 /// ::= uint64
parseUInt64(uint64_t & Val)1635 bool LLParser::parseUInt64(uint64_t &Val) {
1636 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1637 return tokError("expected integer");
1638 Val = Lex.getAPSIntVal().getLimitedValue();
1639 Lex.Lex();
1640 return false;
1641 }
1642
1643 /// parseTLSModel
1644 /// := 'localdynamic'
1645 /// := 'initialexec'
1646 /// := 'localexec'
parseTLSModel(GlobalVariable::ThreadLocalMode & TLM)1647 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1648 switch (Lex.getKind()) {
1649 default:
1650 return tokError("expected localdynamic, initialexec or localexec");
1651 case lltok::kw_localdynamic:
1652 TLM = GlobalVariable::LocalDynamicTLSModel;
1653 break;
1654 case lltok::kw_initialexec:
1655 TLM = GlobalVariable::InitialExecTLSModel;
1656 break;
1657 case lltok::kw_localexec:
1658 TLM = GlobalVariable::LocalExecTLSModel;
1659 break;
1660 }
1661
1662 Lex.Lex();
1663 return false;
1664 }
1665
1666 /// parseOptionalThreadLocal
1667 /// := /*empty*/
1668 /// := 'thread_local'
1669 /// := 'thread_local' '(' tlsmodel ')'
parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode & TLM)1670 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1671 TLM = GlobalVariable::NotThreadLocal;
1672 if (!EatIfPresent(lltok::kw_thread_local))
1673 return false;
1674
1675 TLM = GlobalVariable::GeneralDynamicTLSModel;
1676 if (Lex.getKind() == lltok::lparen) {
1677 Lex.Lex();
1678 return parseTLSModel(TLM) ||
1679 parseToken(lltok::rparen, "expected ')' after thread local model");
1680 }
1681 return false;
1682 }
1683
1684 /// parseOptionalAddrSpace
1685 /// := /*empty*/
1686 /// := 'addrspace' '(' uint32 ')'
parseOptionalAddrSpace(unsigned & AddrSpace,unsigned DefaultAS)1687 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1688 AddrSpace = DefaultAS;
1689 if (!EatIfPresent(lltok::kw_addrspace))
1690 return false;
1691 return parseToken(lltok::lparen, "expected '(' in address space") ||
1692 parseUInt32(AddrSpace) ||
1693 parseToken(lltok::rparen, "expected ')' in address space");
1694 }
1695
1696 /// parseStringAttribute
1697 /// := StringConstant
1698 /// := StringConstant '=' StringConstant
parseStringAttribute(AttrBuilder & B)1699 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1700 std::string Attr = Lex.getStrVal();
1701 Lex.Lex();
1702 std::string Val;
1703 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1704 return true;
1705 B.addAttribute(Attr, Val);
1706 return false;
1707 }
1708
1709 /// parseOptionalParamAttrs - parse a potentially empty list of parameter
1710 /// attributes.
parseOptionalParamAttrs(AttrBuilder & B)1711 bool LLParser::parseOptionalParamAttrs(AttrBuilder &B) {
1712 bool HaveError = false;
1713
1714 B.clear();
1715
1716 while (true) {
1717 lltok::Kind Token = Lex.getKind();
1718 switch (Token) {
1719 default: // End of attributes.
1720 return HaveError;
1721 case lltok::StringConstant: {
1722 if (parseStringAttribute(B))
1723 return true;
1724 continue;
1725 }
1726 case lltok::kw_align: {
1727 MaybeAlign Alignment;
1728 if (parseOptionalAlignment(Alignment, true))
1729 return true;
1730 B.addAlignmentAttr(Alignment);
1731 continue;
1732 }
1733 case lltok::kw_alignstack: {
1734 unsigned Alignment;
1735 if (parseOptionalStackAlignment(Alignment))
1736 return true;
1737 B.addStackAlignmentAttr(Alignment);
1738 continue;
1739 }
1740 case lltok::kw_byval: {
1741 Type *Ty;
1742 if (parseRequiredTypeAttr(Ty, lltok::kw_byval))
1743 return true;
1744 B.addByValAttr(Ty);
1745 continue;
1746 }
1747 case lltok::kw_sret: {
1748 Type *Ty;
1749 if (parseRequiredTypeAttr(Ty, lltok::kw_sret))
1750 return true;
1751 B.addStructRetAttr(Ty);
1752 continue;
1753 }
1754 case lltok::kw_preallocated: {
1755 Type *Ty;
1756 if (parsePreallocated(Ty))
1757 return true;
1758 B.addPreallocatedAttr(Ty);
1759 continue;
1760 }
1761 case lltok::kw_inalloca: {
1762 Type *Ty;
1763 if (parseInalloca(Ty))
1764 return true;
1765 B.addInAllocaAttr(Ty);
1766 continue;
1767 }
1768 case lltok::kw_dereferenceable: {
1769 uint64_t Bytes;
1770 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1771 return true;
1772 B.addDereferenceableAttr(Bytes);
1773 continue;
1774 }
1775 case lltok::kw_dereferenceable_or_null: {
1776 uint64_t Bytes;
1777 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1778 return true;
1779 B.addDereferenceableOrNullAttr(Bytes);
1780 continue;
1781 }
1782 case lltok::kw_byref: {
1783 Type *Ty;
1784 if (parseByRef(Ty))
1785 return true;
1786 B.addByRefAttr(Ty);
1787 continue;
1788 }
1789 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1790 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1791 case lltok::kw_noundef:
1792 B.addAttribute(Attribute::NoUndef);
1793 break;
1794 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1795 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1796 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1797 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1798 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1799 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1800 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1801 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1802 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1803 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1804 case lltok::kw_swiftasync: B.addAttribute(Attribute::SwiftAsync); break;
1805 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1806 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1807 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1808
1809 case lltok::kw_alwaysinline:
1810 case lltok::kw_argmemonly:
1811 case lltok::kw_builtin:
1812 case lltok::kw_inlinehint:
1813 case lltok::kw_jumptable:
1814 case lltok::kw_minsize:
1815 case lltok::kw_mustprogress:
1816 case lltok::kw_naked:
1817 case lltok::kw_nobuiltin:
1818 case lltok::kw_noduplicate:
1819 case lltok::kw_noimplicitfloat:
1820 case lltok::kw_noinline:
1821 case lltok::kw_nonlazybind:
1822 case lltok::kw_nomerge:
1823 case lltok::kw_noprofile:
1824 case lltok::kw_noredzone:
1825 case lltok::kw_noreturn:
1826 case lltok::kw_nocf_check:
1827 case lltok::kw_nounwind:
1828 case lltok::kw_optforfuzzing:
1829 case lltok::kw_optnone:
1830 case lltok::kw_optsize:
1831 case lltok::kw_returns_twice:
1832 case lltok::kw_sanitize_address:
1833 case lltok::kw_sanitize_hwaddress:
1834 case lltok::kw_sanitize_memtag:
1835 case lltok::kw_sanitize_memory:
1836 case lltok::kw_sanitize_thread:
1837 case lltok::kw_speculative_load_hardening:
1838 case lltok::kw_ssp:
1839 case lltok::kw_sspreq:
1840 case lltok::kw_sspstrong:
1841 case lltok::kw_safestack:
1842 case lltok::kw_shadowcallstack:
1843 case lltok::kw_strictfp:
1844 case lltok::kw_uwtable:
1845 case lltok::kw_vscale_range:
1846 HaveError |=
1847 error(Lex.getLoc(), "invalid use of function-only attribute");
1848 break;
1849 }
1850
1851 Lex.Lex();
1852 }
1853 }
1854
1855 /// parseOptionalReturnAttrs - parse a potentially empty list of return
1856 /// attributes.
parseOptionalReturnAttrs(AttrBuilder & B)1857 bool LLParser::parseOptionalReturnAttrs(AttrBuilder &B) {
1858 bool HaveError = false;
1859
1860 B.clear();
1861
1862 while (true) {
1863 lltok::Kind Token = Lex.getKind();
1864 switch (Token) {
1865 default: // End of attributes.
1866 return HaveError;
1867 case lltok::StringConstant: {
1868 if (parseStringAttribute(B))
1869 return true;
1870 continue;
1871 }
1872 case lltok::kw_dereferenceable: {
1873 uint64_t Bytes;
1874 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1875 return true;
1876 B.addDereferenceableAttr(Bytes);
1877 continue;
1878 }
1879 case lltok::kw_dereferenceable_or_null: {
1880 uint64_t Bytes;
1881 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1882 return true;
1883 B.addDereferenceableOrNullAttr(Bytes);
1884 continue;
1885 }
1886 case lltok::kw_align: {
1887 MaybeAlign Alignment;
1888 if (parseOptionalAlignment(Alignment))
1889 return true;
1890 B.addAlignmentAttr(Alignment);
1891 continue;
1892 }
1893 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1894 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1895 case lltok::kw_noundef:
1896 B.addAttribute(Attribute::NoUndef);
1897 break;
1898 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1899 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1900 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1901
1902 // error handling.
1903 case lltok::kw_byval:
1904 case lltok::kw_inalloca:
1905 case lltok::kw_nest:
1906 case lltok::kw_nocapture:
1907 case lltok::kw_returned:
1908 case lltok::kw_sret:
1909 case lltok::kw_swifterror:
1910 case lltok::kw_swiftself:
1911 case lltok::kw_swiftasync:
1912 case lltok::kw_immarg:
1913 case lltok::kw_byref:
1914 HaveError |=
1915 error(Lex.getLoc(), "invalid use of parameter-only attribute");
1916 break;
1917
1918 case lltok::kw_alignstack:
1919 case lltok::kw_alwaysinline:
1920 case lltok::kw_argmemonly:
1921 case lltok::kw_builtin:
1922 case lltok::kw_cold:
1923 case lltok::kw_inlinehint:
1924 case lltok::kw_jumptable:
1925 case lltok::kw_minsize:
1926 case lltok::kw_mustprogress:
1927 case lltok::kw_naked:
1928 case lltok::kw_nobuiltin:
1929 case lltok::kw_noduplicate:
1930 case lltok::kw_noimplicitfloat:
1931 case lltok::kw_noinline:
1932 case lltok::kw_nonlazybind:
1933 case lltok::kw_nomerge:
1934 case lltok::kw_noprofile:
1935 case lltok::kw_noredzone:
1936 case lltok::kw_noreturn:
1937 case lltok::kw_nocf_check:
1938 case lltok::kw_nounwind:
1939 case lltok::kw_optforfuzzing:
1940 case lltok::kw_optnone:
1941 case lltok::kw_optsize:
1942 case lltok::kw_returns_twice:
1943 case lltok::kw_sanitize_address:
1944 case lltok::kw_sanitize_hwaddress:
1945 case lltok::kw_sanitize_memtag:
1946 case lltok::kw_sanitize_memory:
1947 case lltok::kw_sanitize_thread:
1948 case lltok::kw_speculative_load_hardening:
1949 case lltok::kw_ssp:
1950 case lltok::kw_sspreq:
1951 case lltok::kw_sspstrong:
1952 case lltok::kw_safestack:
1953 case lltok::kw_shadowcallstack:
1954 case lltok::kw_strictfp:
1955 case lltok::kw_uwtable:
1956 case lltok::kw_vscale_range:
1957 HaveError |=
1958 error(Lex.getLoc(), "invalid use of function-only attribute");
1959 break;
1960 case lltok::kw_readnone:
1961 case lltok::kw_readonly:
1962 HaveError |=
1963 error(Lex.getLoc(), "invalid use of attribute on return type");
1964 break;
1965 case lltok::kw_preallocated:
1966 HaveError |=
1967 error(Lex.getLoc(),
1968 "invalid use of parameter-only/call site-only attribute");
1969 break;
1970 }
1971
1972 Lex.Lex();
1973 }
1974 }
1975
parseOptionalLinkageAux(lltok::Kind Kind,bool & HasLinkage)1976 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1977 HasLinkage = true;
1978 switch (Kind) {
1979 default:
1980 HasLinkage = false;
1981 return GlobalValue::ExternalLinkage;
1982 case lltok::kw_private:
1983 return GlobalValue::PrivateLinkage;
1984 case lltok::kw_internal:
1985 return GlobalValue::InternalLinkage;
1986 case lltok::kw_weak:
1987 return GlobalValue::WeakAnyLinkage;
1988 case lltok::kw_weak_odr:
1989 return GlobalValue::WeakODRLinkage;
1990 case lltok::kw_linkonce:
1991 return GlobalValue::LinkOnceAnyLinkage;
1992 case lltok::kw_linkonce_odr:
1993 return GlobalValue::LinkOnceODRLinkage;
1994 case lltok::kw_available_externally:
1995 return GlobalValue::AvailableExternallyLinkage;
1996 case lltok::kw_appending:
1997 return GlobalValue::AppendingLinkage;
1998 case lltok::kw_common:
1999 return GlobalValue::CommonLinkage;
2000 case lltok::kw_extern_weak:
2001 return GlobalValue::ExternalWeakLinkage;
2002 case lltok::kw_external:
2003 return GlobalValue::ExternalLinkage;
2004 }
2005 }
2006
2007 /// parseOptionalLinkage
2008 /// ::= /*empty*/
2009 /// ::= 'private'
2010 /// ::= 'internal'
2011 /// ::= 'weak'
2012 /// ::= 'weak_odr'
2013 /// ::= 'linkonce'
2014 /// ::= 'linkonce_odr'
2015 /// ::= 'available_externally'
2016 /// ::= 'appending'
2017 /// ::= 'common'
2018 /// ::= 'extern_weak'
2019 /// ::= 'external'
parseOptionalLinkage(unsigned & Res,bool & HasLinkage,unsigned & Visibility,unsigned & DLLStorageClass,bool & DSOLocal)2020 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2021 unsigned &Visibility,
2022 unsigned &DLLStorageClass, bool &DSOLocal) {
2023 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2024 if (HasLinkage)
2025 Lex.Lex();
2026 parseOptionalDSOLocal(DSOLocal);
2027 parseOptionalVisibility(Visibility);
2028 parseOptionalDLLStorageClass(DLLStorageClass);
2029
2030 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2031 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2032 }
2033
2034 return false;
2035 }
2036
parseOptionalDSOLocal(bool & DSOLocal)2037 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2038 switch (Lex.getKind()) {
2039 default:
2040 DSOLocal = false;
2041 break;
2042 case lltok::kw_dso_local:
2043 DSOLocal = true;
2044 Lex.Lex();
2045 break;
2046 case lltok::kw_dso_preemptable:
2047 DSOLocal = false;
2048 Lex.Lex();
2049 break;
2050 }
2051 }
2052
2053 /// parseOptionalVisibility
2054 /// ::= /*empty*/
2055 /// ::= 'default'
2056 /// ::= 'hidden'
2057 /// ::= 'protected'
2058 ///
parseOptionalVisibility(unsigned & Res)2059 void LLParser::parseOptionalVisibility(unsigned &Res) {
2060 switch (Lex.getKind()) {
2061 default:
2062 Res = GlobalValue::DefaultVisibility;
2063 return;
2064 case lltok::kw_default:
2065 Res = GlobalValue::DefaultVisibility;
2066 break;
2067 case lltok::kw_hidden:
2068 Res = GlobalValue::HiddenVisibility;
2069 break;
2070 case lltok::kw_protected:
2071 Res = GlobalValue::ProtectedVisibility;
2072 break;
2073 }
2074 Lex.Lex();
2075 }
2076
2077 /// parseOptionalDLLStorageClass
2078 /// ::= /*empty*/
2079 /// ::= 'dllimport'
2080 /// ::= 'dllexport'
2081 ///
parseOptionalDLLStorageClass(unsigned & Res)2082 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2083 switch (Lex.getKind()) {
2084 default:
2085 Res = GlobalValue::DefaultStorageClass;
2086 return;
2087 case lltok::kw_dllimport:
2088 Res = GlobalValue::DLLImportStorageClass;
2089 break;
2090 case lltok::kw_dllexport:
2091 Res = GlobalValue::DLLExportStorageClass;
2092 break;
2093 }
2094 Lex.Lex();
2095 }
2096
2097 /// parseOptionalCallingConv
2098 /// ::= /*empty*/
2099 /// ::= 'ccc'
2100 /// ::= 'fastcc'
2101 /// ::= 'intel_ocl_bicc'
2102 /// ::= 'coldcc'
2103 /// ::= 'cfguard_checkcc'
2104 /// ::= 'x86_stdcallcc'
2105 /// ::= 'x86_fastcallcc'
2106 /// ::= 'x86_thiscallcc'
2107 /// ::= 'x86_vectorcallcc'
2108 /// ::= 'arm_apcscc'
2109 /// ::= 'arm_aapcscc'
2110 /// ::= 'arm_aapcs_vfpcc'
2111 /// ::= 'aarch64_vector_pcs'
2112 /// ::= 'aarch64_sve_vector_pcs'
2113 /// ::= 'msp430_intrcc'
2114 /// ::= 'avr_intrcc'
2115 /// ::= 'avr_signalcc'
2116 /// ::= 'ptx_kernel'
2117 /// ::= 'ptx_device'
2118 /// ::= 'spir_func'
2119 /// ::= 'spir_kernel'
2120 /// ::= 'x86_64_sysvcc'
2121 /// ::= 'win64cc'
2122 /// ::= 'webkit_jscc'
2123 /// ::= 'anyregcc'
2124 /// ::= 'preserve_mostcc'
2125 /// ::= 'preserve_allcc'
2126 /// ::= 'ghccc'
2127 /// ::= 'swiftcc'
2128 /// ::= 'swifttailcc'
2129 /// ::= 'x86_intrcc'
2130 /// ::= 'hhvmcc'
2131 /// ::= 'hhvm_ccc'
2132 /// ::= 'cxx_fast_tlscc'
2133 /// ::= 'amdgpu_vs'
2134 /// ::= 'amdgpu_ls'
2135 /// ::= 'amdgpu_hs'
2136 /// ::= 'amdgpu_es'
2137 /// ::= 'amdgpu_gs'
2138 /// ::= 'amdgpu_ps'
2139 /// ::= 'amdgpu_cs'
2140 /// ::= 'amdgpu_kernel'
2141 /// ::= 'tailcc'
2142 /// ::= 'cc' UINT
2143 ///
parseOptionalCallingConv(unsigned & CC)2144 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2145 switch (Lex.getKind()) {
2146 default: CC = CallingConv::C; return false;
2147 case lltok::kw_ccc: CC = CallingConv::C; break;
2148 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2149 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2150 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2151 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
2152 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2153 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
2154 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2155 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2156 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
2157 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
2158 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2159 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2160 case lltok::kw_aarch64_sve_vector_pcs:
2161 CC = CallingConv::AArch64_SVE_VectorCall;
2162 break;
2163 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
2164 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
2165 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
2166 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
2167 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
2168 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
2169 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
2170 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2171 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
2172 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2173 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
2174 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2175 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2176 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2177 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2178 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2179 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
2180 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2181 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
2182 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
2183 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2184 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2185 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
2186 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2187 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2188 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2189 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2190 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2191 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2192 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2193 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2194 case lltok::kw_cc: {
2195 Lex.Lex();
2196 return parseUInt32(CC);
2197 }
2198 }
2199
2200 Lex.Lex();
2201 return false;
2202 }
2203
2204 /// parseMetadataAttachment
2205 /// ::= !dbg !42
parseMetadataAttachment(unsigned & Kind,MDNode * & MD)2206 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2207 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2208
2209 std::string Name = Lex.getStrVal();
2210 Kind = M->getMDKindID(Name);
2211 Lex.Lex();
2212
2213 return parseMDNode(MD);
2214 }
2215
2216 /// parseInstructionMetadata
2217 /// ::= !dbg !42 (',' !dbg !57)*
parseInstructionMetadata(Instruction & Inst)2218 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2219 do {
2220 if (Lex.getKind() != lltok::MetadataVar)
2221 return tokError("expected metadata after comma");
2222
2223 unsigned MDK;
2224 MDNode *N;
2225 if (parseMetadataAttachment(MDK, N))
2226 return true;
2227
2228 Inst.setMetadata(MDK, N);
2229 if (MDK == LLVMContext::MD_tbaa)
2230 InstsWithTBAATag.push_back(&Inst);
2231
2232 // If this is the end of the list, we're done.
2233 } while (EatIfPresent(lltok::comma));
2234 return false;
2235 }
2236
2237 /// parseGlobalObjectMetadataAttachment
2238 /// ::= !dbg !57
parseGlobalObjectMetadataAttachment(GlobalObject & GO)2239 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2240 unsigned MDK;
2241 MDNode *N;
2242 if (parseMetadataAttachment(MDK, N))
2243 return true;
2244
2245 GO.addMetadata(MDK, *N);
2246 return false;
2247 }
2248
2249 /// parseOptionalFunctionMetadata
2250 /// ::= (!dbg !57)*
parseOptionalFunctionMetadata(Function & F)2251 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2252 while (Lex.getKind() == lltok::MetadataVar)
2253 if (parseGlobalObjectMetadataAttachment(F))
2254 return true;
2255 return false;
2256 }
2257
2258 /// parseOptionalAlignment
2259 /// ::= /* empty */
2260 /// ::= 'align' 4
parseOptionalAlignment(MaybeAlign & Alignment,bool AllowParens)2261 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2262 Alignment = None;
2263 if (!EatIfPresent(lltok::kw_align))
2264 return false;
2265 LocTy AlignLoc = Lex.getLoc();
2266 uint32_t Value = 0;
2267
2268 LocTy ParenLoc = Lex.getLoc();
2269 bool HaveParens = false;
2270 if (AllowParens) {
2271 if (EatIfPresent(lltok::lparen))
2272 HaveParens = true;
2273 }
2274
2275 if (parseUInt32(Value))
2276 return true;
2277
2278 if (HaveParens && !EatIfPresent(lltok::rparen))
2279 return error(ParenLoc, "expected ')'");
2280
2281 if (!isPowerOf2_32(Value))
2282 return error(AlignLoc, "alignment is not a power of two");
2283 if (Value > Value::MaximumAlignment)
2284 return error(AlignLoc, "huge alignments are not supported yet");
2285 Alignment = Align(Value);
2286 return false;
2287 }
2288
2289 /// parseOptionalDerefAttrBytes
2290 /// ::= /* empty */
2291 /// ::= AttrKind '(' 4 ')'
2292 ///
2293 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
parseOptionalDerefAttrBytes(lltok::Kind AttrKind,uint64_t & Bytes)2294 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2295 uint64_t &Bytes) {
2296 assert((AttrKind == lltok::kw_dereferenceable ||
2297 AttrKind == lltok::kw_dereferenceable_or_null) &&
2298 "contract!");
2299
2300 Bytes = 0;
2301 if (!EatIfPresent(AttrKind))
2302 return false;
2303 LocTy ParenLoc = Lex.getLoc();
2304 if (!EatIfPresent(lltok::lparen))
2305 return error(ParenLoc, "expected '('");
2306 LocTy DerefLoc = Lex.getLoc();
2307 if (parseUInt64(Bytes))
2308 return true;
2309 ParenLoc = Lex.getLoc();
2310 if (!EatIfPresent(lltok::rparen))
2311 return error(ParenLoc, "expected ')'");
2312 if (!Bytes)
2313 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2314 return false;
2315 }
2316
2317 /// parseOptionalCommaAlign
2318 /// ::=
2319 /// ::= ',' align 4
2320 ///
2321 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2322 /// end.
parseOptionalCommaAlign(MaybeAlign & Alignment,bool & AteExtraComma)2323 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2324 bool &AteExtraComma) {
2325 AteExtraComma = false;
2326 while (EatIfPresent(lltok::comma)) {
2327 // Metadata at the end is an early exit.
2328 if (Lex.getKind() == lltok::MetadataVar) {
2329 AteExtraComma = true;
2330 return false;
2331 }
2332
2333 if (Lex.getKind() != lltok::kw_align)
2334 return error(Lex.getLoc(), "expected metadata or 'align'");
2335
2336 if (parseOptionalAlignment(Alignment))
2337 return true;
2338 }
2339
2340 return false;
2341 }
2342
2343 /// parseOptionalCommaAddrSpace
2344 /// ::=
2345 /// ::= ',' addrspace(1)
2346 ///
2347 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2348 /// end.
parseOptionalCommaAddrSpace(unsigned & AddrSpace,LocTy & Loc,bool & AteExtraComma)2349 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2350 bool &AteExtraComma) {
2351 AteExtraComma = false;
2352 while (EatIfPresent(lltok::comma)) {
2353 // Metadata at the end is an early exit.
2354 if (Lex.getKind() == lltok::MetadataVar) {
2355 AteExtraComma = true;
2356 return false;
2357 }
2358
2359 Loc = Lex.getLoc();
2360 if (Lex.getKind() != lltok::kw_addrspace)
2361 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2362
2363 if (parseOptionalAddrSpace(AddrSpace))
2364 return true;
2365 }
2366
2367 return false;
2368 }
2369
parseAllocSizeArguments(unsigned & BaseSizeArg,Optional<unsigned> & HowManyArg)2370 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2371 Optional<unsigned> &HowManyArg) {
2372 Lex.Lex();
2373
2374 auto StartParen = Lex.getLoc();
2375 if (!EatIfPresent(lltok::lparen))
2376 return error(StartParen, "expected '('");
2377
2378 if (parseUInt32(BaseSizeArg))
2379 return true;
2380
2381 if (EatIfPresent(lltok::comma)) {
2382 auto HowManyAt = Lex.getLoc();
2383 unsigned HowMany;
2384 if (parseUInt32(HowMany))
2385 return true;
2386 if (HowMany == BaseSizeArg)
2387 return error(HowManyAt,
2388 "'allocsize' indices can't refer to the same parameter");
2389 HowManyArg = HowMany;
2390 } else
2391 HowManyArg = None;
2392
2393 auto EndParen = Lex.getLoc();
2394 if (!EatIfPresent(lltok::rparen))
2395 return error(EndParen, "expected ')'");
2396 return false;
2397 }
2398
parseVScaleRangeArguments(unsigned & MinValue,unsigned & MaxValue)2399 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2400 unsigned &MaxValue) {
2401 Lex.Lex();
2402
2403 auto StartParen = Lex.getLoc();
2404 if (!EatIfPresent(lltok::lparen))
2405 return error(StartParen, "expected '('");
2406
2407 if (parseUInt32(MinValue))
2408 return true;
2409
2410 if (EatIfPresent(lltok::comma)) {
2411 if (parseUInt32(MaxValue))
2412 return true;
2413 } else
2414 MaxValue = MinValue;
2415
2416 auto EndParen = Lex.getLoc();
2417 if (!EatIfPresent(lltok::rparen))
2418 return error(EndParen, "expected ')'");
2419 return false;
2420 }
2421
2422 /// parseScopeAndOrdering
2423 /// if isAtomic: ::= SyncScope? AtomicOrdering
2424 /// else: ::=
2425 ///
2426 /// This sets Scope and Ordering to the parsed values.
parseScopeAndOrdering(bool IsAtomic,SyncScope::ID & SSID,AtomicOrdering & Ordering)2427 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2428 AtomicOrdering &Ordering) {
2429 if (!IsAtomic)
2430 return false;
2431
2432 return parseScope(SSID) || parseOrdering(Ordering);
2433 }
2434
2435 /// parseScope
2436 /// ::= syncscope("singlethread" | "<target scope>")?
2437 ///
2438 /// This sets synchronization scope ID to the ID of the parsed value.
parseScope(SyncScope::ID & SSID)2439 bool LLParser::parseScope(SyncScope::ID &SSID) {
2440 SSID = SyncScope::System;
2441 if (EatIfPresent(lltok::kw_syncscope)) {
2442 auto StartParenAt = Lex.getLoc();
2443 if (!EatIfPresent(lltok::lparen))
2444 return error(StartParenAt, "Expected '(' in syncscope");
2445
2446 std::string SSN;
2447 auto SSNAt = Lex.getLoc();
2448 if (parseStringConstant(SSN))
2449 return error(SSNAt, "Expected synchronization scope name");
2450
2451 auto EndParenAt = Lex.getLoc();
2452 if (!EatIfPresent(lltok::rparen))
2453 return error(EndParenAt, "Expected ')' in syncscope");
2454
2455 SSID = Context.getOrInsertSyncScopeID(SSN);
2456 }
2457
2458 return false;
2459 }
2460
2461 /// parseOrdering
2462 /// ::= AtomicOrdering
2463 ///
2464 /// This sets Ordering to the parsed value.
parseOrdering(AtomicOrdering & Ordering)2465 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2466 switch (Lex.getKind()) {
2467 default:
2468 return tokError("Expected ordering on atomic instruction");
2469 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2470 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2471 // Not specified yet:
2472 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2473 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2474 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2475 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2476 case lltok::kw_seq_cst:
2477 Ordering = AtomicOrdering::SequentiallyConsistent;
2478 break;
2479 }
2480 Lex.Lex();
2481 return false;
2482 }
2483
2484 /// parseOptionalStackAlignment
2485 /// ::= /* empty */
2486 /// ::= 'alignstack' '(' 4 ')'
parseOptionalStackAlignment(unsigned & Alignment)2487 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2488 Alignment = 0;
2489 if (!EatIfPresent(lltok::kw_alignstack))
2490 return false;
2491 LocTy ParenLoc = Lex.getLoc();
2492 if (!EatIfPresent(lltok::lparen))
2493 return error(ParenLoc, "expected '('");
2494 LocTy AlignLoc = Lex.getLoc();
2495 if (parseUInt32(Alignment))
2496 return true;
2497 ParenLoc = Lex.getLoc();
2498 if (!EatIfPresent(lltok::rparen))
2499 return error(ParenLoc, "expected ')'");
2500 if (!isPowerOf2_32(Alignment))
2501 return error(AlignLoc, "stack alignment is not a power of two");
2502 return false;
2503 }
2504
2505 /// parseIndexList - This parses the index list for an insert/extractvalue
2506 /// instruction. This sets AteExtraComma in the case where we eat an extra
2507 /// comma at the end of the line and find that it is followed by metadata.
2508 /// Clients that don't allow metadata can call the version of this function that
2509 /// only takes one argument.
2510 ///
2511 /// parseIndexList
2512 /// ::= (',' uint32)+
2513 ///
parseIndexList(SmallVectorImpl<unsigned> & Indices,bool & AteExtraComma)2514 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2515 bool &AteExtraComma) {
2516 AteExtraComma = false;
2517
2518 if (Lex.getKind() != lltok::comma)
2519 return tokError("expected ',' as start of index list");
2520
2521 while (EatIfPresent(lltok::comma)) {
2522 if (Lex.getKind() == lltok::MetadataVar) {
2523 if (Indices.empty())
2524 return tokError("expected index");
2525 AteExtraComma = true;
2526 return false;
2527 }
2528 unsigned Idx = 0;
2529 if (parseUInt32(Idx))
2530 return true;
2531 Indices.push_back(Idx);
2532 }
2533
2534 return false;
2535 }
2536
2537 //===----------------------------------------------------------------------===//
2538 // Type Parsing.
2539 //===----------------------------------------------------------------------===//
2540
2541 /// parseType - parse a type.
parseType(Type * & Result,const Twine & Msg,bool AllowVoid)2542 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2543 SMLoc TypeLoc = Lex.getLoc();
2544 switch (Lex.getKind()) {
2545 default:
2546 return tokError(Msg);
2547 case lltok::Type:
2548 // Type ::= 'float' | 'void' (etc)
2549 Result = Lex.getTyVal();
2550 Lex.Lex();
2551 break;
2552 case lltok::lbrace:
2553 // Type ::= StructType
2554 if (parseAnonStructType(Result, false))
2555 return true;
2556 break;
2557 case lltok::lsquare:
2558 // Type ::= '[' ... ']'
2559 Lex.Lex(); // eat the lsquare.
2560 if (parseArrayVectorType(Result, false))
2561 return true;
2562 break;
2563 case lltok::less: // Either vector or packed struct.
2564 // Type ::= '<' ... '>'
2565 Lex.Lex();
2566 if (Lex.getKind() == lltok::lbrace) {
2567 if (parseAnonStructType(Result, true) ||
2568 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2569 return true;
2570 } else if (parseArrayVectorType(Result, true))
2571 return true;
2572 break;
2573 case lltok::LocalVar: {
2574 // Type ::= %foo
2575 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2576
2577 // If the type hasn't been defined yet, create a forward definition and
2578 // remember where that forward def'n was seen (in case it never is defined).
2579 if (!Entry.first) {
2580 Entry.first = StructType::create(Context, Lex.getStrVal());
2581 Entry.second = Lex.getLoc();
2582 }
2583 Result = Entry.first;
2584 Lex.Lex();
2585 break;
2586 }
2587
2588 case lltok::LocalVarID: {
2589 // Type ::= %4
2590 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2591
2592 // If the type hasn't been defined yet, create a forward definition and
2593 // remember where that forward def'n was seen (in case it never is defined).
2594 if (!Entry.first) {
2595 Entry.first = StructType::create(Context);
2596 Entry.second = Lex.getLoc();
2597 }
2598 Result = Entry.first;
2599 Lex.Lex();
2600 break;
2601 }
2602 }
2603
2604 if (Result->isPointerTy() && cast<PointerType>(Result)->isOpaque()) {
2605 unsigned AddrSpace;
2606 if (parseOptionalAddrSpace(AddrSpace))
2607 return true;
2608 Result = PointerType::get(getContext(), AddrSpace);
2609 }
2610
2611 // parse the type suffixes.
2612 while (true) {
2613 switch (Lex.getKind()) {
2614 // End of type.
2615 default:
2616 if (!AllowVoid && Result->isVoidTy())
2617 return error(TypeLoc, "void type only allowed for function results");
2618 return false;
2619
2620 // Type ::= Type '*'
2621 case lltok::star:
2622 if (Result->isLabelTy())
2623 return tokError("basic block pointers are invalid");
2624 if (Result->isVoidTy())
2625 return tokError("pointers to void are invalid - use i8* instead");
2626 if (!PointerType::isValidElementType(Result))
2627 return tokError("pointer to this type is invalid");
2628 Result = PointerType::getUnqual(Result);
2629 Lex.Lex();
2630 break;
2631
2632 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2633 case lltok::kw_addrspace: {
2634 if (Result->isLabelTy())
2635 return tokError("basic block pointers are invalid");
2636 if (Result->isVoidTy())
2637 return tokError("pointers to void are invalid; use i8* instead");
2638 if (!PointerType::isValidElementType(Result))
2639 return tokError("pointer to this type is invalid");
2640 unsigned AddrSpace;
2641 if (parseOptionalAddrSpace(AddrSpace) ||
2642 parseToken(lltok::star, "expected '*' in address space"))
2643 return true;
2644
2645 Result = PointerType::get(Result, AddrSpace);
2646 break;
2647 }
2648
2649 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2650 case lltok::lparen:
2651 if (parseFunctionType(Result))
2652 return true;
2653 break;
2654 }
2655 }
2656 }
2657
2658 /// parseParameterList
2659 /// ::= '(' ')'
2660 /// ::= '(' Arg (',' Arg)* ')'
2661 /// Arg
2662 /// ::= Type OptionalAttributes Value OptionalAttributes
parseParameterList(SmallVectorImpl<ParamInfo> & ArgList,PerFunctionState & PFS,bool IsMustTailCall,bool InVarArgsFunc)2663 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2664 PerFunctionState &PFS, bool IsMustTailCall,
2665 bool InVarArgsFunc) {
2666 if (parseToken(lltok::lparen, "expected '(' in call"))
2667 return true;
2668
2669 while (Lex.getKind() != lltok::rparen) {
2670 // If this isn't the first argument, we need a comma.
2671 if (!ArgList.empty() &&
2672 parseToken(lltok::comma, "expected ',' in argument list"))
2673 return true;
2674
2675 // parse an ellipsis if this is a musttail call in a variadic function.
2676 if (Lex.getKind() == lltok::dotdotdot) {
2677 const char *Msg = "unexpected ellipsis in argument list for ";
2678 if (!IsMustTailCall)
2679 return tokError(Twine(Msg) + "non-musttail call");
2680 if (!InVarArgsFunc)
2681 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2682 Lex.Lex(); // Lex the '...', it is purely for readability.
2683 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2684 }
2685
2686 // parse the argument.
2687 LocTy ArgLoc;
2688 Type *ArgTy = nullptr;
2689 AttrBuilder ArgAttrs;
2690 Value *V;
2691 if (parseType(ArgTy, ArgLoc))
2692 return true;
2693
2694 if (ArgTy->isMetadataTy()) {
2695 if (parseMetadataAsValue(V, PFS))
2696 return true;
2697 } else {
2698 // Otherwise, handle normal operands.
2699 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2700 return true;
2701 }
2702 ArgList.push_back(ParamInfo(
2703 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2704 }
2705
2706 if (IsMustTailCall && InVarArgsFunc)
2707 return tokError("expected '...' at end of argument list for musttail call "
2708 "in varargs function");
2709
2710 Lex.Lex(); // Lex the ')'.
2711 return false;
2712 }
2713
2714 /// parseRequiredTypeAttr
2715 /// ::= attrname(<ty>)
parseRequiredTypeAttr(Type * & Result,lltok::Kind AttrName)2716 bool LLParser::parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName) {
2717 Result = nullptr;
2718 if (!EatIfPresent(AttrName))
2719 return true;
2720 if (!EatIfPresent(lltok::lparen))
2721 return error(Lex.getLoc(), "expected '('");
2722 if (parseType(Result))
2723 return true;
2724 if (!EatIfPresent(lltok::rparen))
2725 return error(Lex.getLoc(), "expected ')'");
2726 return false;
2727 }
2728
2729 /// parsePreallocated
2730 /// ::= preallocated(<ty>)
parsePreallocated(Type * & Result)2731 bool LLParser::parsePreallocated(Type *&Result) {
2732 return parseRequiredTypeAttr(Result, lltok::kw_preallocated);
2733 }
2734
2735 /// parseInalloca
2736 /// ::= inalloca(<ty>)
parseInalloca(Type * & Result)2737 bool LLParser::parseInalloca(Type *&Result) {
2738 return parseRequiredTypeAttr(Result, lltok::kw_inalloca);
2739 }
2740
2741 /// parseByRef
2742 /// ::= byref(<type>)
parseByRef(Type * & Result)2743 bool LLParser::parseByRef(Type *&Result) {
2744 return parseRequiredTypeAttr(Result, lltok::kw_byref);
2745 }
2746
2747 /// parseOptionalOperandBundles
2748 /// ::= /*empty*/
2749 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2750 ///
2751 /// OperandBundle
2752 /// ::= bundle-tag '(' ')'
2753 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2754 ///
2755 /// bundle-tag ::= String Constant
parseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> & BundleList,PerFunctionState & PFS)2756 bool LLParser::parseOptionalOperandBundles(
2757 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2758 LocTy BeginLoc = Lex.getLoc();
2759 if (!EatIfPresent(lltok::lsquare))
2760 return false;
2761
2762 while (Lex.getKind() != lltok::rsquare) {
2763 // If this isn't the first operand bundle, we need a comma.
2764 if (!BundleList.empty() &&
2765 parseToken(lltok::comma, "expected ',' in input list"))
2766 return true;
2767
2768 std::string Tag;
2769 if (parseStringConstant(Tag))
2770 return true;
2771
2772 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2773 return true;
2774
2775 std::vector<Value *> Inputs;
2776 while (Lex.getKind() != lltok::rparen) {
2777 // If this isn't the first input, we need a comma.
2778 if (!Inputs.empty() &&
2779 parseToken(lltok::comma, "expected ',' in input list"))
2780 return true;
2781
2782 Type *Ty = nullptr;
2783 Value *Input = nullptr;
2784 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2785 return true;
2786 Inputs.push_back(Input);
2787 }
2788
2789 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2790
2791 Lex.Lex(); // Lex the ')'.
2792 }
2793
2794 if (BundleList.empty())
2795 return error(BeginLoc, "operand bundle set must not be empty");
2796
2797 Lex.Lex(); // Lex the ']'.
2798 return false;
2799 }
2800
2801 /// parseArgumentList - parse the argument list for a function type or function
2802 /// prototype.
2803 /// ::= '(' ArgTypeListI ')'
2804 /// ArgTypeListI
2805 /// ::= /*empty*/
2806 /// ::= '...'
2807 /// ::= ArgTypeList ',' '...'
2808 /// ::= ArgType (',' ArgType)*
2809 ///
parseArgumentList(SmallVectorImpl<ArgInfo> & ArgList,bool & IsVarArg)2810 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2811 bool &IsVarArg) {
2812 unsigned CurValID = 0;
2813 IsVarArg = false;
2814 assert(Lex.getKind() == lltok::lparen);
2815 Lex.Lex(); // eat the (.
2816
2817 if (Lex.getKind() == lltok::rparen) {
2818 // empty
2819 } else if (Lex.getKind() == lltok::dotdotdot) {
2820 IsVarArg = true;
2821 Lex.Lex();
2822 } else {
2823 LocTy TypeLoc = Lex.getLoc();
2824 Type *ArgTy = nullptr;
2825 AttrBuilder Attrs;
2826 std::string Name;
2827
2828 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2829 return true;
2830
2831 if (ArgTy->isVoidTy())
2832 return error(TypeLoc, "argument can not have void type");
2833
2834 if (Lex.getKind() == lltok::LocalVar) {
2835 Name = Lex.getStrVal();
2836 Lex.Lex();
2837 } else if (Lex.getKind() == lltok::LocalVarID) {
2838 if (Lex.getUIntVal() != CurValID)
2839 return error(TypeLoc, "argument expected to be numbered '%" +
2840 Twine(CurValID) + "'");
2841 ++CurValID;
2842 Lex.Lex();
2843 }
2844
2845 if (!FunctionType::isValidArgumentType(ArgTy))
2846 return error(TypeLoc, "invalid type for function argument");
2847
2848 ArgList.emplace_back(TypeLoc, ArgTy,
2849 AttributeSet::get(ArgTy->getContext(), Attrs),
2850 std::move(Name));
2851
2852 while (EatIfPresent(lltok::comma)) {
2853 // Handle ... at end of arg list.
2854 if (EatIfPresent(lltok::dotdotdot)) {
2855 IsVarArg = true;
2856 break;
2857 }
2858
2859 // Otherwise must be an argument type.
2860 TypeLoc = Lex.getLoc();
2861 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2862 return true;
2863
2864 if (ArgTy->isVoidTy())
2865 return error(TypeLoc, "argument can not have void type");
2866
2867 if (Lex.getKind() == lltok::LocalVar) {
2868 Name = Lex.getStrVal();
2869 Lex.Lex();
2870 } else {
2871 if (Lex.getKind() == lltok::LocalVarID) {
2872 if (Lex.getUIntVal() != CurValID)
2873 return error(TypeLoc, "argument expected to be numbered '%" +
2874 Twine(CurValID) + "'");
2875 Lex.Lex();
2876 }
2877 ++CurValID;
2878 Name = "";
2879 }
2880
2881 if (!ArgTy->isFirstClassType())
2882 return error(TypeLoc, "invalid type for function argument");
2883
2884 ArgList.emplace_back(TypeLoc, ArgTy,
2885 AttributeSet::get(ArgTy->getContext(), Attrs),
2886 std::move(Name));
2887 }
2888 }
2889
2890 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2891 }
2892
2893 /// parseFunctionType
2894 /// ::= Type ArgumentList OptionalAttrs
parseFunctionType(Type * & Result)2895 bool LLParser::parseFunctionType(Type *&Result) {
2896 assert(Lex.getKind() == lltok::lparen);
2897
2898 if (!FunctionType::isValidReturnType(Result))
2899 return tokError("invalid function return type");
2900
2901 SmallVector<ArgInfo, 8> ArgList;
2902 bool IsVarArg;
2903 if (parseArgumentList(ArgList, IsVarArg))
2904 return true;
2905
2906 // Reject names on the arguments lists.
2907 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2908 if (!ArgList[i].Name.empty())
2909 return error(ArgList[i].Loc, "argument name invalid in function type");
2910 if (ArgList[i].Attrs.hasAttributes())
2911 return error(ArgList[i].Loc,
2912 "argument attributes invalid in function type");
2913 }
2914
2915 SmallVector<Type*, 16> ArgListTy;
2916 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2917 ArgListTy.push_back(ArgList[i].Ty);
2918
2919 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2920 return false;
2921 }
2922
2923 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2924 /// other structs.
parseAnonStructType(Type * & Result,bool Packed)2925 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2926 SmallVector<Type*, 8> Elts;
2927 if (parseStructBody(Elts))
2928 return true;
2929
2930 Result = StructType::get(Context, Elts, Packed);
2931 return false;
2932 }
2933
2934 /// parseStructDefinition - parse a struct in a 'type' definition.
parseStructDefinition(SMLoc TypeLoc,StringRef Name,std::pair<Type *,LocTy> & Entry,Type * & ResultTy)2935 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2936 std::pair<Type *, LocTy> &Entry,
2937 Type *&ResultTy) {
2938 // If the type was already defined, diagnose the redefinition.
2939 if (Entry.first && !Entry.second.isValid())
2940 return error(TypeLoc, "redefinition of type");
2941
2942 // If we have opaque, just return without filling in the definition for the
2943 // struct. This counts as a definition as far as the .ll file goes.
2944 if (EatIfPresent(lltok::kw_opaque)) {
2945 // This type is being defined, so clear the location to indicate this.
2946 Entry.second = SMLoc();
2947
2948 // If this type number has never been uttered, create it.
2949 if (!Entry.first)
2950 Entry.first = StructType::create(Context, Name);
2951 ResultTy = Entry.first;
2952 return false;
2953 }
2954
2955 // If the type starts with '<', then it is either a packed struct or a vector.
2956 bool isPacked = EatIfPresent(lltok::less);
2957
2958 // If we don't have a struct, then we have a random type alias, which we
2959 // accept for compatibility with old files. These types are not allowed to be
2960 // forward referenced and not allowed to be recursive.
2961 if (Lex.getKind() != lltok::lbrace) {
2962 if (Entry.first)
2963 return error(TypeLoc, "forward references to non-struct type");
2964
2965 ResultTy = nullptr;
2966 if (isPacked)
2967 return parseArrayVectorType(ResultTy, true);
2968 return parseType(ResultTy);
2969 }
2970
2971 // This type is being defined, so clear the location to indicate this.
2972 Entry.second = SMLoc();
2973
2974 // If this type number has never been uttered, create it.
2975 if (!Entry.first)
2976 Entry.first = StructType::create(Context, Name);
2977
2978 StructType *STy = cast<StructType>(Entry.first);
2979
2980 SmallVector<Type*, 8> Body;
2981 if (parseStructBody(Body) ||
2982 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2983 return true;
2984
2985 STy->setBody(Body, isPacked);
2986 ResultTy = STy;
2987 return false;
2988 }
2989
2990 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2991 /// StructType
2992 /// ::= '{' '}'
2993 /// ::= '{' Type (',' Type)* '}'
2994 /// ::= '<' '{' '}' '>'
2995 /// ::= '<' '{' Type (',' Type)* '}' '>'
parseStructBody(SmallVectorImpl<Type * > & Body)2996 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2997 assert(Lex.getKind() == lltok::lbrace);
2998 Lex.Lex(); // Consume the '{'
2999
3000 // Handle the empty struct.
3001 if (EatIfPresent(lltok::rbrace))
3002 return false;
3003
3004 LocTy EltTyLoc = Lex.getLoc();
3005 Type *Ty = nullptr;
3006 if (parseType(Ty))
3007 return true;
3008 Body.push_back(Ty);
3009
3010 if (!StructType::isValidElementType(Ty))
3011 return error(EltTyLoc, "invalid element type for struct");
3012
3013 while (EatIfPresent(lltok::comma)) {
3014 EltTyLoc = Lex.getLoc();
3015 if (parseType(Ty))
3016 return true;
3017
3018 if (!StructType::isValidElementType(Ty))
3019 return error(EltTyLoc, "invalid element type for struct");
3020
3021 Body.push_back(Ty);
3022 }
3023
3024 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3025 }
3026
3027 /// parseArrayVectorType - parse an array or vector type, assuming the first
3028 /// token has already been consumed.
3029 /// Type
3030 /// ::= '[' APSINTVAL 'x' Types ']'
3031 /// ::= '<' APSINTVAL 'x' Types '>'
3032 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
parseArrayVectorType(Type * & Result,bool IsVector)3033 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3034 bool Scalable = false;
3035
3036 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3037 Lex.Lex(); // consume the 'vscale'
3038 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3039 return true;
3040
3041 Scalable = true;
3042 }
3043
3044 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3045 Lex.getAPSIntVal().getBitWidth() > 64)
3046 return tokError("expected number in address space");
3047
3048 LocTy SizeLoc = Lex.getLoc();
3049 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3050 Lex.Lex();
3051
3052 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3053 return true;
3054
3055 LocTy TypeLoc = Lex.getLoc();
3056 Type *EltTy = nullptr;
3057 if (parseType(EltTy))
3058 return true;
3059
3060 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3061 "expected end of sequential type"))
3062 return true;
3063
3064 if (IsVector) {
3065 if (Size == 0)
3066 return error(SizeLoc, "zero element vector is illegal");
3067 if ((unsigned)Size != Size)
3068 return error(SizeLoc, "size too large for vector");
3069 if (!VectorType::isValidElementType(EltTy))
3070 return error(TypeLoc, "invalid vector element type");
3071 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3072 } else {
3073 if (!ArrayType::isValidElementType(EltTy))
3074 return error(TypeLoc, "invalid array element type");
3075 Result = ArrayType::get(EltTy, Size);
3076 }
3077 return false;
3078 }
3079
3080 //===----------------------------------------------------------------------===//
3081 // Function Semantic Analysis.
3082 //===----------------------------------------------------------------------===//
3083
PerFunctionState(LLParser & p,Function & f,int functionNumber)3084 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3085 int functionNumber)
3086 : P(p), F(f), FunctionNumber(functionNumber) {
3087
3088 // Insert unnamed arguments into the NumberedVals list.
3089 for (Argument &A : F.args())
3090 if (!A.hasName())
3091 NumberedVals.push_back(&A);
3092 }
3093
~PerFunctionState()3094 LLParser::PerFunctionState::~PerFunctionState() {
3095 // If there were any forward referenced non-basicblock values, delete them.
3096
3097 for (const auto &P : ForwardRefVals) {
3098 if (isa<BasicBlock>(P.second.first))
3099 continue;
3100 P.second.first->replaceAllUsesWith(
3101 UndefValue::get(P.second.first->getType()));
3102 P.second.first->deleteValue();
3103 }
3104
3105 for (const auto &P : ForwardRefValIDs) {
3106 if (isa<BasicBlock>(P.second.first))
3107 continue;
3108 P.second.first->replaceAllUsesWith(
3109 UndefValue::get(P.second.first->getType()));
3110 P.second.first->deleteValue();
3111 }
3112 }
3113
finishFunction()3114 bool LLParser::PerFunctionState::finishFunction() {
3115 if (!ForwardRefVals.empty())
3116 return P.error(ForwardRefVals.begin()->second.second,
3117 "use of undefined value '%" + ForwardRefVals.begin()->first +
3118 "'");
3119 if (!ForwardRefValIDs.empty())
3120 return P.error(ForwardRefValIDs.begin()->second.second,
3121 "use of undefined value '%" +
3122 Twine(ForwardRefValIDs.begin()->first) + "'");
3123 return false;
3124 }
3125
3126 /// getVal - Get a value with the specified name or ID, creating a
3127 /// forward reference record if needed. This can return null if the value
3128 /// exists but does not have the right type.
getVal(const std::string & Name,Type * Ty,LocTy Loc,bool IsCall)3129 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3130 LocTy Loc, bool IsCall) {
3131 // Look this name up in the normal function symbol table.
3132 Value *Val = F.getValueSymbolTable()->lookup(Name);
3133
3134 // If this is a forward reference for the value, see if we already created a
3135 // forward ref record.
3136 if (!Val) {
3137 auto I = ForwardRefVals.find(Name);
3138 if (I != ForwardRefVals.end())
3139 Val = I->second.first;
3140 }
3141
3142 // If we have the value in the symbol table or fwd-ref table, return it.
3143 if (Val)
3144 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
3145
3146 // Don't make placeholders with invalid type.
3147 if (!Ty->isFirstClassType()) {
3148 P.error(Loc, "invalid use of a non-first-class type");
3149 return nullptr;
3150 }
3151
3152 // Otherwise, create a new forward reference for this value and remember it.
3153 Value *FwdVal;
3154 if (Ty->isLabelTy()) {
3155 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3156 } else {
3157 FwdVal = new Argument(Ty, Name);
3158 }
3159
3160 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3161 return FwdVal;
3162 }
3163
getVal(unsigned ID,Type * Ty,LocTy Loc,bool IsCall)3164 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc,
3165 bool IsCall) {
3166 // Look this name up in the normal function symbol table.
3167 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3168
3169 // If this is a forward reference for the value, see if we already created a
3170 // forward ref record.
3171 if (!Val) {
3172 auto I = ForwardRefValIDs.find(ID);
3173 if (I != ForwardRefValIDs.end())
3174 Val = I->second.first;
3175 }
3176
3177 // If we have the value in the symbol table or fwd-ref table, return it.
3178 if (Val)
3179 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
3180
3181 if (!Ty->isFirstClassType()) {
3182 P.error(Loc, "invalid use of a non-first-class type");
3183 return nullptr;
3184 }
3185
3186 // Otherwise, create a new forward reference for this value and remember it.
3187 Value *FwdVal;
3188 if (Ty->isLabelTy()) {
3189 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3190 } else {
3191 FwdVal = new Argument(Ty);
3192 }
3193
3194 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3195 return FwdVal;
3196 }
3197
3198 /// setInstName - After an instruction is parsed and inserted into its
3199 /// basic block, this installs its name.
setInstName(int NameID,const std::string & NameStr,LocTy NameLoc,Instruction * Inst)3200 bool LLParser::PerFunctionState::setInstName(int NameID,
3201 const std::string &NameStr,
3202 LocTy NameLoc, Instruction *Inst) {
3203 // If this instruction has void type, it cannot have a name or ID specified.
3204 if (Inst->getType()->isVoidTy()) {
3205 if (NameID != -1 || !NameStr.empty())
3206 return P.error(NameLoc, "instructions returning void cannot have a name");
3207 return false;
3208 }
3209
3210 // If this was a numbered instruction, verify that the instruction is the
3211 // expected value and resolve any forward references.
3212 if (NameStr.empty()) {
3213 // If neither a name nor an ID was specified, just use the next ID.
3214 if (NameID == -1)
3215 NameID = NumberedVals.size();
3216
3217 if (unsigned(NameID) != NumberedVals.size())
3218 return P.error(NameLoc, "instruction expected to be numbered '%" +
3219 Twine(NumberedVals.size()) + "'");
3220
3221 auto FI = ForwardRefValIDs.find(NameID);
3222 if (FI != ForwardRefValIDs.end()) {
3223 Value *Sentinel = FI->second.first;
3224 if (Sentinel->getType() != Inst->getType())
3225 return P.error(NameLoc, "instruction forward referenced with type '" +
3226 getTypeString(FI->second.first->getType()) +
3227 "'");
3228
3229 Sentinel->replaceAllUsesWith(Inst);
3230 Sentinel->deleteValue();
3231 ForwardRefValIDs.erase(FI);
3232 }
3233
3234 NumberedVals.push_back(Inst);
3235 return false;
3236 }
3237
3238 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3239 auto FI = ForwardRefVals.find(NameStr);
3240 if (FI != ForwardRefVals.end()) {
3241 Value *Sentinel = FI->second.first;
3242 if (Sentinel->getType() != Inst->getType())
3243 return P.error(NameLoc, "instruction forward referenced with type '" +
3244 getTypeString(FI->second.first->getType()) +
3245 "'");
3246
3247 Sentinel->replaceAllUsesWith(Inst);
3248 Sentinel->deleteValue();
3249 ForwardRefVals.erase(FI);
3250 }
3251
3252 // Set the name on the instruction.
3253 Inst->setName(NameStr);
3254
3255 if (Inst->getName() != NameStr)
3256 return P.error(NameLoc, "multiple definition of local value named '" +
3257 NameStr + "'");
3258 return false;
3259 }
3260
3261 /// getBB - Get a basic block with the specified name or ID, creating a
3262 /// forward reference record if needed.
getBB(const std::string & Name,LocTy Loc)3263 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3264 LocTy Loc) {
3265 return dyn_cast_or_null<BasicBlock>(
3266 getVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3267 }
3268
getBB(unsigned ID,LocTy Loc)3269 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3270 return dyn_cast_or_null<BasicBlock>(
3271 getVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3272 }
3273
3274 /// defineBB - Define the specified basic block, which is either named or
3275 /// unnamed. If there is an error, this returns null otherwise it returns
3276 /// the block being defined.
defineBB(const std::string & Name,int NameID,LocTy Loc)3277 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3278 int NameID, LocTy Loc) {
3279 BasicBlock *BB;
3280 if (Name.empty()) {
3281 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3282 P.error(Loc, "label expected to be numbered '" +
3283 Twine(NumberedVals.size()) + "'");
3284 return nullptr;
3285 }
3286 BB = getBB(NumberedVals.size(), Loc);
3287 if (!BB) {
3288 P.error(Loc, "unable to create block numbered '" +
3289 Twine(NumberedVals.size()) + "'");
3290 return nullptr;
3291 }
3292 } else {
3293 BB = getBB(Name, Loc);
3294 if (!BB) {
3295 P.error(Loc, "unable to create block named '" + Name + "'");
3296 return nullptr;
3297 }
3298 }
3299
3300 // Move the block to the end of the function. Forward ref'd blocks are
3301 // inserted wherever they happen to be referenced.
3302 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3303
3304 // Remove the block from forward ref sets.
3305 if (Name.empty()) {
3306 ForwardRefValIDs.erase(NumberedVals.size());
3307 NumberedVals.push_back(BB);
3308 } else {
3309 // BB forward references are already in the function symbol table.
3310 ForwardRefVals.erase(Name);
3311 }
3312
3313 return BB;
3314 }
3315
3316 //===----------------------------------------------------------------------===//
3317 // Constants.
3318 //===----------------------------------------------------------------------===//
3319
3320 /// parseValID - parse an abstract value that doesn't necessarily have a
3321 /// type implied. For example, if we parse "4" we don't know what integer type
3322 /// it has. The value will later be combined with its type and checked for
3323 /// sanity. PFS is used to convert function-local operands of metadata (since
3324 /// metadata operands are not just parsed here but also converted to values).
3325 /// PFS can be null when we are not parsing metadata values inside a function.
parseValID(ValID & ID,PerFunctionState * PFS)3326 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS) {
3327 ID.Loc = Lex.getLoc();
3328 switch (Lex.getKind()) {
3329 default:
3330 return tokError("expected value token");
3331 case lltok::GlobalID: // @42
3332 ID.UIntVal = Lex.getUIntVal();
3333 ID.Kind = ValID::t_GlobalID;
3334 break;
3335 case lltok::GlobalVar: // @foo
3336 ID.StrVal = Lex.getStrVal();
3337 ID.Kind = ValID::t_GlobalName;
3338 break;
3339 case lltok::LocalVarID: // %42
3340 ID.UIntVal = Lex.getUIntVal();
3341 ID.Kind = ValID::t_LocalID;
3342 break;
3343 case lltok::LocalVar: // %foo
3344 ID.StrVal = Lex.getStrVal();
3345 ID.Kind = ValID::t_LocalName;
3346 break;
3347 case lltok::APSInt:
3348 ID.APSIntVal = Lex.getAPSIntVal();
3349 ID.Kind = ValID::t_APSInt;
3350 break;
3351 case lltok::APFloat:
3352 ID.APFloatVal = Lex.getAPFloatVal();
3353 ID.Kind = ValID::t_APFloat;
3354 break;
3355 case lltok::kw_true:
3356 ID.ConstantVal = ConstantInt::getTrue(Context);
3357 ID.Kind = ValID::t_Constant;
3358 break;
3359 case lltok::kw_false:
3360 ID.ConstantVal = ConstantInt::getFalse(Context);
3361 ID.Kind = ValID::t_Constant;
3362 break;
3363 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3364 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3365 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3366 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3367 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3368
3369 case lltok::lbrace: {
3370 // ValID ::= '{' ConstVector '}'
3371 Lex.Lex();
3372 SmallVector<Constant*, 16> Elts;
3373 if (parseGlobalValueVector(Elts) ||
3374 parseToken(lltok::rbrace, "expected end of struct constant"))
3375 return true;
3376
3377 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3378 ID.UIntVal = Elts.size();
3379 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3380 Elts.size() * sizeof(Elts[0]));
3381 ID.Kind = ValID::t_ConstantStruct;
3382 return false;
3383 }
3384 case lltok::less: {
3385 // ValID ::= '<' ConstVector '>' --> Vector.
3386 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3387 Lex.Lex();
3388 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3389
3390 SmallVector<Constant*, 16> Elts;
3391 LocTy FirstEltLoc = Lex.getLoc();
3392 if (parseGlobalValueVector(Elts) ||
3393 (isPackedStruct &&
3394 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3395 parseToken(lltok::greater, "expected end of constant"))
3396 return true;
3397
3398 if (isPackedStruct) {
3399 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3400 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3401 Elts.size() * sizeof(Elts[0]));
3402 ID.UIntVal = Elts.size();
3403 ID.Kind = ValID::t_PackedConstantStruct;
3404 return false;
3405 }
3406
3407 if (Elts.empty())
3408 return error(ID.Loc, "constant vector must not be empty");
3409
3410 if (!Elts[0]->getType()->isIntegerTy() &&
3411 !Elts[0]->getType()->isFloatingPointTy() &&
3412 !Elts[0]->getType()->isPointerTy())
3413 return error(
3414 FirstEltLoc,
3415 "vector elements must have integer, pointer or floating point type");
3416
3417 // Verify that all the vector elements have the same type.
3418 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3419 if (Elts[i]->getType() != Elts[0]->getType())
3420 return error(FirstEltLoc, "vector element #" + Twine(i) +
3421 " is not of type '" +
3422 getTypeString(Elts[0]->getType()));
3423
3424 ID.ConstantVal = ConstantVector::get(Elts);
3425 ID.Kind = ValID::t_Constant;
3426 return false;
3427 }
3428 case lltok::lsquare: { // Array Constant
3429 Lex.Lex();
3430 SmallVector<Constant*, 16> Elts;
3431 LocTy FirstEltLoc = Lex.getLoc();
3432 if (parseGlobalValueVector(Elts) ||
3433 parseToken(lltok::rsquare, "expected end of array constant"))
3434 return true;
3435
3436 // Handle empty element.
3437 if (Elts.empty()) {
3438 // Use undef instead of an array because it's inconvenient to determine
3439 // the element type at this point, there being no elements to examine.
3440 ID.Kind = ValID::t_EmptyArray;
3441 return false;
3442 }
3443
3444 if (!Elts[0]->getType()->isFirstClassType())
3445 return error(FirstEltLoc, "invalid array element type: " +
3446 getTypeString(Elts[0]->getType()));
3447
3448 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3449
3450 // Verify all elements are correct type!
3451 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3452 if (Elts[i]->getType() != Elts[0]->getType())
3453 return error(FirstEltLoc, "array element #" + Twine(i) +
3454 " is not of type '" +
3455 getTypeString(Elts[0]->getType()));
3456 }
3457
3458 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3459 ID.Kind = ValID::t_Constant;
3460 return false;
3461 }
3462 case lltok::kw_c: // c "foo"
3463 Lex.Lex();
3464 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3465 false);
3466 if (parseToken(lltok::StringConstant, "expected string"))
3467 return true;
3468 ID.Kind = ValID::t_Constant;
3469 return false;
3470
3471 case lltok::kw_asm: {
3472 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3473 // STRINGCONSTANT
3474 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3475 Lex.Lex();
3476 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3477 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3478 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3479 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3480 parseStringConstant(ID.StrVal) ||
3481 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3482 parseToken(lltok::StringConstant, "expected constraint string"))
3483 return true;
3484 ID.StrVal2 = Lex.getStrVal();
3485 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3486 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3487 ID.Kind = ValID::t_InlineAsm;
3488 return false;
3489 }
3490
3491 case lltok::kw_blockaddress: {
3492 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3493 Lex.Lex();
3494
3495 ValID Fn, Label;
3496
3497 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3498 parseValID(Fn) ||
3499 parseToken(lltok::comma,
3500 "expected comma in block address expression") ||
3501 parseValID(Label) ||
3502 parseToken(lltok::rparen, "expected ')' in block address expression"))
3503 return true;
3504
3505 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3506 return error(Fn.Loc, "expected function name in blockaddress");
3507 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3508 return error(Label.Loc, "expected basic block name in blockaddress");
3509
3510 // Try to find the function (but skip it if it's forward-referenced).
3511 GlobalValue *GV = nullptr;
3512 if (Fn.Kind == ValID::t_GlobalID) {
3513 if (Fn.UIntVal < NumberedVals.size())
3514 GV = NumberedVals[Fn.UIntVal];
3515 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3516 GV = M->getNamedValue(Fn.StrVal);
3517 }
3518 Function *F = nullptr;
3519 if (GV) {
3520 // Confirm that it's actually a function with a definition.
3521 if (!isa<Function>(GV))
3522 return error(Fn.Loc, "expected function name in blockaddress");
3523 F = cast<Function>(GV);
3524 if (F->isDeclaration())
3525 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3526 }
3527
3528 if (!F) {
3529 // Make a global variable as a placeholder for this reference.
3530 GlobalValue *&FwdRef =
3531 ForwardRefBlockAddresses.insert(std::make_pair(
3532 std::move(Fn),
3533 std::map<ValID, GlobalValue *>()))
3534 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3535 .first->second;
3536 if (!FwdRef)
3537 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3538 GlobalValue::InternalLinkage, nullptr, "");
3539 ID.ConstantVal = FwdRef;
3540 ID.Kind = ValID::t_Constant;
3541 return false;
3542 }
3543
3544 // We found the function; now find the basic block. Don't use PFS, since we
3545 // might be inside a constant expression.
3546 BasicBlock *BB;
3547 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3548 if (Label.Kind == ValID::t_LocalID)
3549 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3550 else
3551 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3552 if (!BB)
3553 return error(Label.Loc, "referenced value is not a basic block");
3554 } else {
3555 if (Label.Kind == ValID::t_LocalID)
3556 return error(Label.Loc, "cannot take address of numeric label after "
3557 "the function is defined");
3558 BB = dyn_cast_or_null<BasicBlock>(
3559 F->getValueSymbolTable()->lookup(Label.StrVal));
3560 if (!BB)
3561 return error(Label.Loc, "referenced value is not a basic block");
3562 }
3563
3564 ID.ConstantVal = BlockAddress::get(F, BB);
3565 ID.Kind = ValID::t_Constant;
3566 return false;
3567 }
3568
3569 case lltok::kw_dso_local_equivalent: {
3570 // ValID ::= 'dso_local_equivalent' @foo
3571 Lex.Lex();
3572
3573 ValID Fn;
3574
3575 if (parseValID(Fn))
3576 return true;
3577
3578 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3579 return error(Fn.Loc,
3580 "expected global value name in dso_local_equivalent");
3581
3582 // Try to find the function (but skip it if it's forward-referenced).
3583 GlobalValue *GV = nullptr;
3584 if (Fn.Kind == ValID::t_GlobalID) {
3585 if (Fn.UIntVal < NumberedVals.size())
3586 GV = NumberedVals[Fn.UIntVal];
3587 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3588 GV = M->getNamedValue(Fn.StrVal);
3589 }
3590
3591 assert(GV && "Could not find a corresponding global variable");
3592
3593 if (!GV->getValueType()->isFunctionTy())
3594 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3595 "in dso_local_equivalent");
3596
3597 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3598 ID.Kind = ValID::t_Constant;
3599 return false;
3600 }
3601
3602 case lltok::kw_trunc:
3603 case lltok::kw_zext:
3604 case lltok::kw_sext:
3605 case lltok::kw_fptrunc:
3606 case lltok::kw_fpext:
3607 case lltok::kw_bitcast:
3608 case lltok::kw_addrspacecast:
3609 case lltok::kw_uitofp:
3610 case lltok::kw_sitofp:
3611 case lltok::kw_fptoui:
3612 case lltok::kw_fptosi:
3613 case lltok::kw_inttoptr:
3614 case lltok::kw_ptrtoint: {
3615 unsigned Opc = Lex.getUIntVal();
3616 Type *DestTy = nullptr;
3617 Constant *SrcVal;
3618 Lex.Lex();
3619 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3620 parseGlobalTypeAndValue(SrcVal) ||
3621 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3622 parseType(DestTy) ||
3623 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3624 return true;
3625 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3626 return error(ID.Loc, "invalid cast opcode for cast from '" +
3627 getTypeString(SrcVal->getType()) + "' to '" +
3628 getTypeString(DestTy) + "'");
3629 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3630 SrcVal, DestTy);
3631 ID.Kind = ValID::t_Constant;
3632 return false;
3633 }
3634 case lltok::kw_extractvalue: {
3635 Lex.Lex();
3636 Constant *Val;
3637 SmallVector<unsigned, 4> Indices;
3638 if (parseToken(lltok::lparen,
3639 "expected '(' in extractvalue constantexpr") ||
3640 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) ||
3641 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3642 return true;
3643
3644 if (!Val->getType()->isAggregateType())
3645 return error(ID.Loc, "extractvalue operand must be aggregate type");
3646 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3647 return error(ID.Loc, "invalid indices for extractvalue");
3648 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3649 ID.Kind = ValID::t_Constant;
3650 return false;
3651 }
3652 case lltok::kw_insertvalue: {
3653 Lex.Lex();
3654 Constant *Val0, *Val1;
3655 SmallVector<unsigned, 4> Indices;
3656 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") ||
3657 parseGlobalTypeAndValue(Val0) ||
3658 parseToken(lltok::comma,
3659 "expected comma in insertvalue constantexpr") ||
3660 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) ||
3661 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3662 return true;
3663 if (!Val0->getType()->isAggregateType())
3664 return error(ID.Loc, "insertvalue operand must be aggregate type");
3665 Type *IndexedType =
3666 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3667 if (!IndexedType)
3668 return error(ID.Loc, "invalid indices for insertvalue");
3669 if (IndexedType != Val1->getType())
3670 return error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3671 getTypeString(Val1->getType()) +
3672 "' instead of '" + getTypeString(IndexedType) +
3673 "'");
3674 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3675 ID.Kind = ValID::t_Constant;
3676 return false;
3677 }
3678 case lltok::kw_icmp:
3679 case lltok::kw_fcmp: {
3680 unsigned PredVal, Opc = Lex.getUIntVal();
3681 Constant *Val0, *Val1;
3682 Lex.Lex();
3683 if (parseCmpPredicate(PredVal, Opc) ||
3684 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3685 parseGlobalTypeAndValue(Val0) ||
3686 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3687 parseGlobalTypeAndValue(Val1) ||
3688 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3689 return true;
3690
3691 if (Val0->getType() != Val1->getType())
3692 return error(ID.Loc, "compare operands must have the same type");
3693
3694 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3695
3696 if (Opc == Instruction::FCmp) {
3697 if (!Val0->getType()->isFPOrFPVectorTy())
3698 return error(ID.Loc, "fcmp requires floating point operands");
3699 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3700 } else {
3701 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3702 if (!Val0->getType()->isIntOrIntVectorTy() &&
3703 !Val0->getType()->isPtrOrPtrVectorTy())
3704 return error(ID.Loc, "icmp requires pointer or integer operands");
3705 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3706 }
3707 ID.Kind = ValID::t_Constant;
3708 return false;
3709 }
3710
3711 // Unary Operators.
3712 case lltok::kw_fneg: {
3713 unsigned Opc = Lex.getUIntVal();
3714 Constant *Val;
3715 Lex.Lex();
3716 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3717 parseGlobalTypeAndValue(Val) ||
3718 parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3719 return true;
3720
3721 // Check that the type is valid for the operator.
3722 switch (Opc) {
3723 case Instruction::FNeg:
3724 if (!Val->getType()->isFPOrFPVectorTy())
3725 return error(ID.Loc, "constexpr requires fp operands");
3726 break;
3727 default: llvm_unreachable("Unknown unary operator!");
3728 }
3729 unsigned Flags = 0;
3730 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3731 ID.ConstantVal = C;
3732 ID.Kind = ValID::t_Constant;
3733 return false;
3734 }
3735 // Binary Operators.
3736 case lltok::kw_add:
3737 case lltok::kw_fadd:
3738 case lltok::kw_sub:
3739 case lltok::kw_fsub:
3740 case lltok::kw_mul:
3741 case lltok::kw_fmul:
3742 case lltok::kw_udiv:
3743 case lltok::kw_sdiv:
3744 case lltok::kw_fdiv:
3745 case lltok::kw_urem:
3746 case lltok::kw_srem:
3747 case lltok::kw_frem:
3748 case lltok::kw_shl:
3749 case lltok::kw_lshr:
3750 case lltok::kw_ashr: {
3751 bool NUW = false;
3752 bool NSW = false;
3753 bool Exact = false;
3754 unsigned Opc = Lex.getUIntVal();
3755 Constant *Val0, *Val1;
3756 Lex.Lex();
3757 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3758 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3759 if (EatIfPresent(lltok::kw_nuw))
3760 NUW = true;
3761 if (EatIfPresent(lltok::kw_nsw)) {
3762 NSW = true;
3763 if (EatIfPresent(lltok::kw_nuw))
3764 NUW = true;
3765 }
3766 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3767 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3768 if (EatIfPresent(lltok::kw_exact))
3769 Exact = true;
3770 }
3771 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3772 parseGlobalTypeAndValue(Val0) ||
3773 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3774 parseGlobalTypeAndValue(Val1) ||
3775 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3776 return true;
3777 if (Val0->getType() != Val1->getType())
3778 return error(ID.Loc, "operands of constexpr must have same type");
3779 // Check that the type is valid for the operator.
3780 switch (Opc) {
3781 case Instruction::Add:
3782 case Instruction::Sub:
3783 case Instruction::Mul:
3784 case Instruction::UDiv:
3785 case Instruction::SDiv:
3786 case Instruction::URem:
3787 case Instruction::SRem:
3788 case Instruction::Shl:
3789 case Instruction::AShr:
3790 case Instruction::LShr:
3791 if (!Val0->getType()->isIntOrIntVectorTy())
3792 return error(ID.Loc, "constexpr requires integer operands");
3793 break;
3794 case Instruction::FAdd:
3795 case Instruction::FSub:
3796 case Instruction::FMul:
3797 case Instruction::FDiv:
3798 case Instruction::FRem:
3799 if (!Val0->getType()->isFPOrFPVectorTy())
3800 return error(ID.Loc, "constexpr requires fp operands");
3801 break;
3802 default: llvm_unreachable("Unknown binary operator!");
3803 }
3804 unsigned Flags = 0;
3805 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3806 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3807 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3808 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3809 ID.ConstantVal = C;
3810 ID.Kind = ValID::t_Constant;
3811 return false;
3812 }
3813
3814 // Logical Operations
3815 case lltok::kw_and:
3816 case lltok::kw_or:
3817 case lltok::kw_xor: {
3818 unsigned Opc = Lex.getUIntVal();
3819 Constant *Val0, *Val1;
3820 Lex.Lex();
3821 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3822 parseGlobalTypeAndValue(Val0) ||
3823 parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3824 parseGlobalTypeAndValue(Val1) ||
3825 parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3826 return true;
3827 if (Val0->getType() != Val1->getType())
3828 return error(ID.Loc, "operands of constexpr must have same type");
3829 if (!Val0->getType()->isIntOrIntVectorTy())
3830 return error(ID.Loc,
3831 "constexpr requires integer or integer vector operands");
3832 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3833 ID.Kind = ValID::t_Constant;
3834 return false;
3835 }
3836
3837 case lltok::kw_getelementptr:
3838 case lltok::kw_shufflevector:
3839 case lltok::kw_insertelement:
3840 case lltok::kw_extractelement:
3841 case lltok::kw_select: {
3842 unsigned Opc = Lex.getUIntVal();
3843 SmallVector<Constant*, 16> Elts;
3844 bool InBounds = false;
3845 Type *Ty;
3846 Lex.Lex();
3847
3848 if (Opc == Instruction::GetElementPtr)
3849 InBounds = EatIfPresent(lltok::kw_inbounds);
3850
3851 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3852 return true;
3853
3854 LocTy ExplicitTypeLoc = Lex.getLoc();
3855 if (Opc == Instruction::GetElementPtr) {
3856 if (parseType(Ty) ||
3857 parseToken(lltok::comma, "expected comma after getelementptr's type"))
3858 return true;
3859 }
3860
3861 Optional<unsigned> InRangeOp;
3862 if (parseGlobalValueVector(
3863 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3864 parseToken(lltok::rparen, "expected ')' in constantexpr"))
3865 return true;
3866
3867 if (Opc == Instruction::GetElementPtr) {
3868 if (Elts.size() == 0 ||
3869 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3870 return error(ID.Loc, "base of getelementptr must be a pointer");
3871
3872 Type *BaseType = Elts[0]->getType();
3873 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3874 if (Ty != BasePointerType->getElementType()) {
3875 return error(
3876 ExplicitTypeLoc,
3877 typeComparisonErrorMessage(
3878 "explicit pointee type doesn't match operand's pointee type",
3879 Ty, BasePointerType->getElementType()));
3880 }
3881
3882 unsigned GEPWidth =
3883 BaseType->isVectorTy()
3884 ? cast<FixedVectorType>(BaseType)->getNumElements()
3885 : 0;
3886
3887 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3888 for (Constant *Val : Indices) {
3889 Type *ValTy = Val->getType();
3890 if (!ValTy->isIntOrIntVectorTy())
3891 return error(ID.Loc, "getelementptr index must be an integer");
3892 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3893 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3894 if (GEPWidth && (ValNumEl != GEPWidth))
3895 return error(
3896 ID.Loc,
3897 "getelementptr vector index has a wrong number of elements");
3898 // GEPWidth may have been unknown because the base is a scalar,
3899 // but it is known now.
3900 GEPWidth = ValNumEl;
3901 }
3902 }
3903
3904 SmallPtrSet<Type*, 4> Visited;
3905 if (!Indices.empty() && !Ty->isSized(&Visited))
3906 return error(ID.Loc, "base element of getelementptr must be sized");
3907
3908 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3909 return error(ID.Loc, "invalid getelementptr indices");
3910
3911 if (InRangeOp) {
3912 if (*InRangeOp == 0)
3913 return error(ID.Loc,
3914 "inrange keyword may not appear on pointer operand");
3915 --*InRangeOp;
3916 }
3917
3918 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3919 InBounds, InRangeOp);
3920 } else if (Opc == Instruction::Select) {
3921 if (Elts.size() != 3)
3922 return error(ID.Loc, "expected three operands to select");
3923 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3924 Elts[2]))
3925 return error(ID.Loc, Reason);
3926 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3927 } else if (Opc == Instruction::ShuffleVector) {
3928 if (Elts.size() != 3)
3929 return error(ID.Loc, "expected three operands to shufflevector");
3930 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3931 return error(ID.Loc, "invalid operands to shufflevector");
3932 SmallVector<int, 16> Mask;
3933 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3934 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3935 } else if (Opc == Instruction::ExtractElement) {
3936 if (Elts.size() != 2)
3937 return error(ID.Loc, "expected two operands to extractelement");
3938 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3939 return error(ID.Loc, "invalid extractelement operands");
3940 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3941 } else {
3942 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3943 if (Elts.size() != 3)
3944 return error(ID.Loc, "expected three operands to insertelement");
3945 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3946 return error(ID.Loc, "invalid insertelement operands");
3947 ID.ConstantVal =
3948 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3949 }
3950
3951 ID.Kind = ValID::t_Constant;
3952 return false;
3953 }
3954 }
3955
3956 Lex.Lex();
3957 return false;
3958 }
3959
3960 /// parseGlobalValue - parse a global value with the specified type.
parseGlobalValue(Type * Ty,Constant * & C)3961 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3962 C = nullptr;
3963 ValID ID;
3964 Value *V = nullptr;
3965 bool Parsed = parseValID(ID) ||
3966 convertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3967 if (V && !(C = dyn_cast<Constant>(V)))
3968 return error(ID.Loc, "global values must be constants");
3969 return Parsed;
3970 }
3971
parseGlobalTypeAndValue(Constant * & V)3972 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3973 Type *Ty = nullptr;
3974 return parseType(Ty) || parseGlobalValue(Ty, V);
3975 }
3976
parseOptionalComdat(StringRef GlobalName,Comdat * & C)3977 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3978 C = nullptr;
3979
3980 LocTy KwLoc = Lex.getLoc();
3981 if (!EatIfPresent(lltok::kw_comdat))
3982 return false;
3983
3984 if (EatIfPresent(lltok::lparen)) {
3985 if (Lex.getKind() != lltok::ComdatVar)
3986 return tokError("expected comdat variable");
3987 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3988 Lex.Lex();
3989 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3990 return true;
3991 } else {
3992 if (GlobalName.empty())
3993 return tokError("comdat cannot be unnamed");
3994 C = getComdat(std::string(GlobalName), KwLoc);
3995 }
3996
3997 return false;
3998 }
3999
4000 /// parseGlobalValueVector
4001 /// ::= /*empty*/
4002 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
parseGlobalValueVector(SmallVectorImpl<Constant * > & Elts,Optional<unsigned> * InRangeOp)4003 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
4004 Optional<unsigned> *InRangeOp) {
4005 // Empty list.
4006 if (Lex.getKind() == lltok::rbrace ||
4007 Lex.getKind() == lltok::rsquare ||
4008 Lex.getKind() == lltok::greater ||
4009 Lex.getKind() == lltok::rparen)
4010 return false;
4011
4012 do {
4013 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
4014 *InRangeOp = Elts.size();
4015
4016 Constant *C;
4017 if (parseGlobalTypeAndValue(C))
4018 return true;
4019 Elts.push_back(C);
4020 } while (EatIfPresent(lltok::comma));
4021
4022 return false;
4023 }
4024
parseMDTuple(MDNode * & MD,bool IsDistinct)4025 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4026 SmallVector<Metadata *, 16> Elts;
4027 if (parseMDNodeVector(Elts))
4028 return true;
4029
4030 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4031 return false;
4032 }
4033
4034 /// MDNode:
4035 /// ::= !{ ... }
4036 /// ::= !7
4037 /// ::= !DILocation(...)
parseMDNode(MDNode * & N)4038 bool LLParser::parseMDNode(MDNode *&N) {
4039 if (Lex.getKind() == lltok::MetadataVar)
4040 return parseSpecializedMDNode(N);
4041
4042 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4043 }
4044
parseMDNodeTail(MDNode * & N)4045 bool LLParser::parseMDNodeTail(MDNode *&N) {
4046 // !{ ... }
4047 if (Lex.getKind() == lltok::lbrace)
4048 return parseMDTuple(N);
4049
4050 // !42
4051 return parseMDNodeID(N);
4052 }
4053
4054 namespace {
4055
4056 /// Structure to represent an optional metadata field.
4057 template <class FieldTy> struct MDFieldImpl {
4058 typedef MDFieldImpl ImplTy;
4059 FieldTy Val;
4060 bool Seen;
4061
assign__anon9931e35d0111::MDFieldImpl4062 void assign(FieldTy Val) {
4063 Seen = true;
4064 this->Val = std::move(Val);
4065 }
4066
MDFieldImpl__anon9931e35d0111::MDFieldImpl4067 explicit MDFieldImpl(FieldTy Default)
4068 : Val(std::move(Default)), Seen(false) {}
4069 };
4070
4071 /// Structure to represent an optional metadata field that
4072 /// can be of either type (A or B) and encapsulates the
4073 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4074 /// to reimplement the specifics for representing each Field.
4075 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4076 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4077 FieldTypeA A;
4078 FieldTypeB B;
4079 bool Seen;
4080
4081 enum {
4082 IsInvalid = 0,
4083 IsTypeA = 1,
4084 IsTypeB = 2
4085 } WhatIs;
4086
assign__anon9931e35d0111::MDEitherFieldImpl4087 void assign(FieldTypeA A) {
4088 Seen = true;
4089 this->A = std::move(A);
4090 WhatIs = IsTypeA;
4091 }
4092
assign__anon9931e35d0111::MDEitherFieldImpl4093 void assign(FieldTypeB B) {
4094 Seen = true;
4095 this->B = std::move(B);
4096 WhatIs = IsTypeB;
4097 }
4098
MDEitherFieldImpl__anon9931e35d0111::MDEitherFieldImpl4099 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4100 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4101 WhatIs(IsInvalid) {}
4102 };
4103
4104 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4105 uint64_t Max;
4106
MDUnsignedField__anon9931e35d0111::MDUnsignedField4107 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4108 : ImplTy(Default), Max(Max) {}
4109 };
4110
4111 struct LineField : public MDUnsignedField {
LineField__anon9931e35d0111::LineField4112 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4113 };
4114
4115 struct ColumnField : public MDUnsignedField {
ColumnField__anon9931e35d0111::ColumnField4116 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4117 };
4118
4119 struct DwarfTagField : public MDUnsignedField {
DwarfTagField__anon9931e35d0111::DwarfTagField4120 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
DwarfTagField__anon9931e35d0111::DwarfTagField4121 DwarfTagField(dwarf::Tag DefaultTag)
4122 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4123 };
4124
4125 struct DwarfMacinfoTypeField : public MDUnsignedField {
DwarfMacinfoTypeField__anon9931e35d0111::DwarfMacinfoTypeField4126 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
DwarfMacinfoTypeField__anon9931e35d0111::DwarfMacinfoTypeField4127 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4128 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4129 };
4130
4131 struct DwarfAttEncodingField : public MDUnsignedField {
DwarfAttEncodingField__anon9931e35d0111::DwarfAttEncodingField4132 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4133 };
4134
4135 struct DwarfVirtualityField : public MDUnsignedField {
DwarfVirtualityField__anon9931e35d0111::DwarfVirtualityField4136 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4137 };
4138
4139 struct DwarfLangField : public MDUnsignedField {
DwarfLangField__anon9931e35d0111::DwarfLangField4140 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4141 };
4142
4143 struct DwarfCCField : public MDUnsignedField {
DwarfCCField__anon9931e35d0111::DwarfCCField4144 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4145 };
4146
4147 struct EmissionKindField : public MDUnsignedField {
EmissionKindField__anon9931e35d0111::EmissionKindField4148 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4149 };
4150
4151 struct NameTableKindField : public MDUnsignedField {
NameTableKindField__anon9931e35d0111::NameTableKindField4152 NameTableKindField()
4153 : MDUnsignedField(
4154 0, (unsigned)
4155 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4156 };
4157
4158 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
DIFlagField__anon9931e35d0111::DIFlagField4159 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4160 };
4161
4162 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
DISPFlagField__anon9931e35d0111::DISPFlagField4163 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4164 };
4165
4166 struct MDAPSIntField : public MDFieldImpl<APSInt> {
MDAPSIntField__anon9931e35d0111::MDAPSIntField4167 MDAPSIntField() : ImplTy(APSInt()) {}
4168 };
4169
4170 struct MDSignedField : public MDFieldImpl<int64_t> {
4171 int64_t Min;
4172 int64_t Max;
4173
MDSignedField__anon9931e35d0111::MDSignedField4174 MDSignedField(int64_t Default = 0)
4175 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
MDSignedField__anon9931e35d0111::MDSignedField4176 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4177 : ImplTy(Default), Min(Min), Max(Max) {}
4178 };
4179
4180 struct MDBoolField : public MDFieldImpl<bool> {
MDBoolField__anon9931e35d0111::MDBoolField4181 MDBoolField(bool Default = false) : ImplTy(Default) {}
4182 };
4183
4184 struct MDField : public MDFieldImpl<Metadata *> {
4185 bool AllowNull;
4186
MDField__anon9931e35d0111::MDField4187 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4188 };
4189
4190 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
MDConstant__anon9931e35d0111::MDConstant4191 MDConstant() : ImplTy(nullptr) {}
4192 };
4193
4194 struct MDStringField : public MDFieldImpl<MDString *> {
4195 bool AllowEmpty;
MDStringField__anon9931e35d0111::MDStringField4196 MDStringField(bool AllowEmpty = true)
4197 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4198 };
4199
4200 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
MDFieldList__anon9931e35d0111::MDFieldList4201 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4202 };
4203
4204 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
ChecksumKindField__anon9931e35d0111::ChecksumKindField4205 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4206 };
4207
4208 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
MDSignedOrMDField__anon9931e35d0111::MDSignedOrMDField4209 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4210 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4211
MDSignedOrMDField__anon9931e35d0111::MDSignedOrMDField4212 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4213 bool AllowNull = true)
4214 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4215
isMDSignedField__anon9931e35d0111::MDSignedOrMDField4216 bool isMDSignedField() const { return WhatIs == IsTypeA; }
isMDField__anon9931e35d0111::MDSignedOrMDField4217 bool isMDField() const { return WhatIs == IsTypeB; }
getMDSignedValue__anon9931e35d0111::MDSignedOrMDField4218 int64_t getMDSignedValue() const {
4219 assert(isMDSignedField() && "Wrong field type");
4220 return A.Val;
4221 }
getMDFieldValue__anon9931e35d0111::MDSignedOrMDField4222 Metadata *getMDFieldValue() const {
4223 assert(isMDField() && "Wrong field type");
4224 return B.Val;
4225 }
4226 };
4227
4228 struct MDSignedOrUnsignedField
4229 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
MDSignedOrUnsignedField__anon9931e35d0111::MDSignedOrUnsignedField4230 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
4231
isMDSignedField__anon9931e35d0111::MDSignedOrUnsignedField4232 bool isMDSignedField() const { return WhatIs == IsTypeA; }
isMDUnsignedField__anon9931e35d0111::MDSignedOrUnsignedField4233 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
getMDSignedValue__anon9931e35d0111::MDSignedOrUnsignedField4234 int64_t getMDSignedValue() const {
4235 assert(isMDSignedField() && "Wrong field type");
4236 return A.Val;
4237 }
getMDUnsignedValue__anon9931e35d0111::MDSignedOrUnsignedField4238 uint64_t getMDUnsignedValue() const {
4239 assert(isMDUnsignedField() && "Wrong field type");
4240 return B.Val;
4241 }
4242 };
4243
4244 } // end anonymous namespace
4245
4246 namespace llvm {
4247
4248 template <>
parseMDField(LocTy Loc,StringRef Name,MDAPSIntField & Result)4249 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4250 if (Lex.getKind() != lltok::APSInt)
4251 return tokError("expected integer");
4252
4253 Result.assign(Lex.getAPSIntVal());
4254 Lex.Lex();
4255 return false;
4256 }
4257
4258 template <>
parseMDField(LocTy Loc,StringRef Name,MDUnsignedField & Result)4259 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4260 MDUnsignedField &Result) {
4261 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4262 return tokError("expected unsigned integer");
4263
4264 auto &U = Lex.getAPSIntVal();
4265 if (U.ugt(Result.Max))
4266 return tokError("value for '" + Name + "' too large, limit is " +
4267 Twine(Result.Max));
4268 Result.assign(U.getZExtValue());
4269 assert(Result.Val <= Result.Max && "Expected value in range");
4270 Lex.Lex();
4271 return false;
4272 }
4273
4274 template <>
parseMDField(LocTy Loc,StringRef Name,LineField & Result)4275 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4276 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4277 }
4278 template <>
parseMDField(LocTy Loc,StringRef Name,ColumnField & Result)4279 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4280 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4281 }
4282
4283 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfTagField & Result)4284 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4285 if (Lex.getKind() == lltok::APSInt)
4286 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4287
4288 if (Lex.getKind() != lltok::DwarfTag)
4289 return tokError("expected DWARF tag");
4290
4291 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4292 if (Tag == dwarf::DW_TAG_invalid)
4293 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4294 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4295
4296 Result.assign(Tag);
4297 Lex.Lex();
4298 return false;
4299 }
4300
4301 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfMacinfoTypeField & Result)4302 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4303 DwarfMacinfoTypeField &Result) {
4304 if (Lex.getKind() == lltok::APSInt)
4305 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4306
4307 if (Lex.getKind() != lltok::DwarfMacinfo)
4308 return tokError("expected DWARF macinfo type");
4309
4310 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4311 if (Macinfo == dwarf::DW_MACINFO_invalid)
4312 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4313 Lex.getStrVal() + "'");
4314 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4315
4316 Result.assign(Macinfo);
4317 Lex.Lex();
4318 return false;
4319 }
4320
4321 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfVirtualityField & Result)4322 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4323 DwarfVirtualityField &Result) {
4324 if (Lex.getKind() == lltok::APSInt)
4325 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4326
4327 if (Lex.getKind() != lltok::DwarfVirtuality)
4328 return tokError("expected DWARF virtuality code");
4329
4330 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4331 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4332 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4333 Lex.getStrVal() + "'");
4334 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4335 Result.assign(Virtuality);
4336 Lex.Lex();
4337 return false;
4338 }
4339
4340 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfLangField & Result)4341 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4342 if (Lex.getKind() == lltok::APSInt)
4343 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4344
4345 if (Lex.getKind() != lltok::DwarfLang)
4346 return tokError("expected DWARF language");
4347
4348 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4349 if (!Lang)
4350 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4351 "'");
4352 assert(Lang <= Result.Max && "Expected valid DWARF language");
4353 Result.assign(Lang);
4354 Lex.Lex();
4355 return false;
4356 }
4357
4358 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfCCField & Result)4359 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4360 if (Lex.getKind() == lltok::APSInt)
4361 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4362
4363 if (Lex.getKind() != lltok::DwarfCC)
4364 return tokError("expected DWARF calling convention");
4365
4366 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4367 if (!CC)
4368 return tokError("invalid DWARF calling convention" + Twine(" '") +
4369 Lex.getStrVal() + "'");
4370 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4371 Result.assign(CC);
4372 Lex.Lex();
4373 return false;
4374 }
4375
4376 template <>
parseMDField(LocTy Loc,StringRef Name,EmissionKindField & Result)4377 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4378 EmissionKindField &Result) {
4379 if (Lex.getKind() == lltok::APSInt)
4380 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4381
4382 if (Lex.getKind() != lltok::EmissionKind)
4383 return tokError("expected emission kind");
4384
4385 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4386 if (!Kind)
4387 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4388 "'");
4389 assert(*Kind <= Result.Max && "Expected valid emission kind");
4390 Result.assign(*Kind);
4391 Lex.Lex();
4392 return false;
4393 }
4394
4395 template <>
parseMDField(LocTy Loc,StringRef Name,NameTableKindField & Result)4396 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4397 NameTableKindField &Result) {
4398 if (Lex.getKind() == lltok::APSInt)
4399 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4400
4401 if (Lex.getKind() != lltok::NameTableKind)
4402 return tokError("expected nameTable kind");
4403
4404 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4405 if (!Kind)
4406 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4407 "'");
4408 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4409 Result.assign((unsigned)*Kind);
4410 Lex.Lex();
4411 return false;
4412 }
4413
4414 template <>
parseMDField(LocTy Loc,StringRef Name,DwarfAttEncodingField & Result)4415 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4416 DwarfAttEncodingField &Result) {
4417 if (Lex.getKind() == lltok::APSInt)
4418 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4419
4420 if (Lex.getKind() != lltok::DwarfAttEncoding)
4421 return tokError("expected DWARF type attribute encoding");
4422
4423 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4424 if (!Encoding)
4425 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4426 Lex.getStrVal() + "'");
4427 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4428 Result.assign(Encoding);
4429 Lex.Lex();
4430 return false;
4431 }
4432
4433 /// DIFlagField
4434 /// ::= uint32
4435 /// ::= DIFlagVector
4436 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4437 template <>
parseMDField(LocTy Loc,StringRef Name,DIFlagField & Result)4438 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4439
4440 // parser for a single flag.
4441 auto parseFlag = [&](DINode::DIFlags &Val) {
4442 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4443 uint32_t TempVal = static_cast<uint32_t>(Val);
4444 bool Res = parseUInt32(TempVal);
4445 Val = static_cast<DINode::DIFlags>(TempVal);
4446 return Res;
4447 }
4448
4449 if (Lex.getKind() != lltok::DIFlag)
4450 return tokError("expected debug info flag");
4451
4452 Val = DINode::getFlag(Lex.getStrVal());
4453 if (!Val)
4454 return tokError(Twine("invalid debug info flag flag '") +
4455 Lex.getStrVal() + "'");
4456 Lex.Lex();
4457 return false;
4458 };
4459
4460 // parse the flags and combine them together.
4461 DINode::DIFlags Combined = DINode::FlagZero;
4462 do {
4463 DINode::DIFlags Val;
4464 if (parseFlag(Val))
4465 return true;
4466 Combined |= Val;
4467 } while (EatIfPresent(lltok::bar));
4468
4469 Result.assign(Combined);
4470 return false;
4471 }
4472
4473 /// DISPFlagField
4474 /// ::= uint32
4475 /// ::= DISPFlagVector
4476 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4477 template <>
parseMDField(LocTy Loc,StringRef Name,DISPFlagField & Result)4478 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4479
4480 // parser for a single flag.
4481 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4482 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4483 uint32_t TempVal = static_cast<uint32_t>(Val);
4484 bool Res = parseUInt32(TempVal);
4485 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4486 return Res;
4487 }
4488
4489 if (Lex.getKind() != lltok::DISPFlag)
4490 return tokError("expected debug info flag");
4491
4492 Val = DISubprogram::getFlag(Lex.getStrVal());
4493 if (!Val)
4494 return tokError(Twine("invalid subprogram debug info flag '") +
4495 Lex.getStrVal() + "'");
4496 Lex.Lex();
4497 return false;
4498 };
4499
4500 // parse the flags and combine them together.
4501 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4502 do {
4503 DISubprogram::DISPFlags Val;
4504 if (parseFlag(Val))
4505 return true;
4506 Combined |= Val;
4507 } while (EatIfPresent(lltok::bar));
4508
4509 Result.assign(Combined);
4510 return false;
4511 }
4512
4513 template <>
parseMDField(LocTy Loc,StringRef Name,MDSignedField & Result)4514 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4515 if (Lex.getKind() != lltok::APSInt)
4516 return tokError("expected signed integer");
4517
4518 auto &S = Lex.getAPSIntVal();
4519 if (S < Result.Min)
4520 return tokError("value for '" + Name + "' too small, limit is " +
4521 Twine(Result.Min));
4522 if (S > Result.Max)
4523 return tokError("value for '" + Name + "' too large, limit is " +
4524 Twine(Result.Max));
4525 Result.assign(S.getExtValue());
4526 assert(Result.Val >= Result.Min && "Expected value in range");
4527 assert(Result.Val <= Result.Max && "Expected value in range");
4528 Lex.Lex();
4529 return false;
4530 }
4531
4532 template <>
parseMDField(LocTy Loc,StringRef Name,MDBoolField & Result)4533 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4534 switch (Lex.getKind()) {
4535 default:
4536 return tokError("expected 'true' or 'false'");
4537 case lltok::kw_true:
4538 Result.assign(true);
4539 break;
4540 case lltok::kw_false:
4541 Result.assign(false);
4542 break;
4543 }
4544 Lex.Lex();
4545 return false;
4546 }
4547
4548 template <>
parseMDField(LocTy Loc,StringRef Name,MDField & Result)4549 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4550 if (Lex.getKind() == lltok::kw_null) {
4551 if (!Result.AllowNull)
4552 return tokError("'" + Name + "' cannot be null");
4553 Lex.Lex();
4554 Result.assign(nullptr);
4555 return false;
4556 }
4557
4558 Metadata *MD;
4559 if (parseMetadata(MD, nullptr))
4560 return true;
4561
4562 Result.assign(MD);
4563 return false;
4564 }
4565
4566 template <>
parseMDField(LocTy Loc,StringRef Name,MDSignedOrMDField & Result)4567 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4568 MDSignedOrMDField &Result) {
4569 // Try to parse a signed int.
4570 if (Lex.getKind() == lltok::APSInt) {
4571 MDSignedField Res = Result.A;
4572 if (!parseMDField(Loc, Name, Res)) {
4573 Result.assign(Res);
4574 return false;
4575 }
4576 return true;
4577 }
4578
4579 // Otherwise, try to parse as an MDField.
4580 MDField Res = Result.B;
4581 if (!parseMDField(Loc, Name, Res)) {
4582 Result.assign(Res);
4583 return false;
4584 }
4585
4586 return true;
4587 }
4588
4589 template <>
parseMDField(LocTy Loc,StringRef Name,MDStringField & Result)4590 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4591 LocTy ValueLoc = Lex.getLoc();
4592 std::string S;
4593 if (parseStringConstant(S))
4594 return true;
4595
4596 if (!Result.AllowEmpty && S.empty())
4597 return error(ValueLoc, "'" + Name + "' cannot be empty");
4598
4599 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4600 return false;
4601 }
4602
4603 template <>
parseMDField(LocTy Loc,StringRef Name,MDFieldList & Result)4604 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4605 SmallVector<Metadata *, 4> MDs;
4606 if (parseMDNodeVector(MDs))
4607 return true;
4608
4609 Result.assign(std::move(MDs));
4610 return false;
4611 }
4612
4613 template <>
parseMDField(LocTy Loc,StringRef Name,ChecksumKindField & Result)4614 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4615 ChecksumKindField &Result) {
4616 Optional<DIFile::ChecksumKind> CSKind =
4617 DIFile::getChecksumKind(Lex.getStrVal());
4618
4619 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4620 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4621 "'");
4622
4623 Result.assign(*CSKind);
4624 Lex.Lex();
4625 return false;
4626 }
4627
4628 } // end namespace llvm
4629
4630 template <class ParserTy>
parseMDFieldsImplBody(ParserTy ParseField)4631 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4632 do {
4633 if (Lex.getKind() != lltok::LabelStr)
4634 return tokError("expected field label here");
4635
4636 if (ParseField())
4637 return true;
4638 } while (EatIfPresent(lltok::comma));
4639
4640 return false;
4641 }
4642
4643 template <class ParserTy>
parseMDFieldsImpl(ParserTy ParseField,LocTy & ClosingLoc)4644 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4645 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4646 Lex.Lex();
4647
4648 if (parseToken(lltok::lparen, "expected '(' here"))
4649 return true;
4650 if (Lex.getKind() != lltok::rparen)
4651 if (parseMDFieldsImplBody(ParseField))
4652 return true;
4653
4654 ClosingLoc = Lex.getLoc();
4655 return parseToken(lltok::rparen, "expected ')' here");
4656 }
4657
4658 template <class FieldTy>
parseMDField(StringRef Name,FieldTy & Result)4659 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4660 if (Result.Seen)
4661 return tokError("field '" + Name + "' cannot be specified more than once");
4662
4663 LocTy Loc = Lex.getLoc();
4664 Lex.Lex();
4665 return parseMDField(Loc, Name, Result);
4666 }
4667
parseSpecializedMDNode(MDNode * & N,bool IsDistinct)4668 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4669 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4670
4671 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4672 if (Lex.getStrVal() == #CLASS) \
4673 return parse##CLASS(N, IsDistinct);
4674 #include "llvm/IR/Metadata.def"
4675
4676 return tokError("expected metadata type");
4677 }
4678
4679 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4680 #define NOP_FIELD(NAME, TYPE, INIT)
4681 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4682 if (!NAME.Seen) \
4683 return error(ClosingLoc, "missing required field '" #NAME "'");
4684 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4685 if (Lex.getStrVal() == #NAME) \
4686 return parseMDField(#NAME, NAME);
4687 #define PARSE_MD_FIELDS() \
4688 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4689 do { \
4690 LocTy ClosingLoc; \
4691 if (parseMDFieldsImpl( \
4692 [&]() -> bool { \
4693 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4694 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4695 "'"); \
4696 }, \
4697 ClosingLoc)) \
4698 return true; \
4699 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4700 } while (false)
4701 #define GET_OR_DISTINCT(CLASS, ARGS) \
4702 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4703
4704 /// parseDILocationFields:
4705 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4706 /// isImplicitCode: true)
parseDILocation(MDNode * & Result,bool IsDistinct)4707 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4708 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4709 OPTIONAL(line, LineField, ); \
4710 OPTIONAL(column, ColumnField, ); \
4711 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4712 OPTIONAL(inlinedAt, MDField, ); \
4713 OPTIONAL(isImplicitCode, MDBoolField, (false));
4714 PARSE_MD_FIELDS();
4715 #undef VISIT_MD_FIELDS
4716
4717 Result =
4718 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4719 inlinedAt.Val, isImplicitCode.Val));
4720 return false;
4721 }
4722
4723 /// parseGenericDINode:
4724 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
parseGenericDINode(MDNode * & Result,bool IsDistinct)4725 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4726 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4727 REQUIRED(tag, DwarfTagField, ); \
4728 OPTIONAL(header, MDStringField, ); \
4729 OPTIONAL(operands, MDFieldList, );
4730 PARSE_MD_FIELDS();
4731 #undef VISIT_MD_FIELDS
4732
4733 Result = GET_OR_DISTINCT(GenericDINode,
4734 (Context, tag.Val, header.Val, operands.Val));
4735 return false;
4736 }
4737
4738 /// parseDISubrange:
4739 /// ::= !DISubrange(count: 30, lowerBound: 2)
4740 /// ::= !DISubrange(count: !node, lowerBound: 2)
4741 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
parseDISubrange(MDNode * & Result,bool IsDistinct)4742 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4743 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4744 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4745 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4746 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4747 OPTIONAL(stride, MDSignedOrMDField, );
4748 PARSE_MD_FIELDS();
4749 #undef VISIT_MD_FIELDS
4750
4751 Metadata *Count = nullptr;
4752 Metadata *LowerBound = nullptr;
4753 Metadata *UpperBound = nullptr;
4754 Metadata *Stride = nullptr;
4755
4756 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4757 if (Bound.isMDSignedField())
4758 return ConstantAsMetadata::get(ConstantInt::getSigned(
4759 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4760 if (Bound.isMDField())
4761 return Bound.getMDFieldValue();
4762 return nullptr;
4763 };
4764
4765 Count = convToMetadata(count);
4766 LowerBound = convToMetadata(lowerBound);
4767 UpperBound = convToMetadata(upperBound);
4768 Stride = convToMetadata(stride);
4769
4770 Result = GET_OR_DISTINCT(DISubrange,
4771 (Context, Count, LowerBound, UpperBound, Stride));
4772
4773 return false;
4774 }
4775
4776 /// parseDIGenericSubrange:
4777 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4778 /// !node3)
parseDIGenericSubrange(MDNode * & Result,bool IsDistinct)4779 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4780 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4781 OPTIONAL(count, MDSignedOrMDField, ); \
4782 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4783 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4784 OPTIONAL(stride, MDSignedOrMDField, );
4785 PARSE_MD_FIELDS();
4786 #undef VISIT_MD_FIELDS
4787
4788 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4789 if (Bound.isMDSignedField())
4790 return DIExpression::get(
4791 Context, {dwarf::DW_OP_consts,
4792 static_cast<uint64_t>(Bound.getMDSignedValue())});
4793 if (Bound.isMDField())
4794 return Bound.getMDFieldValue();
4795 return nullptr;
4796 };
4797
4798 Metadata *Count = ConvToMetadata(count);
4799 Metadata *LowerBound = ConvToMetadata(lowerBound);
4800 Metadata *UpperBound = ConvToMetadata(upperBound);
4801 Metadata *Stride = ConvToMetadata(stride);
4802
4803 Result = GET_OR_DISTINCT(DIGenericSubrange,
4804 (Context, Count, LowerBound, UpperBound, Stride));
4805
4806 return false;
4807 }
4808
4809 /// parseDIEnumerator:
4810 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
parseDIEnumerator(MDNode * & Result,bool IsDistinct)4811 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4812 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4813 REQUIRED(name, MDStringField, ); \
4814 REQUIRED(value, MDAPSIntField, ); \
4815 OPTIONAL(isUnsigned, MDBoolField, (false));
4816 PARSE_MD_FIELDS();
4817 #undef VISIT_MD_FIELDS
4818
4819 if (isUnsigned.Val && value.Val.isNegative())
4820 return tokError("unsigned enumerator with negative value");
4821
4822 APSInt Value(value.Val);
4823 // Add a leading zero so that unsigned values with the msb set are not
4824 // mistaken for negative values when used for signed enumerators.
4825 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4826 Value = Value.zext(Value.getBitWidth() + 1);
4827
4828 Result =
4829 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4830
4831 return false;
4832 }
4833
4834 /// parseDIBasicType:
4835 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4836 /// encoding: DW_ATE_encoding, flags: 0)
parseDIBasicType(MDNode * & Result,bool IsDistinct)4837 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4838 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4839 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4840 OPTIONAL(name, MDStringField, ); \
4841 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4842 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4843 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4844 OPTIONAL(flags, DIFlagField, );
4845 PARSE_MD_FIELDS();
4846 #undef VISIT_MD_FIELDS
4847
4848 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4849 align.Val, encoding.Val, flags.Val));
4850 return false;
4851 }
4852
4853 /// parseDIStringType:
4854 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
parseDIStringType(MDNode * & Result,bool IsDistinct)4855 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4856 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4857 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4858 OPTIONAL(name, MDStringField, ); \
4859 OPTIONAL(stringLength, MDField, ); \
4860 OPTIONAL(stringLengthExpression, MDField, ); \
4861 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4862 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4863 OPTIONAL(encoding, DwarfAttEncodingField, );
4864 PARSE_MD_FIELDS();
4865 #undef VISIT_MD_FIELDS
4866
4867 Result = GET_OR_DISTINCT(DIStringType,
4868 (Context, tag.Val, name.Val, stringLength.Val,
4869 stringLengthExpression.Val, size.Val, align.Val,
4870 encoding.Val));
4871 return false;
4872 }
4873
4874 /// parseDIDerivedType:
4875 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4876 /// line: 7, scope: !1, baseType: !2, size: 32,
4877 /// align: 32, offset: 0, flags: 0, extraData: !3,
4878 /// dwarfAddressSpace: 3)
parseDIDerivedType(MDNode * & Result,bool IsDistinct)4879 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4880 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4881 REQUIRED(tag, DwarfTagField, ); \
4882 OPTIONAL(name, MDStringField, ); \
4883 OPTIONAL(file, MDField, ); \
4884 OPTIONAL(line, LineField, ); \
4885 OPTIONAL(scope, MDField, ); \
4886 REQUIRED(baseType, MDField, ); \
4887 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4888 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4889 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4890 OPTIONAL(flags, DIFlagField, ); \
4891 OPTIONAL(extraData, MDField, ); \
4892 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4893 PARSE_MD_FIELDS();
4894 #undef VISIT_MD_FIELDS
4895
4896 Optional<unsigned> DWARFAddressSpace;
4897 if (dwarfAddressSpace.Val != UINT32_MAX)
4898 DWARFAddressSpace = dwarfAddressSpace.Val;
4899
4900 Result = GET_OR_DISTINCT(DIDerivedType,
4901 (Context, tag.Val, name.Val, file.Val, line.Val,
4902 scope.Val, baseType.Val, size.Val, align.Val,
4903 offset.Val, DWARFAddressSpace, flags.Val,
4904 extraData.Val));
4905 return false;
4906 }
4907
parseDICompositeType(MDNode * & Result,bool IsDistinct)4908 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4909 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4910 REQUIRED(tag, DwarfTagField, ); \
4911 OPTIONAL(name, MDStringField, ); \
4912 OPTIONAL(file, MDField, ); \
4913 OPTIONAL(line, LineField, ); \
4914 OPTIONAL(scope, MDField, ); \
4915 OPTIONAL(baseType, MDField, ); \
4916 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4917 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4918 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4919 OPTIONAL(flags, DIFlagField, ); \
4920 OPTIONAL(elements, MDField, ); \
4921 OPTIONAL(runtimeLang, DwarfLangField, ); \
4922 OPTIONAL(vtableHolder, MDField, ); \
4923 OPTIONAL(templateParams, MDField, ); \
4924 OPTIONAL(identifier, MDStringField, ); \
4925 OPTIONAL(discriminator, MDField, ); \
4926 OPTIONAL(dataLocation, MDField, ); \
4927 OPTIONAL(associated, MDField, ); \
4928 OPTIONAL(allocated, MDField, ); \
4929 OPTIONAL(rank, MDSignedOrMDField, );
4930 PARSE_MD_FIELDS();
4931 #undef VISIT_MD_FIELDS
4932
4933 Metadata *Rank = nullptr;
4934 if (rank.isMDSignedField())
4935 Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4936 Type::getInt64Ty(Context), rank.getMDSignedValue()));
4937 else if (rank.isMDField())
4938 Rank = rank.getMDFieldValue();
4939
4940 // If this has an identifier try to build an ODR type.
4941 if (identifier.Val)
4942 if (auto *CT = DICompositeType::buildODRType(
4943 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4944 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4945 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4946 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4947 Rank)) {
4948 Result = CT;
4949 return false;
4950 }
4951
4952 // Create a new node, and save it in the context if it belongs in the type
4953 // map.
4954 Result = GET_OR_DISTINCT(
4955 DICompositeType,
4956 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4957 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4958 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4959 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4960 Rank));
4961 return false;
4962 }
4963
parseDISubroutineType(MDNode * & Result,bool IsDistinct)4964 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4965 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4966 OPTIONAL(flags, DIFlagField, ); \
4967 OPTIONAL(cc, DwarfCCField, ); \
4968 REQUIRED(types, MDField, );
4969 PARSE_MD_FIELDS();
4970 #undef VISIT_MD_FIELDS
4971
4972 Result = GET_OR_DISTINCT(DISubroutineType,
4973 (Context, flags.Val, cc.Val, types.Val));
4974 return false;
4975 }
4976
4977 /// parseDIFileType:
4978 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4979 /// checksumkind: CSK_MD5,
4980 /// checksum: "000102030405060708090a0b0c0d0e0f",
4981 /// source: "source file contents")
parseDIFile(MDNode * & Result,bool IsDistinct)4982 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4983 // The default constructed value for checksumkind is required, but will never
4984 // be used, as the parser checks if the field was actually Seen before using
4985 // the Val.
4986 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4987 REQUIRED(filename, MDStringField, ); \
4988 REQUIRED(directory, MDStringField, ); \
4989 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4990 OPTIONAL(checksum, MDStringField, ); \
4991 OPTIONAL(source, MDStringField, );
4992 PARSE_MD_FIELDS();
4993 #undef VISIT_MD_FIELDS
4994
4995 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4996 if (checksumkind.Seen && checksum.Seen)
4997 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4998 else if (checksumkind.Seen || checksum.Seen)
4999 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
5000
5001 Optional<MDString *> OptSource;
5002 if (source.Seen)
5003 OptSource = source.Val;
5004 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
5005 OptChecksum, OptSource));
5006 return false;
5007 }
5008
5009 /// parseDICompileUnit:
5010 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5011 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5012 /// splitDebugFilename: "abc.debug",
5013 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5014 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5015 /// sysroot: "/", sdk: "MacOSX.sdk")
parseDICompileUnit(MDNode * & Result,bool IsDistinct)5016 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5017 if (!IsDistinct)
5018 return Lex.Error("missing 'distinct', required for !DICompileUnit");
5019
5020 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5021 REQUIRED(language, DwarfLangField, ); \
5022 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5023 OPTIONAL(producer, MDStringField, ); \
5024 OPTIONAL(isOptimized, MDBoolField, ); \
5025 OPTIONAL(flags, MDStringField, ); \
5026 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5027 OPTIONAL(splitDebugFilename, MDStringField, ); \
5028 OPTIONAL(emissionKind, EmissionKindField, ); \
5029 OPTIONAL(enums, MDField, ); \
5030 OPTIONAL(retainedTypes, MDField, ); \
5031 OPTIONAL(globals, MDField, ); \
5032 OPTIONAL(imports, MDField, ); \
5033 OPTIONAL(macros, MDField, ); \
5034 OPTIONAL(dwoId, MDUnsignedField, ); \
5035 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5036 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5037 OPTIONAL(nameTableKind, NameTableKindField, ); \
5038 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5039 OPTIONAL(sysroot, MDStringField, ); \
5040 OPTIONAL(sdk, MDStringField, );
5041 PARSE_MD_FIELDS();
5042 #undef VISIT_MD_FIELDS
5043
5044 Result = DICompileUnit::getDistinct(
5045 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5046 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5047 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5048 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5049 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5050 return false;
5051 }
5052
5053 /// parseDISubprogram:
5054 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5055 /// file: !1, line: 7, type: !2, isLocal: false,
5056 /// isDefinition: true, scopeLine: 8, containingType: !3,
5057 /// virtuality: DW_VIRTUALTIY_pure_virtual,
5058 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5059 /// spFlags: 10, isOptimized: false, templateParams: !4,
5060 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
parseDISubprogram(MDNode * & Result,bool IsDistinct)5061 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5062 auto Loc = Lex.getLoc();
5063 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5064 OPTIONAL(scope, MDField, ); \
5065 OPTIONAL(name, MDStringField, ); \
5066 OPTIONAL(linkageName, MDStringField, ); \
5067 OPTIONAL(file, MDField, ); \
5068 OPTIONAL(line, LineField, ); \
5069 OPTIONAL(type, MDField, ); \
5070 OPTIONAL(isLocal, MDBoolField, ); \
5071 OPTIONAL(isDefinition, MDBoolField, (true)); \
5072 OPTIONAL(scopeLine, LineField, ); \
5073 OPTIONAL(containingType, MDField, ); \
5074 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5075 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5076 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5077 OPTIONAL(flags, DIFlagField, ); \
5078 OPTIONAL(spFlags, DISPFlagField, ); \
5079 OPTIONAL(isOptimized, MDBoolField, ); \
5080 OPTIONAL(unit, MDField, ); \
5081 OPTIONAL(templateParams, MDField, ); \
5082 OPTIONAL(declaration, MDField, ); \
5083 OPTIONAL(retainedNodes, MDField, ); \
5084 OPTIONAL(thrownTypes, MDField, );
5085 PARSE_MD_FIELDS();
5086 #undef VISIT_MD_FIELDS
5087
5088 // An explicit spFlags field takes precedence over individual fields in
5089 // older IR versions.
5090 DISubprogram::DISPFlags SPFlags =
5091 spFlags.Seen ? spFlags.Val
5092 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5093 isOptimized.Val, virtuality.Val);
5094 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5095 return Lex.Error(
5096 Loc,
5097 "missing 'distinct', required for !DISubprogram that is a Definition");
5098 Result = GET_OR_DISTINCT(
5099 DISubprogram,
5100 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5101 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5102 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5103 declaration.Val, retainedNodes.Val, thrownTypes.Val));
5104 return false;
5105 }
5106
5107 /// parseDILexicalBlock:
5108 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
parseDILexicalBlock(MDNode * & Result,bool IsDistinct)5109 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5110 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5111 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5112 OPTIONAL(file, MDField, ); \
5113 OPTIONAL(line, LineField, ); \
5114 OPTIONAL(column, ColumnField, );
5115 PARSE_MD_FIELDS();
5116 #undef VISIT_MD_FIELDS
5117
5118 Result = GET_OR_DISTINCT(
5119 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5120 return false;
5121 }
5122
5123 /// parseDILexicalBlockFile:
5124 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
parseDILexicalBlockFile(MDNode * & Result,bool IsDistinct)5125 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5126 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5127 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5128 OPTIONAL(file, MDField, ); \
5129 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5130 PARSE_MD_FIELDS();
5131 #undef VISIT_MD_FIELDS
5132
5133 Result = GET_OR_DISTINCT(DILexicalBlockFile,
5134 (Context, scope.Val, file.Val, discriminator.Val));
5135 return false;
5136 }
5137
5138 /// parseDICommonBlock:
5139 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
parseDICommonBlock(MDNode * & Result,bool IsDistinct)5140 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5141 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5142 REQUIRED(scope, MDField, ); \
5143 OPTIONAL(declaration, MDField, ); \
5144 OPTIONAL(name, MDStringField, ); \
5145 OPTIONAL(file, MDField, ); \
5146 OPTIONAL(line, LineField, );
5147 PARSE_MD_FIELDS();
5148 #undef VISIT_MD_FIELDS
5149
5150 Result = GET_OR_DISTINCT(DICommonBlock,
5151 (Context, scope.Val, declaration.Val, name.Val,
5152 file.Val, line.Val));
5153 return false;
5154 }
5155
5156 /// parseDINamespace:
5157 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
parseDINamespace(MDNode * & Result,bool IsDistinct)5158 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5159 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5160 REQUIRED(scope, MDField, ); \
5161 OPTIONAL(name, MDStringField, ); \
5162 OPTIONAL(exportSymbols, MDBoolField, );
5163 PARSE_MD_FIELDS();
5164 #undef VISIT_MD_FIELDS
5165
5166 Result = GET_OR_DISTINCT(DINamespace,
5167 (Context, scope.Val, name.Val, exportSymbols.Val));
5168 return false;
5169 }
5170
5171 /// parseDIMacro:
5172 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5173 /// "SomeValue")
parseDIMacro(MDNode * & Result,bool IsDistinct)5174 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5175 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5176 REQUIRED(type, DwarfMacinfoTypeField, ); \
5177 OPTIONAL(line, LineField, ); \
5178 REQUIRED(name, MDStringField, ); \
5179 OPTIONAL(value, MDStringField, );
5180 PARSE_MD_FIELDS();
5181 #undef VISIT_MD_FIELDS
5182
5183 Result = GET_OR_DISTINCT(DIMacro,
5184 (Context, type.Val, line.Val, name.Val, value.Val));
5185 return false;
5186 }
5187
5188 /// parseDIMacroFile:
5189 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
parseDIMacroFile(MDNode * & Result,bool IsDistinct)5190 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5191 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5192 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5193 OPTIONAL(line, LineField, ); \
5194 REQUIRED(file, MDField, ); \
5195 OPTIONAL(nodes, MDField, );
5196 PARSE_MD_FIELDS();
5197 #undef VISIT_MD_FIELDS
5198
5199 Result = GET_OR_DISTINCT(DIMacroFile,
5200 (Context, type.Val, line.Val, file.Val, nodes.Val));
5201 return false;
5202 }
5203
5204 /// parseDIModule:
5205 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5206 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5207 /// file: !1, line: 4, isDecl: false)
parseDIModule(MDNode * & Result,bool IsDistinct)5208 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5209 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5210 REQUIRED(scope, MDField, ); \
5211 REQUIRED(name, MDStringField, ); \
5212 OPTIONAL(configMacros, MDStringField, ); \
5213 OPTIONAL(includePath, MDStringField, ); \
5214 OPTIONAL(apinotes, MDStringField, ); \
5215 OPTIONAL(file, MDField, ); \
5216 OPTIONAL(line, LineField, ); \
5217 OPTIONAL(isDecl, MDBoolField, );
5218 PARSE_MD_FIELDS();
5219 #undef VISIT_MD_FIELDS
5220
5221 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5222 configMacros.Val, includePath.Val,
5223 apinotes.Val, line.Val, isDecl.Val));
5224 return false;
5225 }
5226
5227 /// parseDITemplateTypeParameter:
5228 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
parseDITemplateTypeParameter(MDNode * & Result,bool IsDistinct)5229 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5230 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5231 OPTIONAL(name, MDStringField, ); \
5232 REQUIRED(type, MDField, ); \
5233 OPTIONAL(defaulted, MDBoolField, );
5234 PARSE_MD_FIELDS();
5235 #undef VISIT_MD_FIELDS
5236
5237 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5238 (Context, name.Val, type.Val, defaulted.Val));
5239 return false;
5240 }
5241
5242 /// parseDITemplateValueParameter:
5243 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5244 /// name: "V", type: !1, defaulted: false,
5245 /// value: i32 7)
parseDITemplateValueParameter(MDNode * & Result,bool IsDistinct)5246 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5247 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5248 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5249 OPTIONAL(name, MDStringField, ); \
5250 OPTIONAL(type, MDField, ); \
5251 OPTIONAL(defaulted, MDBoolField, ); \
5252 REQUIRED(value, MDField, );
5253
5254 PARSE_MD_FIELDS();
5255 #undef VISIT_MD_FIELDS
5256
5257 Result = GET_OR_DISTINCT(
5258 DITemplateValueParameter,
5259 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5260 return false;
5261 }
5262
5263 /// parseDIGlobalVariable:
5264 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5265 /// file: !1, line: 7, type: !2, isLocal: false,
5266 /// isDefinition: true, templateParams: !3,
5267 /// declaration: !4, align: 8)
parseDIGlobalVariable(MDNode * & Result,bool IsDistinct)5268 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5269 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5270 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
5271 OPTIONAL(scope, MDField, ); \
5272 OPTIONAL(linkageName, MDStringField, ); \
5273 OPTIONAL(file, MDField, ); \
5274 OPTIONAL(line, LineField, ); \
5275 OPTIONAL(type, MDField, ); \
5276 OPTIONAL(isLocal, MDBoolField, ); \
5277 OPTIONAL(isDefinition, MDBoolField, (true)); \
5278 OPTIONAL(templateParams, MDField, ); \
5279 OPTIONAL(declaration, MDField, ); \
5280 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
5281 PARSE_MD_FIELDS();
5282 #undef VISIT_MD_FIELDS
5283
5284 Result =
5285 GET_OR_DISTINCT(DIGlobalVariable,
5286 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5287 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5288 declaration.Val, templateParams.Val, align.Val));
5289 return false;
5290 }
5291
5292 /// parseDILocalVariable:
5293 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5294 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5295 /// align: 8)
5296 /// ::= !DILocalVariable(scope: !0, name: "foo",
5297 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5298 /// align: 8)
parseDILocalVariable(MDNode * & Result,bool IsDistinct)5299 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5300 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5301 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5302 OPTIONAL(name, MDStringField, ); \
5303 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5304 OPTIONAL(file, MDField, ); \
5305 OPTIONAL(line, LineField, ); \
5306 OPTIONAL(type, MDField, ); \
5307 OPTIONAL(flags, DIFlagField, ); \
5308 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
5309 PARSE_MD_FIELDS();
5310 #undef VISIT_MD_FIELDS
5311
5312 Result = GET_OR_DISTINCT(DILocalVariable,
5313 (Context, scope.Val, name.Val, file.Val, line.Val,
5314 type.Val, arg.Val, flags.Val, align.Val));
5315 return false;
5316 }
5317
5318 /// parseDILabel:
5319 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
parseDILabel(MDNode * & Result,bool IsDistinct)5320 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5321 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5322 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5323 REQUIRED(name, MDStringField, ); \
5324 REQUIRED(file, MDField, ); \
5325 REQUIRED(line, LineField, );
5326 PARSE_MD_FIELDS();
5327 #undef VISIT_MD_FIELDS
5328
5329 Result = GET_OR_DISTINCT(DILabel,
5330 (Context, scope.Val, name.Val, file.Val, line.Val));
5331 return false;
5332 }
5333
5334 /// parseDIExpression:
5335 /// ::= !DIExpression(0, 7, -1)
parseDIExpression(MDNode * & Result,bool IsDistinct)5336 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5337 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5338 Lex.Lex();
5339
5340 if (parseToken(lltok::lparen, "expected '(' here"))
5341 return true;
5342
5343 SmallVector<uint64_t, 8> Elements;
5344 if (Lex.getKind() != lltok::rparen)
5345 do {
5346 if (Lex.getKind() == lltok::DwarfOp) {
5347 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5348 Lex.Lex();
5349 Elements.push_back(Op);
5350 continue;
5351 }
5352 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5353 }
5354
5355 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5356 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5357 Lex.Lex();
5358 Elements.push_back(Op);
5359 continue;
5360 }
5361 return tokError(Twine("invalid DWARF attribute encoding '") +
5362 Lex.getStrVal() + "'");
5363 }
5364
5365 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5366 return tokError("expected unsigned integer");
5367
5368 auto &U = Lex.getAPSIntVal();
5369 if (U.ugt(UINT64_MAX))
5370 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5371 Elements.push_back(U.getZExtValue());
5372 Lex.Lex();
5373 } while (EatIfPresent(lltok::comma));
5374
5375 if (parseToken(lltok::rparen, "expected ')' here"))
5376 return true;
5377
5378 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5379 return false;
5380 }
5381
parseDIArgList(MDNode * & Result,bool IsDistinct)5382 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5383 return parseDIArgList(Result, IsDistinct, nullptr);
5384 }
5385 /// ParseDIArgList:
5386 /// ::= !DIArgList(i32 7, i64 %0)
parseDIArgList(MDNode * & Result,bool IsDistinct,PerFunctionState * PFS)5387 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5388 PerFunctionState *PFS) {
5389 assert(PFS && "Expected valid function state");
5390 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5391 Lex.Lex();
5392
5393 if (parseToken(lltok::lparen, "expected '(' here"))
5394 return true;
5395
5396 SmallVector<ValueAsMetadata *, 4> Args;
5397 if (Lex.getKind() != lltok::rparen)
5398 do {
5399 Metadata *MD;
5400 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5401 return true;
5402 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5403 } while (EatIfPresent(lltok::comma));
5404
5405 if (parseToken(lltok::rparen, "expected ')' here"))
5406 return true;
5407
5408 Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5409 return false;
5410 }
5411
5412 /// parseDIGlobalVariableExpression:
5413 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
parseDIGlobalVariableExpression(MDNode * & Result,bool IsDistinct)5414 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5415 bool IsDistinct) {
5416 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5417 REQUIRED(var, MDField, ); \
5418 REQUIRED(expr, MDField, );
5419 PARSE_MD_FIELDS();
5420 #undef VISIT_MD_FIELDS
5421
5422 Result =
5423 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5424 return false;
5425 }
5426
5427 /// parseDIObjCProperty:
5428 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5429 /// getter: "getFoo", attributes: 7, type: !2)
parseDIObjCProperty(MDNode * & Result,bool IsDistinct)5430 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5431 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5432 OPTIONAL(name, MDStringField, ); \
5433 OPTIONAL(file, MDField, ); \
5434 OPTIONAL(line, LineField, ); \
5435 OPTIONAL(setter, MDStringField, ); \
5436 OPTIONAL(getter, MDStringField, ); \
5437 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5438 OPTIONAL(type, MDField, );
5439 PARSE_MD_FIELDS();
5440 #undef VISIT_MD_FIELDS
5441
5442 Result = GET_OR_DISTINCT(DIObjCProperty,
5443 (Context, name.Val, file.Val, line.Val, setter.Val,
5444 getter.Val, attributes.Val, type.Val));
5445 return false;
5446 }
5447
5448 /// parseDIImportedEntity:
5449 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5450 /// line: 7, name: "foo")
parseDIImportedEntity(MDNode * & Result,bool IsDistinct)5451 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5452 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5453 REQUIRED(tag, DwarfTagField, ); \
5454 REQUIRED(scope, MDField, ); \
5455 OPTIONAL(entity, MDField, ); \
5456 OPTIONAL(file, MDField, ); \
5457 OPTIONAL(line, LineField, ); \
5458 OPTIONAL(name, MDStringField, );
5459 PARSE_MD_FIELDS();
5460 #undef VISIT_MD_FIELDS
5461
5462 Result = GET_OR_DISTINCT(
5463 DIImportedEntity,
5464 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
5465 return false;
5466 }
5467
5468 #undef PARSE_MD_FIELD
5469 #undef NOP_FIELD
5470 #undef REQUIRE_FIELD
5471 #undef DECLARE_FIELD
5472
5473 /// parseMetadataAsValue
5474 /// ::= metadata i32 %local
5475 /// ::= metadata i32 @global
5476 /// ::= metadata i32 7
5477 /// ::= metadata !0
5478 /// ::= metadata !{...}
5479 /// ::= metadata !"string"
parseMetadataAsValue(Value * & V,PerFunctionState & PFS)5480 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5481 // Note: the type 'metadata' has already been parsed.
5482 Metadata *MD;
5483 if (parseMetadata(MD, &PFS))
5484 return true;
5485
5486 V = MetadataAsValue::get(Context, MD);
5487 return false;
5488 }
5489
5490 /// parseValueAsMetadata
5491 /// ::= i32 %local
5492 /// ::= i32 @global
5493 /// ::= i32 7
parseValueAsMetadata(Metadata * & MD,const Twine & TypeMsg,PerFunctionState * PFS)5494 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5495 PerFunctionState *PFS) {
5496 Type *Ty;
5497 LocTy Loc;
5498 if (parseType(Ty, TypeMsg, Loc))
5499 return true;
5500 if (Ty->isMetadataTy())
5501 return error(Loc, "invalid metadata-value-metadata roundtrip");
5502
5503 Value *V;
5504 if (parseValue(Ty, V, PFS))
5505 return true;
5506
5507 MD = ValueAsMetadata::get(V);
5508 return false;
5509 }
5510
5511 /// parseMetadata
5512 /// ::= i32 %local
5513 /// ::= i32 @global
5514 /// ::= i32 7
5515 /// ::= !42
5516 /// ::= !{...}
5517 /// ::= !"string"
5518 /// ::= !DILocation(...)
parseMetadata(Metadata * & MD,PerFunctionState * PFS)5519 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5520 if (Lex.getKind() == lltok::MetadataVar) {
5521 MDNode *N;
5522 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5523 // so parsing this requires a Function State.
5524 if (Lex.getStrVal() == "DIArgList") {
5525 if (parseDIArgList(N, false, PFS))
5526 return true;
5527 } else if (parseSpecializedMDNode(N)) {
5528 return true;
5529 }
5530 MD = N;
5531 return false;
5532 }
5533
5534 // ValueAsMetadata:
5535 // <type> <value>
5536 if (Lex.getKind() != lltok::exclaim)
5537 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5538
5539 // '!'.
5540 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5541 Lex.Lex();
5542
5543 // MDString:
5544 // ::= '!' STRINGCONSTANT
5545 if (Lex.getKind() == lltok::StringConstant) {
5546 MDString *S;
5547 if (parseMDString(S))
5548 return true;
5549 MD = S;
5550 return false;
5551 }
5552
5553 // MDNode:
5554 // !{ ... }
5555 // !7
5556 MDNode *N;
5557 if (parseMDNodeTail(N))
5558 return true;
5559 MD = N;
5560 return false;
5561 }
5562
5563 //===----------------------------------------------------------------------===//
5564 // Function Parsing.
5565 //===----------------------------------------------------------------------===//
5566
convertValIDToValue(Type * Ty,ValID & ID,Value * & V,PerFunctionState * PFS,bool IsCall)5567 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5568 PerFunctionState *PFS, bool IsCall) {
5569 if (Ty->isFunctionTy())
5570 return error(ID.Loc, "functions are not values, refer to them as pointers");
5571
5572 switch (ID.Kind) {
5573 case ValID::t_LocalID:
5574 if (!PFS)
5575 return error(ID.Loc, "invalid use of function-local name");
5576 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5577 return V == nullptr;
5578 case ValID::t_LocalName:
5579 if (!PFS)
5580 return error(ID.Loc, "invalid use of function-local name");
5581 V = PFS->getVal(ID.StrVal, Ty, ID.Loc, IsCall);
5582 return V == nullptr;
5583 case ValID::t_InlineAsm: {
5584 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5585 return error(ID.Loc, "invalid type for inline asm constraint string");
5586 V = InlineAsm::get(
5587 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5588 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5589 return false;
5590 }
5591 case ValID::t_GlobalName:
5592 V = getGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5593 return V == nullptr;
5594 case ValID::t_GlobalID:
5595 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5596 return V == nullptr;
5597 case ValID::t_APSInt:
5598 if (!Ty->isIntegerTy())
5599 return error(ID.Loc, "integer constant must have integer type");
5600 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5601 V = ConstantInt::get(Context, ID.APSIntVal);
5602 return false;
5603 case ValID::t_APFloat:
5604 if (!Ty->isFloatingPointTy() ||
5605 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5606 return error(ID.Loc, "floating point constant invalid for type");
5607
5608 // The lexer has no type info, so builds all half, bfloat, float, and double
5609 // FP constants as double. Fix this here. Long double does not need this.
5610 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5611 // Check for signaling before potentially converting and losing that info.
5612 bool IsSNAN = ID.APFloatVal.isSignaling();
5613 bool Ignored;
5614 if (Ty->isHalfTy())
5615 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5616 &Ignored);
5617 else if (Ty->isBFloatTy())
5618 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5619 &Ignored);
5620 else if (Ty->isFloatTy())
5621 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5622 &Ignored);
5623 if (IsSNAN) {
5624 // The convert call above may quiet an SNaN, so manufacture another
5625 // SNaN. The bitcast works because the payload (significand) parameter
5626 // is truncated to fit.
5627 APInt Payload = ID.APFloatVal.bitcastToAPInt();
5628 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5629 ID.APFloatVal.isNegative(), &Payload);
5630 }
5631 }
5632 V = ConstantFP::get(Context, ID.APFloatVal);
5633
5634 if (V->getType() != Ty)
5635 return error(ID.Loc, "floating point constant does not have type '" +
5636 getTypeString(Ty) + "'");
5637
5638 return false;
5639 case ValID::t_Null:
5640 if (!Ty->isPointerTy())
5641 return error(ID.Loc, "null must be a pointer type");
5642 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5643 return false;
5644 case ValID::t_Undef:
5645 // FIXME: LabelTy should not be a first-class type.
5646 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5647 return error(ID.Loc, "invalid type for undef constant");
5648 V = UndefValue::get(Ty);
5649 return false;
5650 case ValID::t_EmptyArray:
5651 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5652 return error(ID.Loc, "invalid empty array initializer");
5653 V = UndefValue::get(Ty);
5654 return false;
5655 case ValID::t_Zero:
5656 // FIXME: LabelTy should not be a first-class type.
5657 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5658 return error(ID.Loc, "invalid type for null constant");
5659 V = Constant::getNullValue(Ty);
5660 return false;
5661 case ValID::t_None:
5662 if (!Ty->isTokenTy())
5663 return error(ID.Loc, "invalid type for none constant");
5664 V = Constant::getNullValue(Ty);
5665 return false;
5666 case ValID::t_Poison:
5667 // FIXME: LabelTy should not be a first-class type.
5668 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5669 return error(ID.Loc, "invalid type for poison constant");
5670 V = PoisonValue::get(Ty);
5671 return false;
5672 case ValID::t_Constant:
5673 if (ID.ConstantVal->getType() != Ty)
5674 return error(ID.Loc, "constant expression type mismatch");
5675 V = ID.ConstantVal;
5676 return false;
5677 case ValID::t_ConstantStruct:
5678 case ValID::t_PackedConstantStruct:
5679 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5680 if (ST->getNumElements() != ID.UIntVal)
5681 return error(ID.Loc,
5682 "initializer with struct type has wrong # elements");
5683 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5684 return error(ID.Loc, "packed'ness of initializer and type don't match");
5685
5686 // Verify that the elements are compatible with the structtype.
5687 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5688 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5689 return error(
5690 ID.Loc,
5691 "element " + Twine(i) +
5692 " of struct initializer doesn't match struct element type");
5693
5694 V = ConstantStruct::get(
5695 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5696 } else
5697 return error(ID.Loc, "constant expression type mismatch");
5698 return false;
5699 }
5700 llvm_unreachable("Invalid ValID");
5701 }
5702
parseConstantValue(Type * Ty,Constant * & C)5703 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5704 C = nullptr;
5705 ValID ID;
5706 auto Loc = Lex.getLoc();
5707 if (parseValID(ID, /*PFS=*/nullptr))
5708 return true;
5709 switch (ID.Kind) {
5710 case ValID::t_APSInt:
5711 case ValID::t_APFloat:
5712 case ValID::t_Undef:
5713 case ValID::t_Constant:
5714 case ValID::t_ConstantStruct:
5715 case ValID::t_PackedConstantStruct: {
5716 Value *V;
5717 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5718 return true;
5719 assert(isa<Constant>(V) && "Expected a constant value");
5720 C = cast<Constant>(V);
5721 return false;
5722 }
5723 case ValID::t_Null:
5724 C = Constant::getNullValue(Ty);
5725 return false;
5726 default:
5727 return error(Loc, "expected a constant value");
5728 }
5729 }
5730
parseValue(Type * Ty,Value * & V,PerFunctionState * PFS)5731 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5732 V = nullptr;
5733 ValID ID;
5734 return parseValID(ID, PFS) ||
5735 convertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5736 }
5737
parseTypeAndValue(Value * & V,PerFunctionState * PFS)5738 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5739 Type *Ty = nullptr;
5740 return parseType(Ty) || parseValue(Ty, V, PFS);
5741 }
5742
parseTypeAndBasicBlock(BasicBlock * & BB,LocTy & Loc,PerFunctionState & PFS)5743 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5744 PerFunctionState &PFS) {
5745 Value *V;
5746 Loc = Lex.getLoc();
5747 if (parseTypeAndValue(V, PFS))
5748 return true;
5749 if (!isa<BasicBlock>(V))
5750 return error(Loc, "expected a basic block");
5751 BB = cast<BasicBlock>(V);
5752 return false;
5753 }
5754
5755 /// FunctionHeader
5756 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5757 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5758 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5759 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
parseFunctionHeader(Function * & Fn,bool IsDefine)5760 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5761 // parse the linkage.
5762 LocTy LinkageLoc = Lex.getLoc();
5763 unsigned Linkage;
5764 unsigned Visibility;
5765 unsigned DLLStorageClass;
5766 bool DSOLocal;
5767 AttrBuilder RetAttrs;
5768 unsigned CC;
5769 bool HasLinkage;
5770 Type *RetType = nullptr;
5771 LocTy RetTypeLoc = Lex.getLoc();
5772 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5773 DSOLocal) ||
5774 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5775 parseType(RetType, RetTypeLoc, true /*void allowed*/))
5776 return true;
5777
5778 // Verify that the linkage is ok.
5779 switch ((GlobalValue::LinkageTypes)Linkage) {
5780 case GlobalValue::ExternalLinkage:
5781 break; // always ok.
5782 case GlobalValue::ExternalWeakLinkage:
5783 if (IsDefine)
5784 return error(LinkageLoc, "invalid linkage for function definition");
5785 break;
5786 case GlobalValue::PrivateLinkage:
5787 case GlobalValue::InternalLinkage:
5788 case GlobalValue::AvailableExternallyLinkage:
5789 case GlobalValue::LinkOnceAnyLinkage:
5790 case GlobalValue::LinkOnceODRLinkage:
5791 case GlobalValue::WeakAnyLinkage:
5792 case GlobalValue::WeakODRLinkage:
5793 if (!IsDefine)
5794 return error(LinkageLoc, "invalid linkage for function declaration");
5795 break;
5796 case GlobalValue::AppendingLinkage:
5797 case GlobalValue::CommonLinkage:
5798 return error(LinkageLoc, "invalid function linkage type");
5799 }
5800
5801 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5802 return error(LinkageLoc,
5803 "symbol with local linkage must have default visibility");
5804
5805 if (!FunctionType::isValidReturnType(RetType))
5806 return error(RetTypeLoc, "invalid function return type");
5807
5808 LocTy NameLoc = Lex.getLoc();
5809
5810 std::string FunctionName;
5811 if (Lex.getKind() == lltok::GlobalVar) {
5812 FunctionName = Lex.getStrVal();
5813 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5814 unsigned NameID = Lex.getUIntVal();
5815
5816 if (NameID != NumberedVals.size())
5817 return tokError("function expected to be numbered '%" +
5818 Twine(NumberedVals.size()) + "'");
5819 } else {
5820 return tokError("expected function name");
5821 }
5822
5823 Lex.Lex();
5824
5825 if (Lex.getKind() != lltok::lparen)
5826 return tokError("expected '(' in function argument list");
5827
5828 SmallVector<ArgInfo, 8> ArgList;
5829 bool IsVarArg;
5830 AttrBuilder FuncAttrs;
5831 std::vector<unsigned> FwdRefAttrGrps;
5832 LocTy BuiltinLoc;
5833 std::string Section;
5834 std::string Partition;
5835 MaybeAlign Alignment;
5836 std::string GC;
5837 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5838 unsigned AddrSpace = 0;
5839 Constant *Prefix = nullptr;
5840 Constant *Prologue = nullptr;
5841 Constant *PersonalityFn = nullptr;
5842 Comdat *C;
5843
5844 if (parseArgumentList(ArgList, IsVarArg) ||
5845 parseOptionalUnnamedAddr(UnnamedAddr) ||
5846 parseOptionalProgramAddrSpace(AddrSpace) ||
5847 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5848 BuiltinLoc) ||
5849 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5850 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5851 parseOptionalComdat(FunctionName, C) ||
5852 parseOptionalAlignment(Alignment) ||
5853 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5854 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5855 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5856 (EatIfPresent(lltok::kw_personality) &&
5857 parseGlobalTypeAndValue(PersonalityFn)))
5858 return true;
5859
5860 if (FuncAttrs.contains(Attribute::Builtin))
5861 return error(BuiltinLoc, "'builtin' attribute not valid on function");
5862
5863 // If the alignment was parsed as an attribute, move to the alignment field.
5864 if (FuncAttrs.hasAlignmentAttr()) {
5865 Alignment = FuncAttrs.getAlignment();
5866 FuncAttrs.removeAttribute(Attribute::Alignment);
5867 }
5868
5869 // Okay, if we got here, the function is syntactically valid. Convert types
5870 // and do semantic checks.
5871 std::vector<Type*> ParamTypeList;
5872 SmallVector<AttributeSet, 8> Attrs;
5873
5874 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5875 ParamTypeList.push_back(ArgList[i].Ty);
5876 Attrs.push_back(ArgList[i].Attrs);
5877 }
5878
5879 AttributeList PAL =
5880 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5881 AttributeSet::get(Context, RetAttrs), Attrs);
5882
5883 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5884 return error(RetTypeLoc, "functions with 'sret' argument must return void");
5885
5886 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5887 PointerType *PFT = PointerType::get(FT, AddrSpace);
5888
5889 Fn = nullptr;
5890 if (!FunctionName.empty()) {
5891 // If this was a definition of a forward reference, remove the definition
5892 // from the forward reference table and fill in the forward ref.
5893 auto FRVI = ForwardRefVals.find(FunctionName);
5894 if (FRVI != ForwardRefVals.end()) {
5895 Fn = M->getFunction(FunctionName);
5896 if (!Fn)
5897 return error(FRVI->second.second, "invalid forward reference to "
5898 "function as global value!");
5899 if (Fn->getType() != PFT)
5900 return error(FRVI->second.second,
5901 "invalid forward reference to "
5902 "function '" +
5903 FunctionName +
5904 "' with wrong type: "
5905 "expected '" +
5906 getTypeString(PFT) + "' but was '" +
5907 getTypeString(Fn->getType()) + "'");
5908 ForwardRefVals.erase(FRVI);
5909 } else if ((Fn = M->getFunction(FunctionName))) {
5910 // Reject redefinitions.
5911 return error(NameLoc,
5912 "invalid redefinition of function '" + FunctionName + "'");
5913 } else if (M->getNamedValue(FunctionName)) {
5914 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5915 }
5916
5917 } else {
5918 // If this is a definition of a forward referenced function, make sure the
5919 // types agree.
5920 auto I = ForwardRefValIDs.find(NumberedVals.size());
5921 if (I != ForwardRefValIDs.end()) {
5922 Fn = cast<Function>(I->second.first);
5923 if (Fn->getType() != PFT)
5924 return error(NameLoc, "type of definition and forward reference of '@" +
5925 Twine(NumberedVals.size()) +
5926 "' disagree: "
5927 "expected '" +
5928 getTypeString(PFT) + "' but was '" +
5929 getTypeString(Fn->getType()) + "'");
5930 ForwardRefValIDs.erase(I);
5931 }
5932 }
5933
5934 if (!Fn)
5935 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5936 FunctionName, M);
5937 else // Move the forward-reference to the correct spot in the module.
5938 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5939
5940 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5941
5942 if (FunctionName.empty())
5943 NumberedVals.push_back(Fn);
5944
5945 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5946 maybeSetDSOLocal(DSOLocal, *Fn);
5947 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5948 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5949 Fn->setCallingConv(CC);
5950 Fn->setAttributes(PAL);
5951 Fn->setUnnamedAddr(UnnamedAddr);
5952 Fn->setAlignment(MaybeAlign(Alignment));
5953 Fn->setSection(Section);
5954 Fn->setPartition(Partition);
5955 Fn->setComdat(C);
5956 Fn->setPersonalityFn(PersonalityFn);
5957 if (!GC.empty()) Fn->setGC(GC);
5958 Fn->setPrefixData(Prefix);
5959 Fn->setPrologueData(Prologue);
5960 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5961
5962 // Add all of the arguments we parsed to the function.
5963 Function::arg_iterator ArgIt = Fn->arg_begin();
5964 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5965 // If the argument has a name, insert it into the argument symbol table.
5966 if (ArgList[i].Name.empty()) continue;
5967
5968 // Set the name, if it conflicted, it will be auto-renamed.
5969 ArgIt->setName(ArgList[i].Name);
5970
5971 if (ArgIt->getName() != ArgList[i].Name)
5972 return error(ArgList[i].Loc,
5973 "redefinition of argument '%" + ArgList[i].Name + "'");
5974 }
5975
5976 if (IsDefine)
5977 return false;
5978
5979 // Check the declaration has no block address forward references.
5980 ValID ID;
5981 if (FunctionName.empty()) {
5982 ID.Kind = ValID::t_GlobalID;
5983 ID.UIntVal = NumberedVals.size() - 1;
5984 } else {
5985 ID.Kind = ValID::t_GlobalName;
5986 ID.StrVal = FunctionName;
5987 }
5988 auto Blocks = ForwardRefBlockAddresses.find(ID);
5989 if (Blocks != ForwardRefBlockAddresses.end())
5990 return error(Blocks->first.Loc,
5991 "cannot take blockaddress inside a declaration");
5992 return false;
5993 }
5994
resolveForwardRefBlockAddresses()5995 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5996 ValID ID;
5997 if (FunctionNumber == -1) {
5998 ID.Kind = ValID::t_GlobalName;
5999 ID.StrVal = std::string(F.getName());
6000 } else {
6001 ID.Kind = ValID::t_GlobalID;
6002 ID.UIntVal = FunctionNumber;
6003 }
6004
6005 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6006 if (Blocks == P.ForwardRefBlockAddresses.end())
6007 return false;
6008
6009 for (const auto &I : Blocks->second) {
6010 const ValID &BBID = I.first;
6011 GlobalValue *GV = I.second;
6012
6013 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6014 "Expected local id or name");
6015 BasicBlock *BB;
6016 if (BBID.Kind == ValID::t_LocalName)
6017 BB = getBB(BBID.StrVal, BBID.Loc);
6018 else
6019 BB = getBB(BBID.UIntVal, BBID.Loc);
6020 if (!BB)
6021 return P.error(BBID.Loc, "referenced value is not a basic block");
6022
6023 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
6024 GV->eraseFromParent();
6025 }
6026
6027 P.ForwardRefBlockAddresses.erase(Blocks);
6028 return false;
6029 }
6030
6031 /// parseFunctionBody
6032 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
parseFunctionBody(Function & Fn)6033 bool LLParser::parseFunctionBody(Function &Fn) {
6034 if (Lex.getKind() != lltok::lbrace)
6035 return tokError("expected '{' in function body");
6036 Lex.Lex(); // eat the {.
6037
6038 int FunctionNumber = -1;
6039 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
6040
6041 PerFunctionState PFS(*this, Fn, FunctionNumber);
6042
6043 // Resolve block addresses and allow basic blocks to be forward-declared
6044 // within this function.
6045 if (PFS.resolveForwardRefBlockAddresses())
6046 return true;
6047 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
6048
6049 // We need at least one basic block.
6050 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6051 return tokError("function body requires at least one basic block");
6052
6053 while (Lex.getKind() != lltok::rbrace &&
6054 Lex.getKind() != lltok::kw_uselistorder)
6055 if (parseBasicBlock(PFS))
6056 return true;
6057
6058 while (Lex.getKind() != lltok::rbrace)
6059 if (parseUseListOrder(&PFS))
6060 return true;
6061
6062 // Eat the }.
6063 Lex.Lex();
6064
6065 // Verify function is ok.
6066 return PFS.finishFunction();
6067 }
6068
6069 /// parseBasicBlock
6070 /// ::= (LabelStr|LabelID)? Instruction*
parseBasicBlock(PerFunctionState & PFS)6071 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6072 // If this basic block starts out with a name, remember it.
6073 std::string Name;
6074 int NameID = -1;
6075 LocTy NameLoc = Lex.getLoc();
6076 if (Lex.getKind() == lltok::LabelStr) {
6077 Name = Lex.getStrVal();
6078 Lex.Lex();
6079 } else if (Lex.getKind() == lltok::LabelID) {
6080 NameID = Lex.getUIntVal();
6081 Lex.Lex();
6082 }
6083
6084 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6085 if (!BB)
6086 return true;
6087
6088 std::string NameStr;
6089
6090 // parse the instructions in this block until we get a terminator.
6091 Instruction *Inst;
6092 do {
6093 // This instruction may have three possibilities for a name: a) none
6094 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6095 LocTy NameLoc = Lex.getLoc();
6096 int NameID = -1;
6097 NameStr = "";
6098
6099 if (Lex.getKind() == lltok::LocalVarID) {
6100 NameID = Lex.getUIntVal();
6101 Lex.Lex();
6102 if (parseToken(lltok::equal, "expected '=' after instruction id"))
6103 return true;
6104 } else if (Lex.getKind() == lltok::LocalVar) {
6105 NameStr = Lex.getStrVal();
6106 Lex.Lex();
6107 if (parseToken(lltok::equal, "expected '=' after instruction name"))
6108 return true;
6109 }
6110
6111 switch (parseInstruction(Inst, BB, PFS)) {
6112 default:
6113 llvm_unreachable("Unknown parseInstruction result!");
6114 case InstError: return true;
6115 case InstNormal:
6116 BB->getInstList().push_back(Inst);
6117
6118 // With a normal result, we check to see if the instruction is followed by
6119 // a comma and metadata.
6120 if (EatIfPresent(lltok::comma))
6121 if (parseInstructionMetadata(*Inst))
6122 return true;
6123 break;
6124 case InstExtraComma:
6125 BB->getInstList().push_back(Inst);
6126
6127 // If the instruction parser ate an extra comma at the end of it, it
6128 // *must* be followed by metadata.
6129 if (parseInstructionMetadata(*Inst))
6130 return true;
6131 break;
6132 }
6133
6134 // Set the name on the instruction.
6135 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6136 return true;
6137 } while (!Inst->isTerminator());
6138
6139 return false;
6140 }
6141
6142 //===----------------------------------------------------------------------===//
6143 // Instruction Parsing.
6144 //===----------------------------------------------------------------------===//
6145
6146 /// parseInstruction - parse one of the many different instructions.
6147 ///
parseInstruction(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)6148 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6149 PerFunctionState &PFS) {
6150 lltok::Kind Token = Lex.getKind();
6151 if (Token == lltok::Eof)
6152 return tokError("found end of file when expecting more instructions");
6153 LocTy Loc = Lex.getLoc();
6154 unsigned KeywordVal = Lex.getUIntVal();
6155 Lex.Lex(); // Eat the keyword.
6156
6157 switch (Token) {
6158 default:
6159 return error(Loc, "expected instruction opcode");
6160 // Terminator Instructions.
6161 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6162 case lltok::kw_ret:
6163 return parseRet(Inst, BB, PFS);
6164 case lltok::kw_br:
6165 return parseBr(Inst, PFS);
6166 case lltok::kw_switch:
6167 return parseSwitch(Inst, PFS);
6168 case lltok::kw_indirectbr:
6169 return parseIndirectBr(Inst, PFS);
6170 case lltok::kw_invoke:
6171 return parseInvoke(Inst, PFS);
6172 case lltok::kw_resume:
6173 return parseResume(Inst, PFS);
6174 case lltok::kw_cleanupret:
6175 return parseCleanupRet(Inst, PFS);
6176 case lltok::kw_catchret:
6177 return parseCatchRet(Inst, PFS);
6178 case lltok::kw_catchswitch:
6179 return parseCatchSwitch(Inst, PFS);
6180 case lltok::kw_catchpad:
6181 return parseCatchPad(Inst, PFS);
6182 case lltok::kw_cleanuppad:
6183 return parseCleanupPad(Inst, PFS);
6184 case lltok::kw_callbr:
6185 return parseCallBr(Inst, PFS);
6186 // Unary Operators.
6187 case lltok::kw_fneg: {
6188 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6189 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6190 if (Res != 0)
6191 return Res;
6192 if (FMF.any())
6193 Inst->setFastMathFlags(FMF);
6194 return false;
6195 }
6196 // Binary Operators.
6197 case lltok::kw_add:
6198 case lltok::kw_sub:
6199 case lltok::kw_mul:
6200 case lltok::kw_shl: {
6201 bool NUW = EatIfPresent(lltok::kw_nuw);
6202 bool NSW = EatIfPresent(lltok::kw_nsw);
6203 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6204
6205 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6206 return true;
6207
6208 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6209 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6210 return false;
6211 }
6212 case lltok::kw_fadd:
6213 case lltok::kw_fsub:
6214 case lltok::kw_fmul:
6215 case lltok::kw_fdiv:
6216 case lltok::kw_frem: {
6217 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6218 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6219 if (Res != 0)
6220 return Res;
6221 if (FMF.any())
6222 Inst->setFastMathFlags(FMF);
6223 return 0;
6224 }
6225
6226 case lltok::kw_sdiv:
6227 case lltok::kw_udiv:
6228 case lltok::kw_lshr:
6229 case lltok::kw_ashr: {
6230 bool Exact = EatIfPresent(lltok::kw_exact);
6231
6232 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6233 return true;
6234 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6235 return false;
6236 }
6237
6238 case lltok::kw_urem:
6239 case lltok::kw_srem:
6240 return parseArithmetic(Inst, PFS, KeywordVal,
6241 /*IsFP*/ false);
6242 case lltok::kw_and:
6243 case lltok::kw_or:
6244 case lltok::kw_xor:
6245 return parseLogical(Inst, PFS, KeywordVal);
6246 case lltok::kw_icmp:
6247 return parseCompare(Inst, PFS, KeywordVal);
6248 case lltok::kw_fcmp: {
6249 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6250 int Res = parseCompare(Inst, PFS, KeywordVal);
6251 if (Res != 0)
6252 return Res;
6253 if (FMF.any())
6254 Inst->setFastMathFlags(FMF);
6255 return 0;
6256 }
6257
6258 // Casts.
6259 case lltok::kw_trunc:
6260 case lltok::kw_zext:
6261 case lltok::kw_sext:
6262 case lltok::kw_fptrunc:
6263 case lltok::kw_fpext:
6264 case lltok::kw_bitcast:
6265 case lltok::kw_addrspacecast:
6266 case lltok::kw_uitofp:
6267 case lltok::kw_sitofp:
6268 case lltok::kw_fptoui:
6269 case lltok::kw_fptosi:
6270 case lltok::kw_inttoptr:
6271 case lltok::kw_ptrtoint:
6272 return parseCast(Inst, PFS, KeywordVal);
6273 // Other.
6274 case lltok::kw_select: {
6275 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6276 int Res = parseSelect(Inst, PFS);
6277 if (Res != 0)
6278 return Res;
6279 if (FMF.any()) {
6280 if (!isa<FPMathOperator>(Inst))
6281 return error(Loc, "fast-math-flags specified for select without "
6282 "floating-point scalar or vector return type");
6283 Inst->setFastMathFlags(FMF);
6284 }
6285 return 0;
6286 }
6287 case lltok::kw_va_arg:
6288 return parseVAArg(Inst, PFS);
6289 case lltok::kw_extractelement:
6290 return parseExtractElement(Inst, PFS);
6291 case lltok::kw_insertelement:
6292 return parseInsertElement(Inst, PFS);
6293 case lltok::kw_shufflevector:
6294 return parseShuffleVector(Inst, PFS);
6295 case lltok::kw_phi: {
6296 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6297 int Res = parsePHI(Inst, PFS);
6298 if (Res != 0)
6299 return Res;
6300 if (FMF.any()) {
6301 if (!isa<FPMathOperator>(Inst))
6302 return error(Loc, "fast-math-flags specified for phi without "
6303 "floating-point scalar or vector return type");
6304 Inst->setFastMathFlags(FMF);
6305 }
6306 return 0;
6307 }
6308 case lltok::kw_landingpad:
6309 return parseLandingPad(Inst, PFS);
6310 case lltok::kw_freeze:
6311 return parseFreeze(Inst, PFS);
6312 // Call.
6313 case lltok::kw_call:
6314 return parseCall(Inst, PFS, CallInst::TCK_None);
6315 case lltok::kw_tail:
6316 return parseCall(Inst, PFS, CallInst::TCK_Tail);
6317 case lltok::kw_musttail:
6318 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6319 case lltok::kw_notail:
6320 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6321 // Memory.
6322 case lltok::kw_alloca:
6323 return parseAlloc(Inst, PFS);
6324 case lltok::kw_load:
6325 return parseLoad(Inst, PFS);
6326 case lltok::kw_store:
6327 return parseStore(Inst, PFS);
6328 case lltok::kw_cmpxchg:
6329 return parseCmpXchg(Inst, PFS);
6330 case lltok::kw_atomicrmw:
6331 return parseAtomicRMW(Inst, PFS);
6332 case lltok::kw_fence:
6333 return parseFence(Inst, PFS);
6334 case lltok::kw_getelementptr:
6335 return parseGetElementPtr(Inst, PFS);
6336 case lltok::kw_extractvalue:
6337 return parseExtractValue(Inst, PFS);
6338 case lltok::kw_insertvalue:
6339 return parseInsertValue(Inst, PFS);
6340 }
6341 }
6342
6343 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
parseCmpPredicate(unsigned & P,unsigned Opc)6344 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6345 if (Opc == Instruction::FCmp) {
6346 switch (Lex.getKind()) {
6347 default:
6348 return tokError("expected fcmp predicate (e.g. 'oeq')");
6349 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6350 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6351 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6352 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6353 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6354 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6355 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6356 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6357 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6358 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6359 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6360 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6361 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6362 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6363 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6364 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6365 }
6366 } else {
6367 switch (Lex.getKind()) {
6368 default:
6369 return tokError("expected icmp predicate (e.g. 'eq')");
6370 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
6371 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
6372 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6373 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6374 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6375 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6376 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6377 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6378 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6379 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6380 }
6381 }
6382 Lex.Lex();
6383 return false;
6384 }
6385
6386 //===----------------------------------------------------------------------===//
6387 // Terminator Instructions.
6388 //===----------------------------------------------------------------------===//
6389
6390 /// parseRet - parse a return instruction.
6391 /// ::= 'ret' void (',' !dbg, !1)*
6392 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
parseRet(Instruction * & Inst,BasicBlock * BB,PerFunctionState & PFS)6393 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6394 PerFunctionState &PFS) {
6395 SMLoc TypeLoc = Lex.getLoc();
6396 Type *Ty = nullptr;
6397 if (parseType(Ty, true /*void allowed*/))
6398 return true;
6399
6400 Type *ResType = PFS.getFunction().getReturnType();
6401
6402 if (Ty->isVoidTy()) {
6403 if (!ResType->isVoidTy())
6404 return error(TypeLoc, "value doesn't match function result type '" +
6405 getTypeString(ResType) + "'");
6406
6407 Inst = ReturnInst::Create(Context);
6408 return false;
6409 }
6410
6411 Value *RV;
6412 if (parseValue(Ty, RV, PFS))
6413 return true;
6414
6415 if (ResType != RV->getType())
6416 return error(TypeLoc, "value doesn't match function result type '" +
6417 getTypeString(ResType) + "'");
6418
6419 Inst = ReturnInst::Create(Context, RV);
6420 return false;
6421 }
6422
6423 /// parseBr
6424 /// ::= 'br' TypeAndValue
6425 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseBr(Instruction * & Inst,PerFunctionState & PFS)6426 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6427 LocTy Loc, Loc2;
6428 Value *Op0;
6429 BasicBlock *Op1, *Op2;
6430 if (parseTypeAndValue(Op0, Loc, PFS))
6431 return true;
6432
6433 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6434 Inst = BranchInst::Create(BB);
6435 return false;
6436 }
6437
6438 if (Op0->getType() != Type::getInt1Ty(Context))
6439 return error(Loc, "branch condition must have 'i1' type");
6440
6441 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6442 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6443 parseToken(lltok::comma, "expected ',' after true destination") ||
6444 parseTypeAndBasicBlock(Op2, Loc2, PFS))
6445 return true;
6446
6447 Inst = BranchInst::Create(Op1, Op2, Op0);
6448 return false;
6449 }
6450
6451 /// parseSwitch
6452 /// Instruction
6453 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6454 /// JumpTable
6455 /// ::= (TypeAndValue ',' TypeAndValue)*
parseSwitch(Instruction * & Inst,PerFunctionState & PFS)6456 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6457 LocTy CondLoc, BBLoc;
6458 Value *Cond;
6459 BasicBlock *DefaultBB;
6460 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6461 parseToken(lltok::comma, "expected ',' after switch condition") ||
6462 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6463 parseToken(lltok::lsquare, "expected '[' with switch table"))
6464 return true;
6465
6466 if (!Cond->getType()->isIntegerTy())
6467 return error(CondLoc, "switch condition must have integer type");
6468
6469 // parse the jump table pairs.
6470 SmallPtrSet<Value*, 32> SeenCases;
6471 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6472 while (Lex.getKind() != lltok::rsquare) {
6473 Value *Constant;
6474 BasicBlock *DestBB;
6475
6476 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6477 parseToken(lltok::comma, "expected ',' after case value") ||
6478 parseTypeAndBasicBlock(DestBB, PFS))
6479 return true;
6480
6481 if (!SeenCases.insert(Constant).second)
6482 return error(CondLoc, "duplicate case value in switch");
6483 if (!isa<ConstantInt>(Constant))
6484 return error(CondLoc, "case value is not a constant integer");
6485
6486 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6487 }
6488
6489 Lex.Lex(); // Eat the ']'.
6490
6491 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6492 for (unsigned i = 0, e = Table.size(); i != e; ++i)
6493 SI->addCase(Table[i].first, Table[i].second);
6494 Inst = SI;
6495 return false;
6496 }
6497
6498 /// parseIndirectBr
6499 /// Instruction
6500 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
parseIndirectBr(Instruction * & Inst,PerFunctionState & PFS)6501 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6502 LocTy AddrLoc;
6503 Value *Address;
6504 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6505 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6506 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6507 return true;
6508
6509 if (!Address->getType()->isPointerTy())
6510 return error(AddrLoc, "indirectbr address must have pointer type");
6511
6512 // parse the destination list.
6513 SmallVector<BasicBlock*, 16> DestList;
6514
6515 if (Lex.getKind() != lltok::rsquare) {
6516 BasicBlock *DestBB;
6517 if (parseTypeAndBasicBlock(DestBB, PFS))
6518 return true;
6519 DestList.push_back(DestBB);
6520
6521 while (EatIfPresent(lltok::comma)) {
6522 if (parseTypeAndBasicBlock(DestBB, PFS))
6523 return true;
6524 DestList.push_back(DestBB);
6525 }
6526 }
6527
6528 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6529 return true;
6530
6531 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6532 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6533 IBI->addDestination(DestList[i]);
6534 Inst = IBI;
6535 return false;
6536 }
6537
6538 /// parseInvoke
6539 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6540 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
parseInvoke(Instruction * & Inst,PerFunctionState & PFS)6541 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6542 LocTy CallLoc = Lex.getLoc();
6543 AttrBuilder RetAttrs, FnAttrs;
6544 std::vector<unsigned> FwdRefAttrGrps;
6545 LocTy NoBuiltinLoc;
6546 unsigned CC;
6547 unsigned InvokeAddrSpace;
6548 Type *RetType = nullptr;
6549 LocTy RetTypeLoc;
6550 ValID CalleeID;
6551 SmallVector<ParamInfo, 16> ArgList;
6552 SmallVector<OperandBundleDef, 2> BundleList;
6553
6554 BasicBlock *NormalBB, *UnwindBB;
6555 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6556 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6557 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6558 parseValID(CalleeID) || parseParameterList(ArgList, PFS) ||
6559 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6560 NoBuiltinLoc) ||
6561 parseOptionalOperandBundles(BundleList, PFS) ||
6562 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6563 parseTypeAndBasicBlock(NormalBB, PFS) ||
6564 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6565 parseTypeAndBasicBlock(UnwindBB, PFS))
6566 return true;
6567
6568 // If RetType is a non-function pointer type, then this is the short syntax
6569 // for the call, which means that RetType is just the return type. Infer the
6570 // rest of the function argument types from the arguments that are present.
6571 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6572 if (!Ty) {
6573 // Pull out the types of all of the arguments...
6574 std::vector<Type*> ParamTypes;
6575 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6576 ParamTypes.push_back(ArgList[i].V->getType());
6577
6578 if (!FunctionType::isValidReturnType(RetType))
6579 return error(RetTypeLoc, "Invalid result type for LLVM function");
6580
6581 Ty = FunctionType::get(RetType, ParamTypes, false);
6582 }
6583
6584 CalleeID.FTy = Ty;
6585
6586 // Look up the callee.
6587 Value *Callee;
6588 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6589 Callee, &PFS, /*IsCall=*/true))
6590 return true;
6591
6592 // Set up the Attribute for the function.
6593 SmallVector<Value *, 8> Args;
6594 SmallVector<AttributeSet, 8> ArgAttrs;
6595
6596 // Loop through FunctionType's arguments and ensure they are specified
6597 // correctly. Also, gather any parameter attributes.
6598 FunctionType::param_iterator I = Ty->param_begin();
6599 FunctionType::param_iterator E = Ty->param_end();
6600 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6601 Type *ExpectedTy = nullptr;
6602 if (I != E) {
6603 ExpectedTy = *I++;
6604 } else if (!Ty->isVarArg()) {
6605 return error(ArgList[i].Loc, "too many arguments specified");
6606 }
6607
6608 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6609 return error(ArgList[i].Loc, "argument is not of expected type '" +
6610 getTypeString(ExpectedTy) + "'");
6611 Args.push_back(ArgList[i].V);
6612 ArgAttrs.push_back(ArgList[i].Attrs);
6613 }
6614
6615 if (I != E)
6616 return error(CallLoc, "not enough parameters specified for call");
6617
6618 if (FnAttrs.hasAlignmentAttr())
6619 return error(CallLoc, "invoke instructions may not have an alignment");
6620
6621 // Finish off the Attribute and check them
6622 AttributeList PAL =
6623 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6624 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6625
6626 InvokeInst *II =
6627 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6628 II->setCallingConv(CC);
6629 II->setAttributes(PAL);
6630 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6631 Inst = II;
6632 return false;
6633 }
6634
6635 /// parseResume
6636 /// ::= 'resume' TypeAndValue
parseResume(Instruction * & Inst,PerFunctionState & PFS)6637 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6638 Value *Exn; LocTy ExnLoc;
6639 if (parseTypeAndValue(Exn, ExnLoc, PFS))
6640 return true;
6641
6642 ResumeInst *RI = ResumeInst::Create(Exn);
6643 Inst = RI;
6644 return false;
6645 }
6646
parseExceptionArgs(SmallVectorImpl<Value * > & Args,PerFunctionState & PFS)6647 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6648 PerFunctionState &PFS) {
6649 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6650 return true;
6651
6652 while (Lex.getKind() != lltok::rsquare) {
6653 // If this isn't the first argument, we need a comma.
6654 if (!Args.empty() &&
6655 parseToken(lltok::comma, "expected ',' in argument list"))
6656 return true;
6657
6658 // parse the argument.
6659 LocTy ArgLoc;
6660 Type *ArgTy = nullptr;
6661 if (parseType(ArgTy, ArgLoc))
6662 return true;
6663
6664 Value *V;
6665 if (ArgTy->isMetadataTy()) {
6666 if (parseMetadataAsValue(V, PFS))
6667 return true;
6668 } else {
6669 if (parseValue(ArgTy, V, PFS))
6670 return true;
6671 }
6672 Args.push_back(V);
6673 }
6674
6675 Lex.Lex(); // Lex the ']'.
6676 return false;
6677 }
6678
6679 /// parseCleanupRet
6680 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
parseCleanupRet(Instruction * & Inst,PerFunctionState & PFS)6681 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6682 Value *CleanupPad = nullptr;
6683
6684 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6685 return true;
6686
6687 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6688 return true;
6689
6690 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6691 return true;
6692
6693 BasicBlock *UnwindBB = nullptr;
6694 if (Lex.getKind() == lltok::kw_to) {
6695 Lex.Lex();
6696 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6697 return true;
6698 } else {
6699 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6700 return true;
6701 }
6702 }
6703
6704 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6705 return false;
6706 }
6707
6708 /// parseCatchRet
6709 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
parseCatchRet(Instruction * & Inst,PerFunctionState & PFS)6710 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6711 Value *CatchPad = nullptr;
6712
6713 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6714 return true;
6715
6716 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6717 return true;
6718
6719 BasicBlock *BB;
6720 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6721 parseTypeAndBasicBlock(BB, PFS))
6722 return true;
6723
6724 Inst = CatchReturnInst::Create(CatchPad, BB);
6725 return false;
6726 }
6727
6728 /// parseCatchSwitch
6729 /// ::= 'catchswitch' within Parent
parseCatchSwitch(Instruction * & Inst,PerFunctionState & PFS)6730 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6731 Value *ParentPad;
6732
6733 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6734 return true;
6735
6736 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6737 Lex.getKind() != lltok::LocalVarID)
6738 return tokError("expected scope value for catchswitch");
6739
6740 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6741 return true;
6742
6743 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6744 return true;
6745
6746 SmallVector<BasicBlock *, 32> Table;
6747 do {
6748 BasicBlock *DestBB;
6749 if (parseTypeAndBasicBlock(DestBB, PFS))
6750 return true;
6751 Table.push_back(DestBB);
6752 } while (EatIfPresent(lltok::comma));
6753
6754 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6755 return true;
6756
6757 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6758 return true;
6759
6760 BasicBlock *UnwindBB = nullptr;
6761 if (EatIfPresent(lltok::kw_to)) {
6762 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6763 return true;
6764 } else {
6765 if (parseTypeAndBasicBlock(UnwindBB, PFS))
6766 return true;
6767 }
6768
6769 auto *CatchSwitch =
6770 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6771 for (BasicBlock *DestBB : Table)
6772 CatchSwitch->addHandler(DestBB);
6773 Inst = CatchSwitch;
6774 return false;
6775 }
6776
6777 /// parseCatchPad
6778 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
parseCatchPad(Instruction * & Inst,PerFunctionState & PFS)6779 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6780 Value *CatchSwitch = nullptr;
6781
6782 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6783 return true;
6784
6785 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6786 return tokError("expected scope value for catchpad");
6787
6788 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6789 return true;
6790
6791 SmallVector<Value *, 8> Args;
6792 if (parseExceptionArgs(Args, PFS))
6793 return true;
6794
6795 Inst = CatchPadInst::Create(CatchSwitch, Args);
6796 return false;
6797 }
6798
6799 /// parseCleanupPad
6800 /// ::= 'cleanuppad' within Parent ParamList
parseCleanupPad(Instruction * & Inst,PerFunctionState & PFS)6801 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6802 Value *ParentPad = nullptr;
6803
6804 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6805 return true;
6806
6807 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6808 Lex.getKind() != lltok::LocalVarID)
6809 return tokError("expected scope value for cleanuppad");
6810
6811 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6812 return true;
6813
6814 SmallVector<Value *, 8> Args;
6815 if (parseExceptionArgs(Args, PFS))
6816 return true;
6817
6818 Inst = CleanupPadInst::Create(ParentPad, Args);
6819 return false;
6820 }
6821
6822 //===----------------------------------------------------------------------===//
6823 // Unary Operators.
6824 //===----------------------------------------------------------------------===//
6825
6826 /// parseUnaryOp
6827 /// ::= UnaryOp TypeAndValue ',' Value
6828 ///
6829 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6830 /// operand is allowed.
parseUnaryOp(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc,bool IsFP)6831 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6832 unsigned Opc, bool IsFP) {
6833 LocTy Loc; Value *LHS;
6834 if (parseTypeAndValue(LHS, Loc, PFS))
6835 return true;
6836
6837 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6838 : LHS->getType()->isIntOrIntVectorTy();
6839
6840 if (!Valid)
6841 return error(Loc, "invalid operand type for instruction");
6842
6843 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6844 return false;
6845 }
6846
6847 /// parseCallBr
6848 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6849 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6850 /// '[' LabelList ']'
parseCallBr(Instruction * & Inst,PerFunctionState & PFS)6851 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6852 LocTy CallLoc = Lex.getLoc();
6853 AttrBuilder RetAttrs, FnAttrs;
6854 std::vector<unsigned> FwdRefAttrGrps;
6855 LocTy NoBuiltinLoc;
6856 unsigned CC;
6857 Type *RetType = nullptr;
6858 LocTy RetTypeLoc;
6859 ValID CalleeID;
6860 SmallVector<ParamInfo, 16> ArgList;
6861 SmallVector<OperandBundleDef, 2> BundleList;
6862
6863 BasicBlock *DefaultDest;
6864 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6865 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6866 parseValID(CalleeID) || parseParameterList(ArgList, PFS) ||
6867 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6868 NoBuiltinLoc) ||
6869 parseOptionalOperandBundles(BundleList, PFS) ||
6870 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6871 parseTypeAndBasicBlock(DefaultDest, PFS) ||
6872 parseToken(lltok::lsquare, "expected '[' in callbr"))
6873 return true;
6874
6875 // parse the destination list.
6876 SmallVector<BasicBlock *, 16> IndirectDests;
6877
6878 if (Lex.getKind() != lltok::rsquare) {
6879 BasicBlock *DestBB;
6880 if (parseTypeAndBasicBlock(DestBB, PFS))
6881 return true;
6882 IndirectDests.push_back(DestBB);
6883
6884 while (EatIfPresent(lltok::comma)) {
6885 if (parseTypeAndBasicBlock(DestBB, PFS))
6886 return true;
6887 IndirectDests.push_back(DestBB);
6888 }
6889 }
6890
6891 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6892 return true;
6893
6894 // If RetType is a non-function pointer type, then this is the short syntax
6895 // for the call, which means that RetType is just the return type. Infer the
6896 // rest of the function argument types from the arguments that are present.
6897 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6898 if (!Ty) {
6899 // Pull out the types of all of the arguments...
6900 std::vector<Type *> ParamTypes;
6901 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6902 ParamTypes.push_back(ArgList[i].V->getType());
6903
6904 if (!FunctionType::isValidReturnType(RetType))
6905 return error(RetTypeLoc, "Invalid result type for LLVM function");
6906
6907 Ty = FunctionType::get(RetType, ParamTypes, false);
6908 }
6909
6910 CalleeID.FTy = Ty;
6911
6912 // Look up the callee.
6913 Value *Callee;
6914 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6915 /*IsCall=*/true))
6916 return true;
6917
6918 // Set up the Attribute for the function.
6919 SmallVector<Value *, 8> Args;
6920 SmallVector<AttributeSet, 8> ArgAttrs;
6921
6922 // Loop through FunctionType's arguments and ensure they are specified
6923 // correctly. Also, gather any parameter attributes.
6924 FunctionType::param_iterator I = Ty->param_begin();
6925 FunctionType::param_iterator E = Ty->param_end();
6926 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6927 Type *ExpectedTy = nullptr;
6928 if (I != E) {
6929 ExpectedTy = *I++;
6930 } else if (!Ty->isVarArg()) {
6931 return error(ArgList[i].Loc, "too many arguments specified");
6932 }
6933
6934 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6935 return error(ArgList[i].Loc, "argument is not of expected type '" +
6936 getTypeString(ExpectedTy) + "'");
6937 Args.push_back(ArgList[i].V);
6938 ArgAttrs.push_back(ArgList[i].Attrs);
6939 }
6940
6941 if (I != E)
6942 return error(CallLoc, "not enough parameters specified for call");
6943
6944 if (FnAttrs.hasAlignmentAttr())
6945 return error(CallLoc, "callbr instructions may not have an alignment");
6946
6947 // Finish off the Attribute and check them
6948 AttributeList PAL =
6949 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6950 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6951
6952 CallBrInst *CBI =
6953 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6954 BundleList);
6955 CBI->setCallingConv(CC);
6956 CBI->setAttributes(PAL);
6957 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6958 Inst = CBI;
6959 return false;
6960 }
6961
6962 //===----------------------------------------------------------------------===//
6963 // Binary Operators.
6964 //===----------------------------------------------------------------------===//
6965
6966 /// parseArithmetic
6967 /// ::= ArithmeticOps TypeAndValue ',' Value
6968 ///
6969 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6970 /// operand is allowed.
parseArithmetic(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc,bool IsFP)6971 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6972 unsigned Opc, bool IsFP) {
6973 LocTy Loc; Value *LHS, *RHS;
6974 if (parseTypeAndValue(LHS, Loc, PFS) ||
6975 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6976 parseValue(LHS->getType(), RHS, PFS))
6977 return true;
6978
6979 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6980 : LHS->getType()->isIntOrIntVectorTy();
6981
6982 if (!Valid)
6983 return error(Loc, "invalid operand type for instruction");
6984
6985 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6986 return false;
6987 }
6988
6989 /// parseLogical
6990 /// ::= ArithmeticOps TypeAndValue ',' Value {
parseLogical(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)6991 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6992 unsigned Opc) {
6993 LocTy Loc; Value *LHS, *RHS;
6994 if (parseTypeAndValue(LHS, Loc, PFS) ||
6995 parseToken(lltok::comma, "expected ',' in logical operation") ||
6996 parseValue(LHS->getType(), RHS, PFS))
6997 return true;
6998
6999 if (!LHS->getType()->isIntOrIntVectorTy())
7000 return error(Loc,
7001 "instruction requires integer or integer vector operands");
7002
7003 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7004 return false;
7005 }
7006
7007 /// parseCompare
7008 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
7009 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
parseCompare(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)7010 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7011 unsigned Opc) {
7012 // parse the integer/fp comparison predicate.
7013 LocTy Loc;
7014 unsigned Pred;
7015 Value *LHS, *RHS;
7016 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7017 parseToken(lltok::comma, "expected ',' after compare value") ||
7018 parseValue(LHS->getType(), RHS, PFS))
7019 return true;
7020
7021 if (Opc == Instruction::FCmp) {
7022 if (!LHS->getType()->isFPOrFPVectorTy())
7023 return error(Loc, "fcmp requires floating point operands");
7024 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7025 } else {
7026 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7027 if (!LHS->getType()->isIntOrIntVectorTy() &&
7028 !LHS->getType()->isPtrOrPtrVectorTy())
7029 return error(Loc, "icmp requires integer operands");
7030 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7031 }
7032 return false;
7033 }
7034
7035 //===----------------------------------------------------------------------===//
7036 // Other Instructions.
7037 //===----------------------------------------------------------------------===//
7038
7039 /// parseCast
7040 /// ::= CastOpc TypeAndValue 'to' Type
parseCast(Instruction * & Inst,PerFunctionState & PFS,unsigned Opc)7041 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7042 unsigned Opc) {
7043 LocTy Loc;
7044 Value *Op;
7045 Type *DestTy = nullptr;
7046 if (parseTypeAndValue(Op, Loc, PFS) ||
7047 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7048 parseType(DestTy))
7049 return true;
7050
7051 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7052 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
7053 return error(Loc, "invalid cast opcode for cast from '" +
7054 getTypeString(Op->getType()) + "' to '" +
7055 getTypeString(DestTy) + "'");
7056 }
7057 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7058 return false;
7059 }
7060
7061 /// parseSelect
7062 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseSelect(Instruction * & Inst,PerFunctionState & PFS)7063 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7064 LocTy Loc;
7065 Value *Op0, *Op1, *Op2;
7066 if (parseTypeAndValue(Op0, Loc, PFS) ||
7067 parseToken(lltok::comma, "expected ',' after select condition") ||
7068 parseTypeAndValue(Op1, PFS) ||
7069 parseToken(lltok::comma, "expected ',' after select value") ||
7070 parseTypeAndValue(Op2, PFS))
7071 return true;
7072
7073 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7074 return error(Loc, Reason);
7075
7076 Inst = SelectInst::Create(Op0, Op1, Op2);
7077 return false;
7078 }
7079
7080 /// parseVAArg
7081 /// ::= 'va_arg' TypeAndValue ',' Type
parseVAArg(Instruction * & Inst,PerFunctionState & PFS)7082 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7083 Value *Op;
7084 Type *EltTy = nullptr;
7085 LocTy TypeLoc;
7086 if (parseTypeAndValue(Op, PFS) ||
7087 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7088 parseType(EltTy, TypeLoc))
7089 return true;
7090
7091 if (!EltTy->isFirstClassType())
7092 return error(TypeLoc, "va_arg requires operand with first class type");
7093
7094 Inst = new VAArgInst(Op, EltTy);
7095 return false;
7096 }
7097
7098 /// parseExtractElement
7099 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
parseExtractElement(Instruction * & Inst,PerFunctionState & PFS)7100 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7101 LocTy Loc;
7102 Value *Op0, *Op1;
7103 if (parseTypeAndValue(Op0, Loc, PFS) ||
7104 parseToken(lltok::comma, "expected ',' after extract value") ||
7105 parseTypeAndValue(Op1, PFS))
7106 return true;
7107
7108 if (!ExtractElementInst::isValidOperands(Op0, Op1))
7109 return error(Loc, "invalid extractelement operands");
7110
7111 Inst = ExtractElementInst::Create(Op0, Op1);
7112 return false;
7113 }
7114
7115 /// parseInsertElement
7116 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseInsertElement(Instruction * & Inst,PerFunctionState & PFS)7117 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7118 LocTy Loc;
7119 Value *Op0, *Op1, *Op2;
7120 if (parseTypeAndValue(Op0, Loc, PFS) ||
7121 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7122 parseTypeAndValue(Op1, PFS) ||
7123 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7124 parseTypeAndValue(Op2, PFS))
7125 return true;
7126
7127 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7128 return error(Loc, "invalid insertelement operands");
7129
7130 Inst = InsertElementInst::Create(Op0, Op1, Op2);
7131 return false;
7132 }
7133
7134 /// parseShuffleVector
7135 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
parseShuffleVector(Instruction * & Inst,PerFunctionState & PFS)7136 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7137 LocTy Loc;
7138 Value *Op0, *Op1, *Op2;
7139 if (parseTypeAndValue(Op0, Loc, PFS) ||
7140 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7141 parseTypeAndValue(Op1, PFS) ||
7142 parseToken(lltok::comma, "expected ',' after shuffle value") ||
7143 parseTypeAndValue(Op2, PFS))
7144 return true;
7145
7146 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7147 return error(Loc, "invalid shufflevector operands");
7148
7149 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7150 return false;
7151 }
7152
7153 /// parsePHI
7154 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
parsePHI(Instruction * & Inst,PerFunctionState & PFS)7155 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7156 Type *Ty = nullptr; LocTy TypeLoc;
7157 Value *Op0, *Op1;
7158
7159 if (parseType(Ty, TypeLoc) ||
7160 parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7161 parseValue(Ty, Op0, PFS) ||
7162 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7163 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7164 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7165 return true;
7166
7167 bool AteExtraComma = false;
7168 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
7169
7170 while (true) {
7171 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7172
7173 if (!EatIfPresent(lltok::comma))
7174 break;
7175
7176 if (Lex.getKind() == lltok::MetadataVar) {
7177 AteExtraComma = true;
7178 break;
7179 }
7180
7181 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7182 parseValue(Ty, Op0, PFS) ||
7183 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7184 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7185 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7186 return true;
7187 }
7188
7189 if (!Ty->isFirstClassType())
7190 return error(TypeLoc, "phi node must have first class type");
7191
7192 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7193 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7194 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7195 Inst = PN;
7196 return AteExtraComma ? InstExtraComma : InstNormal;
7197 }
7198
7199 /// parseLandingPad
7200 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7201 /// Clause
7202 /// ::= 'catch' TypeAndValue
7203 /// ::= 'filter'
7204 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
parseLandingPad(Instruction * & Inst,PerFunctionState & PFS)7205 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7206 Type *Ty = nullptr; LocTy TyLoc;
7207
7208 if (parseType(Ty, TyLoc))
7209 return true;
7210
7211 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7212 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7213
7214 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7215 LandingPadInst::ClauseType CT;
7216 if (EatIfPresent(lltok::kw_catch))
7217 CT = LandingPadInst::Catch;
7218 else if (EatIfPresent(lltok::kw_filter))
7219 CT = LandingPadInst::Filter;
7220 else
7221 return tokError("expected 'catch' or 'filter' clause type");
7222
7223 Value *V;
7224 LocTy VLoc;
7225 if (parseTypeAndValue(V, VLoc, PFS))
7226 return true;
7227
7228 // A 'catch' type expects a non-array constant. A filter clause expects an
7229 // array constant.
7230 if (CT == LandingPadInst::Catch) {
7231 if (isa<ArrayType>(V->getType()))
7232 error(VLoc, "'catch' clause has an invalid type");
7233 } else {
7234 if (!isa<ArrayType>(V->getType()))
7235 error(VLoc, "'filter' clause has an invalid type");
7236 }
7237
7238 Constant *CV = dyn_cast<Constant>(V);
7239 if (!CV)
7240 return error(VLoc, "clause argument must be a constant");
7241 LP->addClause(CV);
7242 }
7243
7244 Inst = LP.release();
7245 return false;
7246 }
7247
7248 /// parseFreeze
7249 /// ::= 'freeze' Type Value
parseFreeze(Instruction * & Inst,PerFunctionState & PFS)7250 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7251 LocTy Loc;
7252 Value *Op;
7253 if (parseTypeAndValue(Op, Loc, PFS))
7254 return true;
7255
7256 Inst = new FreezeInst(Op);
7257 return false;
7258 }
7259
7260 /// parseCall
7261 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7262 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7263 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7264 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7265 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7266 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7267 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7268 /// OptionalAttrs Type Value ParameterList OptionalAttrs
parseCall(Instruction * & Inst,PerFunctionState & PFS,CallInst::TailCallKind TCK)7269 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7270 CallInst::TailCallKind TCK) {
7271 AttrBuilder RetAttrs, FnAttrs;
7272 std::vector<unsigned> FwdRefAttrGrps;
7273 LocTy BuiltinLoc;
7274 unsigned CallAddrSpace;
7275 unsigned CC;
7276 Type *RetType = nullptr;
7277 LocTy RetTypeLoc;
7278 ValID CalleeID;
7279 SmallVector<ParamInfo, 16> ArgList;
7280 SmallVector<OperandBundleDef, 2> BundleList;
7281 LocTy CallLoc = Lex.getLoc();
7282
7283 if (TCK != CallInst::TCK_None &&
7284 parseToken(lltok::kw_call,
7285 "expected 'tail call', 'musttail call', or 'notail call'"))
7286 return true;
7287
7288 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7289
7290 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7291 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7292 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7293 parseValID(CalleeID) ||
7294 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7295 PFS.getFunction().isVarArg()) ||
7296 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7297 parseOptionalOperandBundles(BundleList, PFS))
7298 return true;
7299
7300 // If RetType is a non-function pointer type, then this is the short syntax
7301 // for the call, which means that RetType is just the return type. Infer the
7302 // rest of the function argument types from the arguments that are present.
7303 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7304 if (!Ty) {
7305 // Pull out the types of all of the arguments...
7306 std::vector<Type*> ParamTypes;
7307 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7308 ParamTypes.push_back(ArgList[i].V->getType());
7309
7310 if (!FunctionType::isValidReturnType(RetType))
7311 return error(RetTypeLoc, "Invalid result type for LLVM function");
7312
7313 Ty = FunctionType::get(RetType, ParamTypes, false);
7314 }
7315
7316 CalleeID.FTy = Ty;
7317
7318 // Look up the callee.
7319 Value *Callee;
7320 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7321 &PFS, /*IsCall=*/true))
7322 return true;
7323
7324 // Set up the Attribute for the function.
7325 SmallVector<AttributeSet, 8> Attrs;
7326
7327 SmallVector<Value*, 8> Args;
7328
7329 // Loop through FunctionType's arguments and ensure they are specified
7330 // correctly. Also, gather any parameter attributes.
7331 FunctionType::param_iterator I = Ty->param_begin();
7332 FunctionType::param_iterator E = Ty->param_end();
7333 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7334 Type *ExpectedTy = nullptr;
7335 if (I != E) {
7336 ExpectedTy = *I++;
7337 } else if (!Ty->isVarArg()) {
7338 return error(ArgList[i].Loc, "too many arguments specified");
7339 }
7340
7341 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7342 return error(ArgList[i].Loc, "argument is not of expected type '" +
7343 getTypeString(ExpectedTy) + "'");
7344 Args.push_back(ArgList[i].V);
7345 Attrs.push_back(ArgList[i].Attrs);
7346 }
7347
7348 if (I != E)
7349 return error(CallLoc, "not enough parameters specified for call");
7350
7351 if (FnAttrs.hasAlignmentAttr())
7352 return error(CallLoc, "call instructions may not have an alignment");
7353
7354 // Finish off the Attribute and check them
7355 AttributeList PAL =
7356 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7357 AttributeSet::get(Context, RetAttrs), Attrs);
7358
7359 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7360 CI->setTailCallKind(TCK);
7361 CI->setCallingConv(CC);
7362 if (FMF.any()) {
7363 if (!isa<FPMathOperator>(CI)) {
7364 CI->deleteValue();
7365 return error(CallLoc, "fast-math-flags specified for call without "
7366 "floating-point scalar or vector return type");
7367 }
7368 CI->setFastMathFlags(FMF);
7369 }
7370 CI->setAttributes(PAL);
7371 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7372 Inst = CI;
7373 return false;
7374 }
7375
7376 //===----------------------------------------------------------------------===//
7377 // Memory Instructions.
7378 //===----------------------------------------------------------------------===//
7379
7380 /// parseAlloc
7381 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7382 /// (',' 'align' i32)? (',', 'addrspace(n))?
parseAlloc(Instruction * & Inst,PerFunctionState & PFS)7383 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7384 Value *Size = nullptr;
7385 LocTy SizeLoc, TyLoc, ASLoc;
7386 MaybeAlign Alignment;
7387 unsigned AddrSpace = 0;
7388 Type *Ty = nullptr;
7389
7390 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7391 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7392
7393 if (parseType(Ty, TyLoc))
7394 return true;
7395
7396 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7397 return error(TyLoc, "invalid type for alloca");
7398
7399 bool AteExtraComma = false;
7400 if (EatIfPresent(lltok::comma)) {
7401 if (Lex.getKind() == lltok::kw_align) {
7402 if (parseOptionalAlignment(Alignment))
7403 return true;
7404 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7405 return true;
7406 } else if (Lex.getKind() == lltok::kw_addrspace) {
7407 ASLoc = Lex.getLoc();
7408 if (parseOptionalAddrSpace(AddrSpace))
7409 return true;
7410 } else if (Lex.getKind() == lltok::MetadataVar) {
7411 AteExtraComma = true;
7412 } else {
7413 if (parseTypeAndValue(Size, SizeLoc, PFS))
7414 return true;
7415 if (EatIfPresent(lltok::comma)) {
7416 if (Lex.getKind() == lltok::kw_align) {
7417 if (parseOptionalAlignment(Alignment))
7418 return true;
7419 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7420 return true;
7421 } else if (Lex.getKind() == lltok::kw_addrspace) {
7422 ASLoc = Lex.getLoc();
7423 if (parseOptionalAddrSpace(AddrSpace))
7424 return true;
7425 } else if (Lex.getKind() == lltok::MetadataVar) {
7426 AteExtraComma = true;
7427 }
7428 }
7429 }
7430 }
7431
7432 if (Size && !Size->getType()->isIntegerTy())
7433 return error(SizeLoc, "element count must have integer type");
7434
7435 SmallPtrSet<Type *, 4> Visited;
7436 if (!Alignment && !Ty->isSized(&Visited))
7437 return error(TyLoc, "Cannot allocate unsized type");
7438 if (!Alignment)
7439 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7440 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7441 AI->setUsedWithInAlloca(IsInAlloca);
7442 AI->setSwiftError(IsSwiftError);
7443 Inst = AI;
7444 return AteExtraComma ? InstExtraComma : InstNormal;
7445 }
7446
7447 /// parseLoad
7448 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7449 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7450 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
parseLoad(Instruction * & Inst,PerFunctionState & PFS)7451 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7452 Value *Val; LocTy Loc;
7453 MaybeAlign Alignment;
7454 bool AteExtraComma = false;
7455 bool isAtomic = false;
7456 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7457 SyncScope::ID SSID = SyncScope::System;
7458
7459 if (Lex.getKind() == lltok::kw_atomic) {
7460 isAtomic = true;
7461 Lex.Lex();
7462 }
7463
7464 bool isVolatile = false;
7465 if (Lex.getKind() == lltok::kw_volatile) {
7466 isVolatile = true;
7467 Lex.Lex();
7468 }
7469
7470 Type *Ty;
7471 LocTy ExplicitTypeLoc = Lex.getLoc();
7472 if (parseType(Ty) ||
7473 parseToken(lltok::comma, "expected comma after load's type") ||
7474 parseTypeAndValue(Val, Loc, PFS) ||
7475 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7476 parseOptionalCommaAlign(Alignment, AteExtraComma))
7477 return true;
7478
7479 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7480 return error(Loc, "load operand must be a pointer to a first class type");
7481 if (isAtomic && !Alignment)
7482 return error(Loc, "atomic load must have explicit non-zero alignment");
7483 if (Ordering == AtomicOrdering::Release ||
7484 Ordering == AtomicOrdering::AcquireRelease)
7485 return error(Loc, "atomic load cannot use Release ordering");
7486
7487 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7488 return error(
7489 ExplicitTypeLoc,
7490 typeComparisonErrorMessage(
7491 "explicit pointee type doesn't match operand's pointee type", Ty,
7492 cast<PointerType>(Val->getType())->getElementType()));
7493 }
7494 SmallPtrSet<Type *, 4> Visited;
7495 if (!Alignment && !Ty->isSized(&Visited))
7496 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7497 if (!Alignment)
7498 Alignment = M->getDataLayout().getABITypeAlign(Ty);
7499 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7500 return AteExtraComma ? InstExtraComma : InstNormal;
7501 }
7502
7503 /// parseStore
7504
7505 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7506 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7507 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
parseStore(Instruction * & Inst,PerFunctionState & PFS)7508 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7509 Value *Val, *Ptr; LocTy Loc, PtrLoc;
7510 MaybeAlign Alignment;
7511 bool AteExtraComma = false;
7512 bool isAtomic = false;
7513 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7514 SyncScope::ID SSID = SyncScope::System;
7515
7516 if (Lex.getKind() == lltok::kw_atomic) {
7517 isAtomic = true;
7518 Lex.Lex();
7519 }
7520
7521 bool isVolatile = false;
7522 if (Lex.getKind() == lltok::kw_volatile) {
7523 isVolatile = true;
7524 Lex.Lex();
7525 }
7526
7527 if (parseTypeAndValue(Val, Loc, PFS) ||
7528 parseToken(lltok::comma, "expected ',' after store operand") ||
7529 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7530 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7531 parseOptionalCommaAlign(Alignment, AteExtraComma))
7532 return true;
7533
7534 if (!Ptr->getType()->isPointerTy())
7535 return error(PtrLoc, "store operand must be a pointer");
7536 if (!Val->getType()->isFirstClassType())
7537 return error(Loc, "store operand must be a first class value");
7538 if (!cast<PointerType>(Ptr->getType())
7539 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7540 return error(Loc, "stored value and pointer type do not match");
7541 if (isAtomic && !Alignment)
7542 return error(Loc, "atomic store must have explicit non-zero alignment");
7543 if (Ordering == AtomicOrdering::Acquire ||
7544 Ordering == AtomicOrdering::AcquireRelease)
7545 return error(Loc, "atomic store cannot use Acquire ordering");
7546 SmallPtrSet<Type *, 4> Visited;
7547 if (!Alignment && !Val->getType()->isSized(&Visited))
7548 return error(Loc, "storing unsized types is not allowed");
7549 if (!Alignment)
7550 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7551
7552 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7553 return AteExtraComma ? InstExtraComma : InstNormal;
7554 }
7555
7556 /// parseCmpXchg
7557 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7558 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7559 /// 'Align'?
parseCmpXchg(Instruction * & Inst,PerFunctionState & PFS)7560 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7561 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7562 bool AteExtraComma = false;
7563 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7564 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7565 SyncScope::ID SSID = SyncScope::System;
7566 bool isVolatile = false;
7567 bool isWeak = false;
7568 MaybeAlign Alignment;
7569
7570 if (EatIfPresent(lltok::kw_weak))
7571 isWeak = true;
7572
7573 if (EatIfPresent(lltok::kw_volatile))
7574 isVolatile = true;
7575
7576 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7577 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7578 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7579 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7580 parseTypeAndValue(New, NewLoc, PFS) ||
7581 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7582 parseOrdering(FailureOrdering) ||
7583 parseOptionalCommaAlign(Alignment, AteExtraComma))
7584 return true;
7585
7586 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7587 return tokError("invalid cmpxchg success ordering");
7588 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7589 return tokError("invalid cmpxchg failure ordering");
7590 if (!Ptr->getType()->isPointerTy())
7591 return error(PtrLoc, "cmpxchg operand must be a pointer");
7592 if (!cast<PointerType>(Ptr->getType())
7593 ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7594 return error(CmpLoc, "compare value and pointer type do not match");
7595 if (!cast<PointerType>(Ptr->getType())
7596 ->isOpaqueOrPointeeTypeMatches(New->getType()))
7597 return error(NewLoc, "new value and pointer type do not match");
7598 if (Cmp->getType() != New->getType())
7599 return error(NewLoc, "compare value and new value type do not match");
7600 if (!New->getType()->isFirstClassType())
7601 return error(NewLoc, "cmpxchg operand must be a first class value");
7602
7603 const Align DefaultAlignment(
7604 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7605 Cmp->getType()));
7606
7607 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7608 Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering,
7609 FailureOrdering, SSID);
7610 CXI->setVolatile(isVolatile);
7611 CXI->setWeak(isWeak);
7612
7613 Inst = CXI;
7614 return AteExtraComma ? InstExtraComma : InstNormal;
7615 }
7616
7617 /// parseAtomicRMW
7618 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7619 /// 'singlethread'? AtomicOrdering
parseAtomicRMW(Instruction * & Inst,PerFunctionState & PFS)7620 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7621 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7622 bool AteExtraComma = false;
7623 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7624 SyncScope::ID SSID = SyncScope::System;
7625 bool isVolatile = false;
7626 bool IsFP = false;
7627 AtomicRMWInst::BinOp Operation;
7628 MaybeAlign Alignment;
7629
7630 if (EatIfPresent(lltok::kw_volatile))
7631 isVolatile = true;
7632
7633 switch (Lex.getKind()) {
7634 default:
7635 return tokError("expected binary operation in atomicrmw");
7636 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7637 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7638 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7639 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7640 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7641 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7642 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7643 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7644 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7645 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7646 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7647 case lltok::kw_fadd:
7648 Operation = AtomicRMWInst::FAdd;
7649 IsFP = true;
7650 break;
7651 case lltok::kw_fsub:
7652 Operation = AtomicRMWInst::FSub;
7653 IsFP = true;
7654 break;
7655 }
7656 Lex.Lex(); // Eat the operation.
7657
7658 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7659 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7660 parseTypeAndValue(Val, ValLoc, PFS) ||
7661 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7662 parseOptionalCommaAlign(Alignment, AteExtraComma))
7663 return true;
7664
7665 if (Ordering == AtomicOrdering::Unordered)
7666 return tokError("atomicrmw cannot be unordered");
7667 if (!Ptr->getType()->isPointerTy())
7668 return error(PtrLoc, "atomicrmw operand must be a pointer");
7669 if (!cast<PointerType>(Ptr->getType())
7670 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7671 return error(ValLoc, "atomicrmw value and pointer type do not match");
7672
7673 if (Operation == AtomicRMWInst::Xchg) {
7674 if (!Val->getType()->isIntegerTy() &&
7675 !Val->getType()->isFloatingPointTy()) {
7676 return error(ValLoc,
7677 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7678 " operand must be an integer or floating point type");
7679 }
7680 } else if (IsFP) {
7681 if (!Val->getType()->isFloatingPointTy()) {
7682 return error(ValLoc, "atomicrmw " +
7683 AtomicRMWInst::getOperationName(Operation) +
7684 " operand must be a floating point type");
7685 }
7686 } else {
7687 if (!Val->getType()->isIntegerTy()) {
7688 return error(ValLoc, "atomicrmw " +
7689 AtomicRMWInst::getOperationName(Operation) +
7690 " operand must be an integer");
7691 }
7692 }
7693
7694 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7695 if (Size < 8 || (Size & (Size - 1)))
7696 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7697 " integer");
7698 const Align DefaultAlignment(
7699 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7700 Val->getType()));
7701 AtomicRMWInst *RMWI =
7702 new AtomicRMWInst(Operation, Ptr, Val,
7703 Alignment.getValueOr(DefaultAlignment), Ordering, SSID);
7704 RMWI->setVolatile(isVolatile);
7705 Inst = RMWI;
7706 return AteExtraComma ? InstExtraComma : InstNormal;
7707 }
7708
7709 /// parseFence
7710 /// ::= 'fence' 'singlethread'? AtomicOrdering
parseFence(Instruction * & Inst,PerFunctionState & PFS)7711 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7712 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7713 SyncScope::ID SSID = SyncScope::System;
7714 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7715 return true;
7716
7717 if (Ordering == AtomicOrdering::Unordered)
7718 return tokError("fence cannot be unordered");
7719 if (Ordering == AtomicOrdering::Monotonic)
7720 return tokError("fence cannot be monotonic");
7721
7722 Inst = new FenceInst(Context, Ordering, SSID);
7723 return InstNormal;
7724 }
7725
7726 /// parseGetElementPtr
7727 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
parseGetElementPtr(Instruction * & Inst,PerFunctionState & PFS)7728 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7729 Value *Ptr = nullptr;
7730 Value *Val = nullptr;
7731 LocTy Loc, EltLoc;
7732
7733 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7734
7735 Type *Ty = nullptr;
7736 LocTy ExplicitTypeLoc = Lex.getLoc();
7737 if (parseType(Ty) ||
7738 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7739 parseTypeAndValue(Ptr, Loc, PFS))
7740 return true;
7741
7742 Type *BaseType = Ptr->getType();
7743 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7744 if (!BasePointerType)
7745 return error(Loc, "base of getelementptr must be a pointer");
7746
7747 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7748 return error(
7749 ExplicitTypeLoc,
7750 typeComparisonErrorMessage(
7751 "explicit pointee type doesn't match operand's pointee type", Ty,
7752 BasePointerType->getElementType()));
7753 }
7754
7755 SmallVector<Value*, 16> Indices;
7756 bool AteExtraComma = false;
7757 // GEP returns a vector of pointers if at least one of parameters is a vector.
7758 // All vector parameters should have the same vector width.
7759 ElementCount GEPWidth = BaseType->isVectorTy()
7760 ? cast<VectorType>(BaseType)->getElementCount()
7761 : ElementCount::getFixed(0);
7762
7763 while (EatIfPresent(lltok::comma)) {
7764 if (Lex.getKind() == lltok::MetadataVar) {
7765 AteExtraComma = true;
7766 break;
7767 }
7768 if (parseTypeAndValue(Val, EltLoc, PFS))
7769 return true;
7770 if (!Val->getType()->isIntOrIntVectorTy())
7771 return error(EltLoc, "getelementptr index must be an integer");
7772
7773 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7774 ElementCount ValNumEl = ValVTy->getElementCount();
7775 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7776 return error(
7777 EltLoc,
7778 "getelementptr vector index has a wrong number of elements");
7779 GEPWidth = ValNumEl;
7780 }
7781 Indices.push_back(Val);
7782 }
7783
7784 SmallPtrSet<Type*, 4> Visited;
7785 if (!Indices.empty() && !Ty->isSized(&Visited))
7786 return error(Loc, "base element of getelementptr must be sized");
7787
7788 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7789 return error(Loc, "invalid getelementptr indices");
7790 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7791 if (InBounds)
7792 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7793 return AteExtraComma ? InstExtraComma : InstNormal;
7794 }
7795
7796 /// parseExtractValue
7797 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
parseExtractValue(Instruction * & Inst,PerFunctionState & PFS)7798 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7799 Value *Val; LocTy Loc;
7800 SmallVector<unsigned, 4> Indices;
7801 bool AteExtraComma;
7802 if (parseTypeAndValue(Val, Loc, PFS) ||
7803 parseIndexList(Indices, AteExtraComma))
7804 return true;
7805
7806 if (!Val->getType()->isAggregateType())
7807 return error(Loc, "extractvalue operand must be aggregate type");
7808
7809 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7810 return error(Loc, "invalid indices for extractvalue");
7811 Inst = ExtractValueInst::Create(Val, Indices);
7812 return AteExtraComma ? InstExtraComma : InstNormal;
7813 }
7814
7815 /// parseInsertValue
7816 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
parseInsertValue(Instruction * & Inst,PerFunctionState & PFS)7817 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7818 Value *Val0, *Val1; LocTy Loc0, Loc1;
7819 SmallVector<unsigned, 4> Indices;
7820 bool AteExtraComma;
7821 if (parseTypeAndValue(Val0, Loc0, PFS) ||
7822 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7823 parseTypeAndValue(Val1, Loc1, PFS) ||
7824 parseIndexList(Indices, AteExtraComma))
7825 return true;
7826
7827 if (!Val0->getType()->isAggregateType())
7828 return error(Loc0, "insertvalue operand must be aggregate type");
7829
7830 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7831 if (!IndexedType)
7832 return error(Loc0, "invalid indices for insertvalue");
7833 if (IndexedType != Val1->getType())
7834 return error(Loc1, "insertvalue operand and field disagree in type: '" +
7835 getTypeString(Val1->getType()) + "' instead of '" +
7836 getTypeString(IndexedType) + "'");
7837 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7838 return AteExtraComma ? InstExtraComma : InstNormal;
7839 }
7840
7841 //===----------------------------------------------------------------------===//
7842 // Embedded metadata.
7843 //===----------------------------------------------------------------------===//
7844
7845 /// parseMDNodeVector
7846 /// ::= { Element (',' Element)* }
7847 /// Element
7848 /// ::= 'null' | TypeAndValue
parseMDNodeVector(SmallVectorImpl<Metadata * > & Elts)7849 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7850 if (parseToken(lltok::lbrace, "expected '{' here"))
7851 return true;
7852
7853 // Check for an empty list.
7854 if (EatIfPresent(lltok::rbrace))
7855 return false;
7856
7857 do {
7858 // Null is a special case since it is typeless.
7859 if (EatIfPresent(lltok::kw_null)) {
7860 Elts.push_back(nullptr);
7861 continue;
7862 }
7863
7864 Metadata *MD;
7865 if (parseMetadata(MD, nullptr))
7866 return true;
7867 Elts.push_back(MD);
7868 } while (EatIfPresent(lltok::comma));
7869
7870 return parseToken(lltok::rbrace, "expected end of metadata node");
7871 }
7872
7873 //===----------------------------------------------------------------------===//
7874 // Use-list order directives.
7875 //===----------------------------------------------------------------------===//
sortUseListOrder(Value * V,ArrayRef<unsigned> Indexes,SMLoc Loc)7876 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7877 SMLoc Loc) {
7878 if (V->use_empty())
7879 return error(Loc, "value has no uses");
7880
7881 unsigned NumUses = 0;
7882 SmallDenseMap<const Use *, unsigned, 16> Order;
7883 for (const Use &U : V->uses()) {
7884 if (++NumUses > Indexes.size())
7885 break;
7886 Order[&U] = Indexes[NumUses - 1];
7887 }
7888 if (NumUses < 2)
7889 return error(Loc, "value only has one use");
7890 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7891 return error(Loc,
7892 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7893
7894 V->sortUseList([&](const Use &L, const Use &R) {
7895 return Order.lookup(&L) < Order.lookup(&R);
7896 });
7897 return false;
7898 }
7899
7900 /// parseUseListOrderIndexes
7901 /// ::= '{' uint32 (',' uint32)+ '}'
parseUseListOrderIndexes(SmallVectorImpl<unsigned> & Indexes)7902 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7903 SMLoc Loc = Lex.getLoc();
7904 if (parseToken(lltok::lbrace, "expected '{' here"))
7905 return true;
7906 if (Lex.getKind() == lltok::rbrace)
7907 return Lex.Error("expected non-empty list of uselistorder indexes");
7908
7909 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7910 // indexes should be distinct numbers in the range [0, size-1], and should
7911 // not be in order.
7912 unsigned Offset = 0;
7913 unsigned Max = 0;
7914 bool IsOrdered = true;
7915 assert(Indexes.empty() && "Expected empty order vector");
7916 do {
7917 unsigned Index;
7918 if (parseUInt32(Index))
7919 return true;
7920
7921 // Update consistency checks.
7922 Offset += Index - Indexes.size();
7923 Max = std::max(Max, Index);
7924 IsOrdered &= Index == Indexes.size();
7925
7926 Indexes.push_back(Index);
7927 } while (EatIfPresent(lltok::comma));
7928
7929 if (parseToken(lltok::rbrace, "expected '}' here"))
7930 return true;
7931
7932 if (Indexes.size() < 2)
7933 return error(Loc, "expected >= 2 uselistorder indexes");
7934 if (Offset != 0 || Max >= Indexes.size())
7935 return error(Loc,
7936 "expected distinct uselistorder indexes in range [0, size)");
7937 if (IsOrdered)
7938 return error(Loc, "expected uselistorder indexes to change the order");
7939
7940 return false;
7941 }
7942
7943 /// parseUseListOrder
7944 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
parseUseListOrder(PerFunctionState * PFS)7945 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7946 SMLoc Loc = Lex.getLoc();
7947 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7948 return true;
7949
7950 Value *V;
7951 SmallVector<unsigned, 16> Indexes;
7952 if (parseTypeAndValue(V, PFS) ||
7953 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7954 parseUseListOrderIndexes(Indexes))
7955 return true;
7956
7957 return sortUseListOrder(V, Indexes, Loc);
7958 }
7959
7960 /// parseUseListOrderBB
7961 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
parseUseListOrderBB()7962 bool LLParser::parseUseListOrderBB() {
7963 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7964 SMLoc Loc = Lex.getLoc();
7965 Lex.Lex();
7966
7967 ValID Fn, Label;
7968 SmallVector<unsigned, 16> Indexes;
7969 if (parseValID(Fn) ||
7970 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7971 parseValID(Label) ||
7972 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7973 parseUseListOrderIndexes(Indexes))
7974 return true;
7975
7976 // Check the function.
7977 GlobalValue *GV;
7978 if (Fn.Kind == ValID::t_GlobalName)
7979 GV = M->getNamedValue(Fn.StrVal);
7980 else if (Fn.Kind == ValID::t_GlobalID)
7981 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7982 else
7983 return error(Fn.Loc, "expected function name in uselistorder_bb");
7984 if (!GV)
7985 return error(Fn.Loc,
7986 "invalid function forward reference in uselistorder_bb");
7987 auto *F = dyn_cast<Function>(GV);
7988 if (!F)
7989 return error(Fn.Loc, "expected function name in uselistorder_bb");
7990 if (F->isDeclaration())
7991 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7992
7993 // Check the basic block.
7994 if (Label.Kind == ValID::t_LocalID)
7995 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7996 if (Label.Kind != ValID::t_LocalName)
7997 return error(Label.Loc, "expected basic block name in uselistorder_bb");
7998 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7999 if (!V)
8000 return error(Label.Loc, "invalid basic block in uselistorder_bb");
8001 if (!isa<BasicBlock>(V))
8002 return error(Label.Loc, "expected basic block in uselistorder_bb");
8003
8004 return sortUseListOrder(V, Indexes, Loc);
8005 }
8006
8007 /// ModuleEntry
8008 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8009 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
parseModuleEntry(unsigned ID)8010 bool LLParser::parseModuleEntry(unsigned ID) {
8011 assert(Lex.getKind() == lltok::kw_module);
8012 Lex.Lex();
8013
8014 std::string Path;
8015 if (parseToken(lltok::colon, "expected ':' here") ||
8016 parseToken(lltok::lparen, "expected '(' here") ||
8017 parseToken(lltok::kw_path, "expected 'path' here") ||
8018 parseToken(lltok::colon, "expected ':' here") ||
8019 parseStringConstant(Path) ||
8020 parseToken(lltok::comma, "expected ',' here") ||
8021 parseToken(lltok::kw_hash, "expected 'hash' here") ||
8022 parseToken(lltok::colon, "expected ':' here") ||
8023 parseToken(lltok::lparen, "expected '(' here"))
8024 return true;
8025
8026 ModuleHash Hash;
8027 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8028 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8029 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8030 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8031 parseUInt32(Hash[4]))
8032 return true;
8033
8034 if (parseToken(lltok::rparen, "expected ')' here") ||
8035 parseToken(lltok::rparen, "expected ')' here"))
8036 return true;
8037
8038 auto ModuleEntry = Index->addModule(Path, ID, Hash);
8039 ModuleIdMap[ID] = ModuleEntry->first();
8040
8041 return false;
8042 }
8043
8044 /// TypeIdEntry
8045 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
parseTypeIdEntry(unsigned ID)8046 bool LLParser::parseTypeIdEntry(unsigned ID) {
8047 assert(Lex.getKind() == lltok::kw_typeid);
8048 Lex.Lex();
8049
8050 std::string Name;
8051 if (parseToken(lltok::colon, "expected ':' here") ||
8052 parseToken(lltok::lparen, "expected '(' here") ||
8053 parseToken(lltok::kw_name, "expected 'name' here") ||
8054 parseToken(lltok::colon, "expected ':' here") ||
8055 parseStringConstant(Name))
8056 return true;
8057
8058 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8059 if (parseToken(lltok::comma, "expected ',' here") ||
8060 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8061 return true;
8062
8063 // Check if this ID was forward referenced, and if so, update the
8064 // corresponding GUIDs.
8065 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8066 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8067 for (auto TIDRef : FwdRefTIDs->second) {
8068 assert(!*TIDRef.first &&
8069 "Forward referenced type id GUID expected to be 0");
8070 *TIDRef.first = GlobalValue::getGUID(Name);
8071 }
8072 ForwardRefTypeIds.erase(FwdRefTIDs);
8073 }
8074
8075 return false;
8076 }
8077
8078 /// TypeIdSummary
8079 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
parseTypeIdSummary(TypeIdSummary & TIS)8080 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8081 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8082 parseToken(lltok::colon, "expected ':' here") ||
8083 parseToken(lltok::lparen, "expected '(' here") ||
8084 parseTypeTestResolution(TIS.TTRes))
8085 return true;
8086
8087 if (EatIfPresent(lltok::comma)) {
8088 // Expect optional wpdResolutions field
8089 if (parseOptionalWpdResolutions(TIS.WPDRes))
8090 return true;
8091 }
8092
8093 if (parseToken(lltok::rparen, "expected ')' here"))
8094 return true;
8095
8096 return false;
8097 }
8098
8099 static ValueInfo EmptyVI =
8100 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8101
8102 /// TypeIdCompatibleVtableEntry
8103 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8104 /// TypeIdCompatibleVtableInfo
8105 /// ')'
parseTypeIdCompatibleVtableEntry(unsigned ID)8106 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8107 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
8108 Lex.Lex();
8109
8110 std::string Name;
8111 if (parseToken(lltok::colon, "expected ':' here") ||
8112 parseToken(lltok::lparen, "expected '(' here") ||
8113 parseToken(lltok::kw_name, "expected 'name' here") ||
8114 parseToken(lltok::colon, "expected ':' here") ||
8115 parseStringConstant(Name))
8116 return true;
8117
8118 TypeIdCompatibleVtableInfo &TI =
8119 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8120 if (parseToken(lltok::comma, "expected ',' here") ||
8121 parseToken(lltok::kw_summary, "expected 'summary' here") ||
8122 parseToken(lltok::colon, "expected ':' here") ||
8123 parseToken(lltok::lparen, "expected '(' here"))
8124 return true;
8125
8126 IdToIndexMapType IdToIndexMap;
8127 // parse each call edge
8128 do {
8129 uint64_t Offset;
8130 if (parseToken(lltok::lparen, "expected '(' here") ||
8131 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8132 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8133 parseToken(lltok::comma, "expected ',' here"))
8134 return true;
8135
8136 LocTy Loc = Lex.getLoc();
8137 unsigned GVId;
8138 ValueInfo VI;
8139 if (parseGVReference(VI, GVId))
8140 return true;
8141
8142 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8143 // forward reference. We will save the location of the ValueInfo needing an
8144 // update, but can only do so once the std::vector is finalized.
8145 if (VI == EmptyVI)
8146 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8147 TI.push_back({Offset, VI});
8148
8149 if (parseToken(lltok::rparen, "expected ')' in call"))
8150 return true;
8151 } while (EatIfPresent(lltok::comma));
8152
8153 // Now that the TI vector is finalized, it is safe to save the locations
8154 // of any forward GV references that need updating later.
8155 for (auto I : IdToIndexMap) {
8156 auto &Infos = ForwardRefValueInfos[I.first];
8157 for (auto P : I.second) {
8158 assert(TI[P.first].VTableVI == EmptyVI &&
8159 "Forward referenced ValueInfo expected to be empty");
8160 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8161 }
8162 }
8163
8164 if (parseToken(lltok::rparen, "expected ')' here") ||
8165 parseToken(lltok::rparen, "expected ')' here"))
8166 return true;
8167
8168 // Check if this ID was forward referenced, and if so, update the
8169 // corresponding GUIDs.
8170 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8171 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8172 for (auto TIDRef : FwdRefTIDs->second) {
8173 assert(!*TIDRef.first &&
8174 "Forward referenced type id GUID expected to be 0");
8175 *TIDRef.first = GlobalValue::getGUID(Name);
8176 }
8177 ForwardRefTypeIds.erase(FwdRefTIDs);
8178 }
8179
8180 return false;
8181 }
8182
8183 /// TypeTestResolution
8184 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
8185 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8186 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8187 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8188 /// [',' 'inlinesBits' ':' UInt64]? ')'
parseTypeTestResolution(TypeTestResolution & TTRes)8189 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8190 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8191 parseToken(lltok::colon, "expected ':' here") ||
8192 parseToken(lltok::lparen, "expected '(' here") ||
8193 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8194 parseToken(lltok::colon, "expected ':' here"))
8195 return true;
8196
8197 switch (Lex.getKind()) {
8198 case lltok::kw_unknown:
8199 TTRes.TheKind = TypeTestResolution::Unknown;
8200 break;
8201 case lltok::kw_unsat:
8202 TTRes.TheKind = TypeTestResolution::Unsat;
8203 break;
8204 case lltok::kw_byteArray:
8205 TTRes.TheKind = TypeTestResolution::ByteArray;
8206 break;
8207 case lltok::kw_inline:
8208 TTRes.TheKind = TypeTestResolution::Inline;
8209 break;
8210 case lltok::kw_single:
8211 TTRes.TheKind = TypeTestResolution::Single;
8212 break;
8213 case lltok::kw_allOnes:
8214 TTRes.TheKind = TypeTestResolution::AllOnes;
8215 break;
8216 default:
8217 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8218 }
8219 Lex.Lex();
8220
8221 if (parseToken(lltok::comma, "expected ',' here") ||
8222 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8223 parseToken(lltok::colon, "expected ':' here") ||
8224 parseUInt32(TTRes.SizeM1BitWidth))
8225 return true;
8226
8227 // parse optional fields
8228 while (EatIfPresent(lltok::comma)) {
8229 switch (Lex.getKind()) {
8230 case lltok::kw_alignLog2:
8231 Lex.Lex();
8232 if (parseToken(lltok::colon, "expected ':'") ||
8233 parseUInt64(TTRes.AlignLog2))
8234 return true;
8235 break;
8236 case lltok::kw_sizeM1:
8237 Lex.Lex();
8238 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8239 return true;
8240 break;
8241 case lltok::kw_bitMask: {
8242 unsigned Val;
8243 Lex.Lex();
8244 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8245 return true;
8246 assert(Val <= 0xff);
8247 TTRes.BitMask = (uint8_t)Val;
8248 break;
8249 }
8250 case lltok::kw_inlineBits:
8251 Lex.Lex();
8252 if (parseToken(lltok::colon, "expected ':'") ||
8253 parseUInt64(TTRes.InlineBits))
8254 return true;
8255 break;
8256 default:
8257 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8258 }
8259 }
8260
8261 if (parseToken(lltok::rparen, "expected ')' here"))
8262 return true;
8263
8264 return false;
8265 }
8266
8267 /// OptionalWpdResolutions
8268 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8269 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
parseOptionalWpdResolutions(std::map<uint64_t,WholeProgramDevirtResolution> & WPDResMap)8270 bool LLParser::parseOptionalWpdResolutions(
8271 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8272 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8273 parseToken(lltok::colon, "expected ':' here") ||
8274 parseToken(lltok::lparen, "expected '(' here"))
8275 return true;
8276
8277 do {
8278 uint64_t Offset;
8279 WholeProgramDevirtResolution WPDRes;
8280 if (parseToken(lltok::lparen, "expected '(' here") ||
8281 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8282 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8283 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8284 parseToken(lltok::rparen, "expected ')' here"))
8285 return true;
8286 WPDResMap[Offset] = WPDRes;
8287 } while (EatIfPresent(lltok::comma));
8288
8289 if (parseToken(lltok::rparen, "expected ')' here"))
8290 return true;
8291
8292 return false;
8293 }
8294
8295 /// WpdRes
8296 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8297 /// [',' OptionalResByArg]? ')'
8298 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8299 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
8300 /// [',' OptionalResByArg]? ')'
8301 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8302 /// [',' OptionalResByArg]? ')'
parseWpdRes(WholeProgramDevirtResolution & WPDRes)8303 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8304 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8305 parseToken(lltok::colon, "expected ':' here") ||
8306 parseToken(lltok::lparen, "expected '(' here") ||
8307 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8308 parseToken(lltok::colon, "expected ':' here"))
8309 return true;
8310
8311 switch (Lex.getKind()) {
8312 case lltok::kw_indir:
8313 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8314 break;
8315 case lltok::kw_singleImpl:
8316 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8317 break;
8318 case lltok::kw_branchFunnel:
8319 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8320 break;
8321 default:
8322 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8323 }
8324 Lex.Lex();
8325
8326 // parse optional fields
8327 while (EatIfPresent(lltok::comma)) {
8328 switch (Lex.getKind()) {
8329 case lltok::kw_singleImplName:
8330 Lex.Lex();
8331 if (parseToken(lltok::colon, "expected ':' here") ||
8332 parseStringConstant(WPDRes.SingleImplName))
8333 return true;
8334 break;
8335 case lltok::kw_resByArg:
8336 if (parseOptionalResByArg(WPDRes.ResByArg))
8337 return true;
8338 break;
8339 default:
8340 return error(Lex.getLoc(),
8341 "expected optional WholeProgramDevirtResolution field");
8342 }
8343 }
8344
8345 if (parseToken(lltok::rparen, "expected ')' here"))
8346 return true;
8347
8348 return false;
8349 }
8350
8351 /// OptionalResByArg
8352 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8353 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8354 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8355 /// 'virtualConstProp' )
8356 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8357 /// [',' 'bit' ':' UInt32]? ')'
parseOptionalResByArg(std::map<std::vector<uint64_t>,WholeProgramDevirtResolution::ByArg> & ResByArg)8358 bool LLParser::parseOptionalResByArg(
8359 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8360 &ResByArg) {
8361 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8362 parseToken(lltok::colon, "expected ':' here") ||
8363 parseToken(lltok::lparen, "expected '(' here"))
8364 return true;
8365
8366 do {
8367 std::vector<uint64_t> Args;
8368 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8369 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8370 parseToken(lltok::colon, "expected ':' here") ||
8371 parseToken(lltok::lparen, "expected '(' here") ||
8372 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8373 parseToken(lltok::colon, "expected ':' here"))
8374 return true;
8375
8376 WholeProgramDevirtResolution::ByArg ByArg;
8377 switch (Lex.getKind()) {
8378 case lltok::kw_indir:
8379 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8380 break;
8381 case lltok::kw_uniformRetVal:
8382 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8383 break;
8384 case lltok::kw_uniqueRetVal:
8385 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8386 break;
8387 case lltok::kw_virtualConstProp:
8388 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8389 break;
8390 default:
8391 return error(Lex.getLoc(),
8392 "unexpected WholeProgramDevirtResolution::ByArg kind");
8393 }
8394 Lex.Lex();
8395
8396 // parse optional fields
8397 while (EatIfPresent(lltok::comma)) {
8398 switch (Lex.getKind()) {
8399 case lltok::kw_info:
8400 Lex.Lex();
8401 if (parseToken(lltok::colon, "expected ':' here") ||
8402 parseUInt64(ByArg.Info))
8403 return true;
8404 break;
8405 case lltok::kw_byte:
8406 Lex.Lex();
8407 if (parseToken(lltok::colon, "expected ':' here") ||
8408 parseUInt32(ByArg.Byte))
8409 return true;
8410 break;
8411 case lltok::kw_bit:
8412 Lex.Lex();
8413 if (parseToken(lltok::colon, "expected ':' here") ||
8414 parseUInt32(ByArg.Bit))
8415 return true;
8416 break;
8417 default:
8418 return error(Lex.getLoc(),
8419 "expected optional whole program devirt field");
8420 }
8421 }
8422
8423 if (parseToken(lltok::rparen, "expected ')' here"))
8424 return true;
8425
8426 ResByArg[Args] = ByArg;
8427 } while (EatIfPresent(lltok::comma));
8428
8429 if (parseToken(lltok::rparen, "expected ')' here"))
8430 return true;
8431
8432 return false;
8433 }
8434
8435 /// OptionalResByArg
8436 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
parseArgs(std::vector<uint64_t> & Args)8437 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8438 if (parseToken(lltok::kw_args, "expected 'args' here") ||
8439 parseToken(lltok::colon, "expected ':' here") ||
8440 parseToken(lltok::lparen, "expected '(' here"))
8441 return true;
8442
8443 do {
8444 uint64_t Val;
8445 if (parseUInt64(Val))
8446 return true;
8447 Args.push_back(Val);
8448 } while (EatIfPresent(lltok::comma));
8449
8450 if (parseToken(lltok::rparen, "expected ')' here"))
8451 return true;
8452
8453 return false;
8454 }
8455
8456 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8457
resolveFwdRef(ValueInfo * Fwd,ValueInfo & Resolved)8458 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8459 bool ReadOnly = Fwd->isReadOnly();
8460 bool WriteOnly = Fwd->isWriteOnly();
8461 assert(!(ReadOnly && WriteOnly));
8462 *Fwd = Resolved;
8463 if (ReadOnly)
8464 Fwd->setReadOnly();
8465 if (WriteOnly)
8466 Fwd->setWriteOnly();
8467 }
8468
8469 /// Stores the given Name/GUID and associated summary into the Index.
8470 /// Also updates any forward references to the associated entry ID.
addGlobalValueToIndex(std::string Name,GlobalValue::GUID GUID,GlobalValue::LinkageTypes Linkage,unsigned ID,std::unique_ptr<GlobalValueSummary> Summary)8471 void LLParser::addGlobalValueToIndex(
8472 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8473 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8474 // First create the ValueInfo utilizing the Name or GUID.
8475 ValueInfo VI;
8476 if (GUID != 0) {
8477 assert(Name.empty());
8478 VI = Index->getOrInsertValueInfo(GUID);
8479 } else {
8480 assert(!Name.empty());
8481 if (M) {
8482 auto *GV = M->getNamedValue(Name);
8483 assert(GV);
8484 VI = Index->getOrInsertValueInfo(GV);
8485 } else {
8486 assert(
8487 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8488 "Need a source_filename to compute GUID for local");
8489 GUID = GlobalValue::getGUID(
8490 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8491 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8492 }
8493 }
8494
8495 // Resolve forward references from calls/refs
8496 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8497 if (FwdRefVIs != ForwardRefValueInfos.end()) {
8498 for (auto VIRef : FwdRefVIs->second) {
8499 assert(VIRef.first->getRef() == FwdVIRef &&
8500 "Forward referenced ValueInfo expected to be empty");
8501 resolveFwdRef(VIRef.first, VI);
8502 }
8503 ForwardRefValueInfos.erase(FwdRefVIs);
8504 }
8505
8506 // Resolve forward references from aliases
8507 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8508 if (FwdRefAliasees != ForwardRefAliasees.end()) {
8509 for (auto AliaseeRef : FwdRefAliasees->second) {
8510 assert(!AliaseeRef.first->hasAliasee() &&
8511 "Forward referencing alias already has aliasee");
8512 assert(Summary && "Aliasee must be a definition");
8513 AliaseeRef.first->setAliasee(VI, Summary.get());
8514 }
8515 ForwardRefAliasees.erase(FwdRefAliasees);
8516 }
8517
8518 // Add the summary if one was provided.
8519 if (Summary)
8520 Index->addGlobalValueSummary(VI, std::move(Summary));
8521
8522 // Save the associated ValueInfo for use in later references by ID.
8523 if (ID == NumberedValueInfos.size())
8524 NumberedValueInfos.push_back(VI);
8525 else {
8526 // Handle non-continuous numbers (to make test simplification easier).
8527 if (ID > NumberedValueInfos.size())
8528 NumberedValueInfos.resize(ID + 1);
8529 NumberedValueInfos[ID] = VI;
8530 }
8531 }
8532
8533 /// parseSummaryIndexFlags
8534 /// ::= 'flags' ':' UInt64
parseSummaryIndexFlags()8535 bool LLParser::parseSummaryIndexFlags() {
8536 assert(Lex.getKind() == lltok::kw_flags);
8537 Lex.Lex();
8538
8539 if (parseToken(lltok::colon, "expected ':' here"))
8540 return true;
8541 uint64_t Flags;
8542 if (parseUInt64(Flags))
8543 return true;
8544 if (Index)
8545 Index->setFlags(Flags);
8546 return false;
8547 }
8548
8549 /// parseBlockCount
8550 /// ::= 'blockcount' ':' UInt64
parseBlockCount()8551 bool LLParser::parseBlockCount() {
8552 assert(Lex.getKind() == lltok::kw_blockcount);
8553 Lex.Lex();
8554
8555 if (parseToken(lltok::colon, "expected ':' here"))
8556 return true;
8557 uint64_t BlockCount;
8558 if (parseUInt64(BlockCount))
8559 return true;
8560 if (Index)
8561 Index->setBlockCount(BlockCount);
8562 return false;
8563 }
8564
8565 /// parseGVEntry
8566 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8567 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8568 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
parseGVEntry(unsigned ID)8569 bool LLParser::parseGVEntry(unsigned ID) {
8570 assert(Lex.getKind() == lltok::kw_gv);
8571 Lex.Lex();
8572
8573 if (parseToken(lltok::colon, "expected ':' here") ||
8574 parseToken(lltok::lparen, "expected '(' here"))
8575 return true;
8576
8577 std::string Name;
8578 GlobalValue::GUID GUID = 0;
8579 switch (Lex.getKind()) {
8580 case lltok::kw_name:
8581 Lex.Lex();
8582 if (parseToken(lltok::colon, "expected ':' here") ||
8583 parseStringConstant(Name))
8584 return true;
8585 // Can't create GUID/ValueInfo until we have the linkage.
8586 break;
8587 case lltok::kw_guid:
8588 Lex.Lex();
8589 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8590 return true;
8591 break;
8592 default:
8593 return error(Lex.getLoc(), "expected name or guid tag");
8594 }
8595
8596 if (!EatIfPresent(lltok::comma)) {
8597 // No summaries. Wrap up.
8598 if (parseToken(lltok::rparen, "expected ')' here"))
8599 return true;
8600 // This was created for a call to an external or indirect target.
8601 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8602 // created for indirect calls with VP. A Name with no GUID came from
8603 // an external definition. We pass ExternalLinkage since that is only
8604 // used when the GUID must be computed from Name, and in that case
8605 // the symbol must have external linkage.
8606 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8607 nullptr);
8608 return false;
8609 }
8610
8611 // Have a list of summaries
8612 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8613 parseToken(lltok::colon, "expected ':' here") ||
8614 parseToken(lltok::lparen, "expected '(' here"))
8615 return true;
8616 do {
8617 switch (Lex.getKind()) {
8618 case lltok::kw_function:
8619 if (parseFunctionSummary(Name, GUID, ID))
8620 return true;
8621 break;
8622 case lltok::kw_variable:
8623 if (parseVariableSummary(Name, GUID, ID))
8624 return true;
8625 break;
8626 case lltok::kw_alias:
8627 if (parseAliasSummary(Name, GUID, ID))
8628 return true;
8629 break;
8630 default:
8631 return error(Lex.getLoc(), "expected summary type");
8632 }
8633 } while (EatIfPresent(lltok::comma));
8634
8635 if (parseToken(lltok::rparen, "expected ')' here") ||
8636 parseToken(lltok::rparen, "expected ')' here"))
8637 return true;
8638
8639 return false;
8640 }
8641
8642 /// FunctionSummary
8643 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8644 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8645 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8646 /// [',' OptionalRefs]? ')'
parseFunctionSummary(std::string Name,GlobalValue::GUID GUID,unsigned ID)8647 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8648 unsigned ID) {
8649 assert(Lex.getKind() == lltok::kw_function);
8650 Lex.Lex();
8651
8652 StringRef ModulePath;
8653 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8654 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8655 /*NotEligibleToImport=*/false,
8656 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8657 unsigned InstCount;
8658 std::vector<FunctionSummary::EdgeTy> Calls;
8659 FunctionSummary::TypeIdInfo TypeIdInfo;
8660 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8661 std::vector<ValueInfo> Refs;
8662 // Default is all-zeros (conservative values).
8663 FunctionSummary::FFlags FFlags = {};
8664 if (parseToken(lltok::colon, "expected ':' here") ||
8665 parseToken(lltok::lparen, "expected '(' here") ||
8666 parseModuleReference(ModulePath) ||
8667 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8668 parseToken(lltok::comma, "expected ',' here") ||
8669 parseToken(lltok::kw_insts, "expected 'insts' here") ||
8670 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8671 return true;
8672
8673 // parse optional fields
8674 while (EatIfPresent(lltok::comma)) {
8675 switch (Lex.getKind()) {
8676 case lltok::kw_funcFlags:
8677 if (parseOptionalFFlags(FFlags))
8678 return true;
8679 break;
8680 case lltok::kw_calls:
8681 if (parseOptionalCalls(Calls))
8682 return true;
8683 break;
8684 case lltok::kw_typeIdInfo:
8685 if (parseOptionalTypeIdInfo(TypeIdInfo))
8686 return true;
8687 break;
8688 case lltok::kw_refs:
8689 if (parseOptionalRefs(Refs))
8690 return true;
8691 break;
8692 case lltok::kw_params:
8693 if (parseOptionalParamAccesses(ParamAccesses))
8694 return true;
8695 break;
8696 default:
8697 return error(Lex.getLoc(), "expected optional function summary field");
8698 }
8699 }
8700
8701 if (parseToken(lltok::rparen, "expected ')' here"))
8702 return true;
8703
8704 auto FS = std::make_unique<FunctionSummary>(
8705 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8706 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8707 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8708 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8709 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8710 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8711 std::move(ParamAccesses));
8712
8713 FS->setModulePath(ModulePath);
8714
8715 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8716 ID, std::move(FS));
8717
8718 return false;
8719 }
8720
8721 /// VariableSummary
8722 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8723 /// [',' OptionalRefs]? ')'
parseVariableSummary(std::string Name,GlobalValue::GUID GUID,unsigned ID)8724 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8725 unsigned ID) {
8726 assert(Lex.getKind() == lltok::kw_variable);
8727 Lex.Lex();
8728
8729 StringRef ModulePath;
8730 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8731 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8732 /*NotEligibleToImport=*/false,
8733 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8734 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8735 /* WriteOnly */ false,
8736 /* Constant */ false,
8737 GlobalObject::VCallVisibilityPublic);
8738 std::vector<ValueInfo> Refs;
8739 VTableFuncList VTableFuncs;
8740 if (parseToken(lltok::colon, "expected ':' here") ||
8741 parseToken(lltok::lparen, "expected '(' here") ||
8742 parseModuleReference(ModulePath) ||
8743 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8744 parseToken(lltok::comma, "expected ',' here") ||
8745 parseGVarFlags(GVarFlags))
8746 return true;
8747
8748 // parse optional fields
8749 while (EatIfPresent(lltok::comma)) {
8750 switch (Lex.getKind()) {
8751 case lltok::kw_vTableFuncs:
8752 if (parseOptionalVTableFuncs(VTableFuncs))
8753 return true;
8754 break;
8755 case lltok::kw_refs:
8756 if (parseOptionalRefs(Refs))
8757 return true;
8758 break;
8759 default:
8760 return error(Lex.getLoc(), "expected optional variable summary field");
8761 }
8762 }
8763
8764 if (parseToken(lltok::rparen, "expected ')' here"))
8765 return true;
8766
8767 auto GS =
8768 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8769
8770 GS->setModulePath(ModulePath);
8771 GS->setVTableFuncs(std::move(VTableFuncs));
8772
8773 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8774 ID, std::move(GS));
8775
8776 return false;
8777 }
8778
8779 /// AliasSummary
8780 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8781 /// 'aliasee' ':' GVReference ')'
parseAliasSummary(std::string Name,GlobalValue::GUID GUID,unsigned ID)8782 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8783 unsigned ID) {
8784 assert(Lex.getKind() == lltok::kw_alias);
8785 LocTy Loc = Lex.getLoc();
8786 Lex.Lex();
8787
8788 StringRef ModulePath;
8789 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8790 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8791 /*NotEligibleToImport=*/false,
8792 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8793 if (parseToken(lltok::colon, "expected ':' here") ||
8794 parseToken(lltok::lparen, "expected '(' here") ||
8795 parseModuleReference(ModulePath) ||
8796 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8797 parseToken(lltok::comma, "expected ',' here") ||
8798 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8799 parseToken(lltok::colon, "expected ':' here"))
8800 return true;
8801
8802 ValueInfo AliaseeVI;
8803 unsigned GVId;
8804 if (parseGVReference(AliaseeVI, GVId))
8805 return true;
8806
8807 if (parseToken(lltok::rparen, "expected ')' here"))
8808 return true;
8809
8810 auto AS = std::make_unique<AliasSummary>(GVFlags);
8811
8812 AS->setModulePath(ModulePath);
8813
8814 // Record forward reference if the aliasee is not parsed yet.
8815 if (AliaseeVI.getRef() == FwdVIRef) {
8816 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8817 } else {
8818 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8819 assert(Summary && "Aliasee must be a definition");
8820 AS->setAliasee(AliaseeVI, Summary);
8821 }
8822
8823 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8824 ID, std::move(AS));
8825
8826 return false;
8827 }
8828
8829 /// Flag
8830 /// ::= [0|1]
parseFlag(unsigned & Val)8831 bool LLParser::parseFlag(unsigned &Val) {
8832 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8833 return tokError("expected integer");
8834 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8835 Lex.Lex();
8836 return false;
8837 }
8838
8839 /// OptionalFFlags
8840 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8841 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8842 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8843 /// [',' 'noInline' ':' Flag]? ')'
8844 /// [',' 'alwaysInline' ':' Flag]? ')'
8845
parseOptionalFFlags(FunctionSummary::FFlags & FFlags)8846 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8847 assert(Lex.getKind() == lltok::kw_funcFlags);
8848 Lex.Lex();
8849
8850 if (parseToken(lltok::colon, "expected ':' in funcFlags") |
8851 parseToken(lltok::lparen, "expected '(' in funcFlags"))
8852 return true;
8853
8854 do {
8855 unsigned Val = 0;
8856 switch (Lex.getKind()) {
8857 case lltok::kw_readNone:
8858 Lex.Lex();
8859 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8860 return true;
8861 FFlags.ReadNone = Val;
8862 break;
8863 case lltok::kw_readOnly:
8864 Lex.Lex();
8865 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8866 return true;
8867 FFlags.ReadOnly = Val;
8868 break;
8869 case lltok::kw_noRecurse:
8870 Lex.Lex();
8871 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8872 return true;
8873 FFlags.NoRecurse = Val;
8874 break;
8875 case lltok::kw_returnDoesNotAlias:
8876 Lex.Lex();
8877 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8878 return true;
8879 FFlags.ReturnDoesNotAlias = Val;
8880 break;
8881 case lltok::kw_noInline:
8882 Lex.Lex();
8883 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8884 return true;
8885 FFlags.NoInline = Val;
8886 break;
8887 case lltok::kw_alwaysInline:
8888 Lex.Lex();
8889 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8890 return true;
8891 FFlags.AlwaysInline = Val;
8892 break;
8893 default:
8894 return error(Lex.getLoc(), "expected function flag type");
8895 }
8896 } while (EatIfPresent(lltok::comma));
8897
8898 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8899 return true;
8900
8901 return false;
8902 }
8903
8904 /// OptionalCalls
8905 /// := 'calls' ':' '(' Call [',' Call]* ')'
8906 /// Call ::= '(' 'callee' ':' GVReference
8907 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> & Calls)8908 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8909 assert(Lex.getKind() == lltok::kw_calls);
8910 Lex.Lex();
8911
8912 if (parseToken(lltok::colon, "expected ':' in calls") |
8913 parseToken(lltok::lparen, "expected '(' in calls"))
8914 return true;
8915
8916 IdToIndexMapType IdToIndexMap;
8917 // parse each call edge
8918 do {
8919 ValueInfo VI;
8920 if (parseToken(lltok::lparen, "expected '(' in call") ||
8921 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8922 parseToken(lltok::colon, "expected ':'"))
8923 return true;
8924
8925 LocTy Loc = Lex.getLoc();
8926 unsigned GVId;
8927 if (parseGVReference(VI, GVId))
8928 return true;
8929
8930 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8931 unsigned RelBF = 0;
8932 if (EatIfPresent(lltok::comma)) {
8933 // Expect either hotness or relbf
8934 if (EatIfPresent(lltok::kw_hotness)) {
8935 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8936 return true;
8937 } else {
8938 if (parseToken(lltok::kw_relbf, "expected relbf") ||
8939 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8940 return true;
8941 }
8942 }
8943 // Keep track of the Call array index needing a forward reference.
8944 // We will save the location of the ValueInfo needing an update, but
8945 // can only do so once the std::vector is finalized.
8946 if (VI.getRef() == FwdVIRef)
8947 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8948 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8949
8950 if (parseToken(lltok::rparen, "expected ')' in call"))
8951 return true;
8952 } while (EatIfPresent(lltok::comma));
8953
8954 // Now that the Calls vector is finalized, it is safe to save the locations
8955 // of any forward GV references that need updating later.
8956 for (auto I : IdToIndexMap) {
8957 auto &Infos = ForwardRefValueInfos[I.first];
8958 for (auto P : I.second) {
8959 assert(Calls[P.first].first.getRef() == FwdVIRef &&
8960 "Forward referenced ValueInfo expected to be empty");
8961 Infos.emplace_back(&Calls[P.first].first, P.second);
8962 }
8963 }
8964
8965 if (parseToken(lltok::rparen, "expected ')' in calls"))
8966 return true;
8967
8968 return false;
8969 }
8970
8971 /// Hotness
8972 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
parseHotness(CalleeInfo::HotnessType & Hotness)8973 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8974 switch (Lex.getKind()) {
8975 case lltok::kw_unknown:
8976 Hotness = CalleeInfo::HotnessType::Unknown;
8977 break;
8978 case lltok::kw_cold:
8979 Hotness = CalleeInfo::HotnessType::Cold;
8980 break;
8981 case lltok::kw_none:
8982 Hotness = CalleeInfo::HotnessType::None;
8983 break;
8984 case lltok::kw_hot:
8985 Hotness = CalleeInfo::HotnessType::Hot;
8986 break;
8987 case lltok::kw_critical:
8988 Hotness = CalleeInfo::HotnessType::Critical;
8989 break;
8990 default:
8991 return error(Lex.getLoc(), "invalid call edge hotness");
8992 }
8993 Lex.Lex();
8994 return false;
8995 }
8996
8997 /// OptionalVTableFuncs
8998 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8999 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
parseOptionalVTableFuncs(VTableFuncList & VTableFuncs)9000 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9001 assert(Lex.getKind() == lltok::kw_vTableFuncs);
9002 Lex.Lex();
9003
9004 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") |
9005 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9006 return true;
9007
9008 IdToIndexMapType IdToIndexMap;
9009 // parse each virtual function pair
9010 do {
9011 ValueInfo VI;
9012 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9013 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9014 parseToken(lltok::colon, "expected ':'"))
9015 return true;
9016
9017 LocTy Loc = Lex.getLoc();
9018 unsigned GVId;
9019 if (parseGVReference(VI, GVId))
9020 return true;
9021
9022 uint64_t Offset;
9023 if (parseToken(lltok::comma, "expected comma") ||
9024 parseToken(lltok::kw_offset, "expected offset") ||
9025 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9026 return true;
9027
9028 // Keep track of the VTableFuncs array index needing a forward reference.
9029 // We will save the location of the ValueInfo needing an update, but
9030 // can only do so once the std::vector is finalized.
9031 if (VI == EmptyVI)
9032 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9033 VTableFuncs.push_back({VI, Offset});
9034
9035 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9036 return true;
9037 } while (EatIfPresent(lltok::comma));
9038
9039 // Now that the VTableFuncs vector is finalized, it is safe to save the
9040 // locations of any forward GV references that need updating later.
9041 for (auto I : IdToIndexMap) {
9042 auto &Infos = ForwardRefValueInfos[I.first];
9043 for (auto P : I.second) {
9044 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9045 "Forward referenced ValueInfo expected to be empty");
9046 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9047 }
9048 }
9049
9050 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9051 return true;
9052
9053 return false;
9054 }
9055
9056 /// ParamNo := 'param' ':' UInt64
parseParamNo(uint64_t & ParamNo)9057 bool LLParser::parseParamNo(uint64_t &ParamNo) {
9058 if (parseToken(lltok::kw_param, "expected 'param' here") ||
9059 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9060 return true;
9061 return false;
9062 }
9063
9064 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
parseParamAccessOffset(ConstantRange & Range)9065 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9066 APSInt Lower;
9067 APSInt Upper;
9068 auto ParseAPSInt = [&](APSInt &Val) {
9069 if (Lex.getKind() != lltok::APSInt)
9070 return tokError("expected integer");
9071 Val = Lex.getAPSIntVal();
9072 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9073 Val.setIsSigned(true);
9074 Lex.Lex();
9075 return false;
9076 };
9077 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9078 parseToken(lltok::colon, "expected ':' here") ||
9079 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9080 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9081 parseToken(lltok::rsquare, "expected ']' here"))
9082 return true;
9083
9084 ++Upper;
9085 Range =
9086 (Lower == Upper && !Lower.isMaxValue())
9087 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9088 : ConstantRange(Lower, Upper);
9089
9090 return false;
9091 }
9092
9093 /// ParamAccessCall
9094 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
parseParamAccessCall(FunctionSummary::ParamAccess::Call & Call,IdLocListType & IdLocList)9095 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9096 IdLocListType &IdLocList) {
9097 if (parseToken(lltok::lparen, "expected '(' here") ||
9098 parseToken(lltok::kw_callee, "expected 'callee' here") ||
9099 parseToken(lltok::colon, "expected ':' here"))
9100 return true;
9101
9102 unsigned GVId;
9103 ValueInfo VI;
9104 LocTy Loc = Lex.getLoc();
9105 if (parseGVReference(VI, GVId))
9106 return true;
9107
9108 Call.Callee = VI;
9109 IdLocList.emplace_back(GVId, Loc);
9110
9111 if (parseToken(lltok::comma, "expected ',' here") ||
9112 parseParamNo(Call.ParamNo) ||
9113 parseToken(lltok::comma, "expected ',' here") ||
9114 parseParamAccessOffset(Call.Offsets))
9115 return true;
9116
9117 if (parseToken(lltok::rparen, "expected ')' here"))
9118 return true;
9119
9120 return false;
9121 }
9122
9123 /// ParamAccess
9124 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9125 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
parseParamAccess(FunctionSummary::ParamAccess & Param,IdLocListType & IdLocList)9126 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9127 IdLocListType &IdLocList) {
9128 if (parseToken(lltok::lparen, "expected '(' here") ||
9129 parseParamNo(Param.ParamNo) ||
9130 parseToken(lltok::comma, "expected ',' here") ||
9131 parseParamAccessOffset(Param.Use))
9132 return true;
9133
9134 if (EatIfPresent(lltok::comma)) {
9135 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9136 parseToken(lltok::colon, "expected ':' here") ||
9137 parseToken(lltok::lparen, "expected '(' here"))
9138 return true;
9139 do {
9140 FunctionSummary::ParamAccess::Call Call;
9141 if (parseParamAccessCall(Call, IdLocList))
9142 return true;
9143 Param.Calls.push_back(Call);
9144 } while (EatIfPresent(lltok::comma));
9145
9146 if (parseToken(lltok::rparen, "expected ')' here"))
9147 return true;
9148 }
9149
9150 if (parseToken(lltok::rparen, "expected ')' here"))
9151 return true;
9152
9153 return false;
9154 }
9155
9156 /// OptionalParamAccesses
9157 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
parseOptionalParamAccesses(std::vector<FunctionSummary::ParamAccess> & Params)9158 bool LLParser::parseOptionalParamAccesses(
9159 std::vector<FunctionSummary::ParamAccess> &Params) {
9160 assert(Lex.getKind() == lltok::kw_params);
9161 Lex.Lex();
9162
9163 if (parseToken(lltok::colon, "expected ':' here") ||
9164 parseToken(lltok::lparen, "expected '(' here"))
9165 return true;
9166
9167 IdLocListType VContexts;
9168 size_t CallsNum = 0;
9169 do {
9170 FunctionSummary::ParamAccess ParamAccess;
9171 if (parseParamAccess(ParamAccess, VContexts))
9172 return true;
9173 CallsNum += ParamAccess.Calls.size();
9174 assert(VContexts.size() == CallsNum);
9175 Params.emplace_back(std::move(ParamAccess));
9176 } while (EatIfPresent(lltok::comma));
9177
9178 if (parseToken(lltok::rparen, "expected ')' here"))
9179 return true;
9180
9181 // Now that the Params is finalized, it is safe to save the locations
9182 // of any forward GV references that need updating later.
9183 IdLocListType::const_iterator ItContext = VContexts.begin();
9184 for (auto &PA : Params) {
9185 for (auto &C : PA.Calls) {
9186 if (C.Callee.getRef() == FwdVIRef)
9187 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9188 ItContext->second);
9189 ++ItContext;
9190 }
9191 }
9192 assert(ItContext == VContexts.end());
9193
9194 return false;
9195 }
9196
9197 /// OptionalRefs
9198 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
parseOptionalRefs(std::vector<ValueInfo> & Refs)9199 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9200 assert(Lex.getKind() == lltok::kw_refs);
9201 Lex.Lex();
9202
9203 if (parseToken(lltok::colon, "expected ':' in refs") ||
9204 parseToken(lltok::lparen, "expected '(' in refs"))
9205 return true;
9206
9207 struct ValueContext {
9208 ValueInfo VI;
9209 unsigned GVId;
9210 LocTy Loc;
9211 };
9212 std::vector<ValueContext> VContexts;
9213 // parse each ref edge
9214 do {
9215 ValueContext VC;
9216 VC.Loc = Lex.getLoc();
9217 if (parseGVReference(VC.VI, VC.GVId))
9218 return true;
9219 VContexts.push_back(VC);
9220 } while (EatIfPresent(lltok::comma));
9221
9222 // Sort value contexts so that ones with writeonly
9223 // and readonly ValueInfo are at the end of VContexts vector.
9224 // See FunctionSummary::specialRefCounts()
9225 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9226 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9227 });
9228
9229 IdToIndexMapType IdToIndexMap;
9230 for (auto &VC : VContexts) {
9231 // Keep track of the Refs array index needing a forward reference.
9232 // We will save the location of the ValueInfo needing an update, but
9233 // can only do so once the std::vector is finalized.
9234 if (VC.VI.getRef() == FwdVIRef)
9235 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9236 Refs.push_back(VC.VI);
9237 }
9238
9239 // Now that the Refs vector is finalized, it is safe to save the locations
9240 // of any forward GV references that need updating later.
9241 for (auto I : IdToIndexMap) {
9242 auto &Infos = ForwardRefValueInfos[I.first];
9243 for (auto P : I.second) {
9244 assert(Refs[P.first].getRef() == FwdVIRef &&
9245 "Forward referenced ValueInfo expected to be empty");
9246 Infos.emplace_back(&Refs[P.first], P.second);
9247 }
9248 }
9249
9250 if (parseToken(lltok::rparen, "expected ')' in refs"))
9251 return true;
9252
9253 return false;
9254 }
9255
9256 /// OptionalTypeIdInfo
9257 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9258 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9259 /// [',' TypeCheckedLoadConstVCalls]? ')'
parseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo & TypeIdInfo)9260 bool LLParser::parseOptionalTypeIdInfo(
9261 FunctionSummary::TypeIdInfo &TypeIdInfo) {
9262 assert(Lex.getKind() == lltok::kw_typeIdInfo);
9263 Lex.Lex();
9264
9265 if (parseToken(lltok::colon, "expected ':' here") ||
9266 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9267 return true;
9268
9269 do {
9270 switch (Lex.getKind()) {
9271 case lltok::kw_typeTests:
9272 if (parseTypeTests(TypeIdInfo.TypeTests))
9273 return true;
9274 break;
9275 case lltok::kw_typeTestAssumeVCalls:
9276 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9277 TypeIdInfo.TypeTestAssumeVCalls))
9278 return true;
9279 break;
9280 case lltok::kw_typeCheckedLoadVCalls:
9281 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9282 TypeIdInfo.TypeCheckedLoadVCalls))
9283 return true;
9284 break;
9285 case lltok::kw_typeTestAssumeConstVCalls:
9286 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9287 TypeIdInfo.TypeTestAssumeConstVCalls))
9288 return true;
9289 break;
9290 case lltok::kw_typeCheckedLoadConstVCalls:
9291 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9292 TypeIdInfo.TypeCheckedLoadConstVCalls))
9293 return true;
9294 break;
9295 default:
9296 return error(Lex.getLoc(), "invalid typeIdInfo list type");
9297 }
9298 } while (EatIfPresent(lltok::comma));
9299
9300 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9301 return true;
9302
9303 return false;
9304 }
9305
9306 /// TypeTests
9307 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9308 /// [',' (SummaryID | UInt64)]* ')'
parseTypeTests(std::vector<GlobalValue::GUID> & TypeTests)9309 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9310 assert(Lex.getKind() == lltok::kw_typeTests);
9311 Lex.Lex();
9312
9313 if (parseToken(lltok::colon, "expected ':' here") ||
9314 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9315 return true;
9316
9317 IdToIndexMapType IdToIndexMap;
9318 do {
9319 GlobalValue::GUID GUID = 0;
9320 if (Lex.getKind() == lltok::SummaryID) {
9321 unsigned ID = Lex.getUIntVal();
9322 LocTy Loc = Lex.getLoc();
9323 // Keep track of the TypeTests array index needing a forward reference.
9324 // We will save the location of the GUID needing an update, but
9325 // can only do so once the std::vector is finalized.
9326 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9327 Lex.Lex();
9328 } else if (parseUInt64(GUID))
9329 return true;
9330 TypeTests.push_back(GUID);
9331 } while (EatIfPresent(lltok::comma));
9332
9333 // Now that the TypeTests vector is finalized, it is safe to save the
9334 // locations of any forward GV references that need updating later.
9335 for (auto I : IdToIndexMap) {
9336 auto &Ids = ForwardRefTypeIds[I.first];
9337 for (auto P : I.second) {
9338 assert(TypeTests[P.first] == 0 &&
9339 "Forward referenced type id GUID expected to be 0");
9340 Ids.emplace_back(&TypeTests[P.first], P.second);
9341 }
9342 }
9343
9344 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9345 return true;
9346
9347 return false;
9348 }
9349
9350 /// VFuncIdList
9351 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
parseVFuncIdList(lltok::Kind Kind,std::vector<FunctionSummary::VFuncId> & VFuncIdList)9352 bool LLParser::parseVFuncIdList(
9353 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9354 assert(Lex.getKind() == Kind);
9355 Lex.Lex();
9356
9357 if (parseToken(lltok::colon, "expected ':' here") ||
9358 parseToken(lltok::lparen, "expected '(' here"))
9359 return true;
9360
9361 IdToIndexMapType IdToIndexMap;
9362 do {
9363 FunctionSummary::VFuncId VFuncId;
9364 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9365 return true;
9366 VFuncIdList.push_back(VFuncId);
9367 } while (EatIfPresent(lltok::comma));
9368
9369 if (parseToken(lltok::rparen, "expected ')' here"))
9370 return true;
9371
9372 // Now that the VFuncIdList vector is finalized, it is safe to save the
9373 // locations of any forward GV references that need updating later.
9374 for (auto I : IdToIndexMap) {
9375 auto &Ids = ForwardRefTypeIds[I.first];
9376 for (auto P : I.second) {
9377 assert(VFuncIdList[P.first].GUID == 0 &&
9378 "Forward referenced type id GUID expected to be 0");
9379 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9380 }
9381 }
9382
9383 return false;
9384 }
9385
9386 /// ConstVCallList
9387 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
parseConstVCallList(lltok::Kind Kind,std::vector<FunctionSummary::ConstVCall> & ConstVCallList)9388 bool LLParser::parseConstVCallList(
9389 lltok::Kind Kind,
9390 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9391 assert(Lex.getKind() == Kind);
9392 Lex.Lex();
9393
9394 if (parseToken(lltok::colon, "expected ':' here") ||
9395 parseToken(lltok::lparen, "expected '(' here"))
9396 return true;
9397
9398 IdToIndexMapType IdToIndexMap;
9399 do {
9400 FunctionSummary::ConstVCall ConstVCall;
9401 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9402 return true;
9403 ConstVCallList.push_back(ConstVCall);
9404 } while (EatIfPresent(lltok::comma));
9405
9406 if (parseToken(lltok::rparen, "expected ')' here"))
9407 return true;
9408
9409 // Now that the ConstVCallList vector is finalized, it is safe to save the
9410 // locations of any forward GV references that need updating later.
9411 for (auto I : IdToIndexMap) {
9412 auto &Ids = ForwardRefTypeIds[I.first];
9413 for (auto P : I.second) {
9414 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9415 "Forward referenced type id GUID expected to be 0");
9416 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9417 }
9418 }
9419
9420 return false;
9421 }
9422
9423 /// ConstVCall
9424 /// ::= '(' VFuncId ',' Args ')'
parseConstVCall(FunctionSummary::ConstVCall & ConstVCall,IdToIndexMapType & IdToIndexMap,unsigned Index)9425 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9426 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9427 if (parseToken(lltok::lparen, "expected '(' here") ||
9428 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9429 return true;
9430
9431 if (EatIfPresent(lltok::comma))
9432 if (parseArgs(ConstVCall.Args))
9433 return true;
9434
9435 if (parseToken(lltok::rparen, "expected ')' here"))
9436 return true;
9437
9438 return false;
9439 }
9440
9441 /// VFuncId
9442 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9443 /// 'offset' ':' UInt64 ')'
parseVFuncId(FunctionSummary::VFuncId & VFuncId,IdToIndexMapType & IdToIndexMap,unsigned Index)9444 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9445 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9446 assert(Lex.getKind() == lltok::kw_vFuncId);
9447 Lex.Lex();
9448
9449 if (parseToken(lltok::colon, "expected ':' here") ||
9450 parseToken(lltok::lparen, "expected '(' here"))
9451 return true;
9452
9453 if (Lex.getKind() == lltok::SummaryID) {
9454 VFuncId.GUID = 0;
9455 unsigned ID = Lex.getUIntVal();
9456 LocTy Loc = Lex.getLoc();
9457 // Keep track of the array index needing a forward reference.
9458 // We will save the location of the GUID needing an update, but
9459 // can only do so once the caller's std::vector is finalized.
9460 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9461 Lex.Lex();
9462 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9463 parseToken(lltok::colon, "expected ':' here") ||
9464 parseUInt64(VFuncId.GUID))
9465 return true;
9466
9467 if (parseToken(lltok::comma, "expected ',' here") ||
9468 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9469 parseToken(lltok::colon, "expected ':' here") ||
9470 parseUInt64(VFuncId.Offset) ||
9471 parseToken(lltok::rparen, "expected ')' here"))
9472 return true;
9473
9474 return false;
9475 }
9476
9477 /// GVFlags
9478 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9479 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9480 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9481 /// 'canAutoHide' ':' Flag ',' ')'
parseGVFlags(GlobalValueSummary::GVFlags & GVFlags)9482 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9483 assert(Lex.getKind() == lltok::kw_flags);
9484 Lex.Lex();
9485
9486 if (parseToken(lltok::colon, "expected ':' here") ||
9487 parseToken(lltok::lparen, "expected '(' here"))
9488 return true;
9489
9490 do {
9491 unsigned Flag = 0;
9492 switch (Lex.getKind()) {
9493 case lltok::kw_linkage:
9494 Lex.Lex();
9495 if (parseToken(lltok::colon, "expected ':'"))
9496 return true;
9497 bool HasLinkage;
9498 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9499 assert(HasLinkage && "Linkage not optional in summary entry");
9500 Lex.Lex();
9501 break;
9502 case lltok::kw_visibility:
9503 Lex.Lex();
9504 if (parseToken(lltok::colon, "expected ':'"))
9505 return true;
9506 parseOptionalVisibility(Flag);
9507 GVFlags.Visibility = Flag;
9508 break;
9509 case lltok::kw_notEligibleToImport:
9510 Lex.Lex();
9511 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9512 return true;
9513 GVFlags.NotEligibleToImport = Flag;
9514 break;
9515 case lltok::kw_live:
9516 Lex.Lex();
9517 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9518 return true;
9519 GVFlags.Live = Flag;
9520 break;
9521 case lltok::kw_dsoLocal:
9522 Lex.Lex();
9523 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9524 return true;
9525 GVFlags.DSOLocal = Flag;
9526 break;
9527 case lltok::kw_canAutoHide:
9528 Lex.Lex();
9529 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9530 return true;
9531 GVFlags.CanAutoHide = Flag;
9532 break;
9533 default:
9534 return error(Lex.getLoc(), "expected gv flag type");
9535 }
9536 } while (EatIfPresent(lltok::comma));
9537
9538 if (parseToken(lltok::rparen, "expected ')' here"))
9539 return true;
9540
9541 return false;
9542 }
9543
9544 /// GVarFlags
9545 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9546 /// ',' 'writeonly' ':' Flag
9547 /// ',' 'constant' ':' Flag ')'
parseGVarFlags(GlobalVarSummary::GVarFlags & GVarFlags)9548 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9549 assert(Lex.getKind() == lltok::kw_varFlags);
9550 Lex.Lex();
9551
9552 if (parseToken(lltok::colon, "expected ':' here") ||
9553 parseToken(lltok::lparen, "expected '(' here"))
9554 return true;
9555
9556 auto ParseRest = [this](unsigned int &Val) {
9557 Lex.Lex();
9558 if (parseToken(lltok::colon, "expected ':'"))
9559 return true;
9560 return parseFlag(Val);
9561 };
9562
9563 do {
9564 unsigned Flag = 0;
9565 switch (Lex.getKind()) {
9566 case lltok::kw_readonly:
9567 if (ParseRest(Flag))
9568 return true;
9569 GVarFlags.MaybeReadOnly = Flag;
9570 break;
9571 case lltok::kw_writeonly:
9572 if (ParseRest(Flag))
9573 return true;
9574 GVarFlags.MaybeWriteOnly = Flag;
9575 break;
9576 case lltok::kw_constant:
9577 if (ParseRest(Flag))
9578 return true;
9579 GVarFlags.Constant = Flag;
9580 break;
9581 case lltok::kw_vcall_visibility:
9582 if (ParseRest(Flag))
9583 return true;
9584 GVarFlags.VCallVisibility = Flag;
9585 break;
9586 default:
9587 return error(Lex.getLoc(), "expected gvar flag type");
9588 }
9589 } while (EatIfPresent(lltok::comma));
9590 return parseToken(lltok::rparen, "expected ')' here");
9591 }
9592
9593 /// ModuleReference
9594 /// ::= 'module' ':' UInt
parseModuleReference(StringRef & ModulePath)9595 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9596 // parse module id.
9597 if (parseToken(lltok::kw_module, "expected 'module' here") ||
9598 parseToken(lltok::colon, "expected ':' here") ||
9599 parseToken(lltok::SummaryID, "expected module ID"))
9600 return true;
9601
9602 unsigned ModuleID = Lex.getUIntVal();
9603 auto I = ModuleIdMap.find(ModuleID);
9604 // We should have already parsed all module IDs
9605 assert(I != ModuleIdMap.end());
9606 ModulePath = I->second;
9607 return false;
9608 }
9609
9610 /// GVReference
9611 /// ::= SummaryID
parseGVReference(ValueInfo & VI,unsigned & GVId)9612 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9613 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9614 if (!ReadOnly)
9615 WriteOnly = EatIfPresent(lltok::kw_writeonly);
9616 if (parseToken(lltok::SummaryID, "expected GV ID"))
9617 return true;
9618
9619 GVId = Lex.getUIntVal();
9620 // Check if we already have a VI for this GV
9621 if (GVId < NumberedValueInfos.size()) {
9622 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9623 VI = NumberedValueInfos[GVId];
9624 } else
9625 // We will create a forward reference to the stored location.
9626 VI = ValueInfo(false, FwdVIRef);
9627
9628 if (ReadOnly)
9629 VI.setReadOnly();
9630 if (WriteOnly)
9631 VI.setWriteOnly();
9632 return false;
9633 }
9634