1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the parser class for .ll files.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/ScopeExit.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/Operator.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/ModRef.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
57 static std::string
getTypeString(Type
*T
) {
59 raw_string_ostream
Tmp(Result
);
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run(bool UpgradeDebugInfo
,
66 DataLayoutCallbackTy DataLayoutCallback
) {
70 if (Context
.shouldDiscardValueNames())
73 "Can't read textual IR with a Context that discards named Values");
76 if (parseTargetDefinitions(DataLayoutCallback
))
80 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo
) ||
84 bool LLParser::parseStandaloneConstantValue(Constant
*&C
,
85 const SlotMapping
*Slots
) {
86 restoreParsingState(Slots
);
90 if (parseType(Ty
) || parseConstantValue(Ty
, C
))
92 if (Lex
.getKind() != lltok::Eof
)
93 return error(Lex
.getLoc(), "expected end of string");
97 bool LLParser::parseTypeAtBeginning(Type
*&Ty
, unsigned &Read
,
98 const SlotMapping
*Slots
) {
99 restoreParsingState(Slots
);
103 SMLoc Start
= Lex
.getLoc();
107 SMLoc End
= Lex
.getLoc();
108 Read
= End
.getPointer() - Start
.getPointer();
113 void LLParser::restoreParsingState(const SlotMapping
*Slots
) {
116 NumberedVals
= Slots
->GlobalValues
;
117 NumberedMetadata
= Slots
->MetadataNodes
;
118 for (const auto &I
: Slots
->NamedTypes
)
120 std::make_pair(I
.getKey(), std::make_pair(I
.second
, LocTy())));
121 for (const auto &I
: Slots
->Types
)
122 NumberedTypes
.insert(
123 std::make_pair(I
.first
, std::make_pair(I
.second
, LocTy())));
126 /// validateEndOfModule - Do final validity and basic correctness checks at the
127 /// end of the module.
128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo
) {
131 // Handle any function attribute group forward references.
132 for (const auto &RAG
: ForwardRefAttrGroups
) {
133 Value
*V
= RAG
.first
;
134 const std::vector
<unsigned> &Attrs
= RAG
.second
;
135 AttrBuilder
B(Context
);
137 for (const auto &Attr
: Attrs
) {
138 auto R
= NumberedAttrBuilders
.find(Attr
);
139 if (R
!= NumberedAttrBuilders
.end())
143 if (Function
*Fn
= dyn_cast
<Function
>(V
)) {
144 AttributeList AS
= Fn
->getAttributes();
145 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
146 AS
= AS
.removeFnAttributes(Context
);
150 // If the alignment was parsed as an attribute, move to the alignment
152 if (MaybeAlign A
= FnAttrs
.getAlignment()) {
153 Fn
->setAlignment(*A
);
154 FnAttrs
.removeAttribute(Attribute::Alignment
);
157 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
158 Fn
->setAttributes(AS
);
159 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(V
)) {
160 AttributeList AS
= CI
->getAttributes();
161 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
162 AS
= AS
.removeFnAttributes(Context
);
164 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
165 CI
->setAttributes(AS
);
166 } else if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(V
)) {
167 AttributeList AS
= II
->getAttributes();
168 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
169 AS
= AS
.removeFnAttributes(Context
);
171 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
172 II
->setAttributes(AS
);
173 } else if (CallBrInst
*CBI
= dyn_cast
<CallBrInst
>(V
)) {
174 AttributeList AS
= CBI
->getAttributes();
175 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
176 AS
= AS
.removeFnAttributes(Context
);
178 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
179 CBI
->setAttributes(AS
);
180 } else if (auto *GV
= dyn_cast
<GlobalVariable
>(V
)) {
181 AttrBuilder
Attrs(M
->getContext(), GV
->getAttributes());
183 GV
->setAttributes(AttributeSet::get(Context
,Attrs
));
185 llvm_unreachable("invalid object with forward attribute group reference");
189 // If there are entries in ForwardRefBlockAddresses at this point, the
190 // function was never defined.
191 if (!ForwardRefBlockAddresses
.empty())
192 return error(ForwardRefBlockAddresses
.begin()->first
.Loc
,
193 "expected function name in blockaddress");
195 auto ResolveForwardRefDSOLocalEquivalents
= [&](const ValID
&GVRef
,
196 GlobalValue
*FwdRef
) {
197 GlobalValue
*GV
= nullptr;
198 if (GVRef
.Kind
== ValID::t_GlobalName
) {
199 GV
= M
->getNamedValue(GVRef
.StrVal
);
200 } else if (GVRef
.UIntVal
< NumberedVals
.size()) {
201 GV
= dyn_cast
<GlobalValue
>(NumberedVals
[GVRef
.UIntVal
]);
205 return error(GVRef
.Loc
, "unknown function '" + GVRef
.StrVal
+
206 "' referenced by dso_local_equivalent");
208 if (!GV
->getValueType()->isFunctionTy())
209 return error(GVRef
.Loc
,
210 "expected a function, alias to function, or ifunc "
211 "in dso_local_equivalent");
213 auto *Equiv
= DSOLocalEquivalent::get(GV
);
214 FwdRef
->replaceAllUsesWith(Equiv
);
215 FwdRef
->eraseFromParent();
219 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
220 // point, they are references after the function was defined. Resolve those
222 for (auto &Iter
: ForwardRefDSOLocalEquivalentIDs
) {
223 if (ResolveForwardRefDSOLocalEquivalents(Iter
.first
, Iter
.second
))
226 for (auto &Iter
: ForwardRefDSOLocalEquivalentNames
) {
227 if (ResolveForwardRefDSOLocalEquivalents(Iter
.first
, Iter
.second
))
230 ForwardRefDSOLocalEquivalentIDs
.clear();
231 ForwardRefDSOLocalEquivalentNames
.clear();
233 for (const auto &NT
: NumberedTypes
)
234 if (NT
.second
.second
.isValid())
235 return error(NT
.second
.second
,
236 "use of undefined type '%" + Twine(NT
.first
) + "'");
238 for (StringMap
<std::pair
<Type
*, LocTy
> >::iterator I
=
239 NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
)
240 if (I
->second
.second
.isValid())
241 return error(I
->second
.second
,
242 "use of undefined type named '" + I
->getKey() + "'");
244 if (!ForwardRefComdats
.empty())
245 return error(ForwardRefComdats
.begin()->second
,
246 "use of undefined comdat '$" +
247 ForwardRefComdats
.begin()->first
+ "'");
249 if (!ForwardRefVals
.empty())
250 return error(ForwardRefVals
.begin()->second
.second
,
251 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
254 if (!ForwardRefValIDs
.empty())
255 return error(ForwardRefValIDs
.begin()->second
.second
,
256 "use of undefined value '@" +
257 Twine(ForwardRefValIDs
.begin()->first
) + "'");
259 if (!ForwardRefMDNodes
.empty())
260 return error(ForwardRefMDNodes
.begin()->second
.second
,
261 "use of undefined metadata '!" +
262 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
264 // Resolve metadata cycles.
265 for (auto &N
: NumberedMetadata
) {
266 if (N
.second
&& !N
.second
->isResolved())
267 N
.second
->resolveCycles();
270 for (auto *Inst
: InstsWithTBAATag
) {
271 MDNode
*MD
= Inst
->getMetadata(LLVMContext::MD_tbaa
);
272 assert(MD
&& "UpgradeInstWithTBAATag should have a TBAA tag");
273 auto *UpgradedMD
= UpgradeTBAANode(*MD
);
274 if (MD
!= UpgradedMD
)
275 Inst
->setMetadata(LLVMContext::MD_tbaa
, UpgradedMD
);
278 // Look for intrinsic functions and CallInst that need to be upgraded. We use
279 // make_early_inc_range here because we may remove some functions.
280 for (Function
&F
: llvm::make_early_inc_range(*M
))
281 UpgradeCallsToIntrinsic(&F
);
283 if (UpgradeDebugInfo
)
284 llvm::UpgradeDebugInfo(*M
);
286 UpgradeModuleFlags(*M
);
287 UpgradeSectionAttributes(*M
);
291 // Initialize the slot mapping.
292 // Because by this point we've parsed and validated everything, we can "steal"
293 // the mapping from LLParser as it doesn't need it anymore.
294 Slots
->GlobalValues
= std::move(NumberedVals
);
295 Slots
->MetadataNodes
= std::move(NumberedMetadata
);
296 for (const auto &I
: NamedTypes
)
297 Slots
->NamedTypes
.insert(std::make_pair(I
.getKey(), I
.second
.first
));
298 for (const auto &I
: NumberedTypes
)
299 Slots
->Types
.insert(std::make_pair(I
.first
, I
.second
.first
));
304 /// Do final validity and basic correctness checks at the end of the index.
305 bool LLParser::validateEndOfIndex() {
309 if (!ForwardRefValueInfos
.empty())
310 return error(ForwardRefValueInfos
.begin()->second
.front().second
,
311 "use of undefined summary '^" +
312 Twine(ForwardRefValueInfos
.begin()->first
) + "'");
314 if (!ForwardRefAliasees
.empty())
315 return error(ForwardRefAliasees
.begin()->second
.front().second
,
316 "use of undefined summary '^" +
317 Twine(ForwardRefAliasees
.begin()->first
) + "'");
319 if (!ForwardRefTypeIds
.empty())
320 return error(ForwardRefTypeIds
.begin()->second
.front().second
,
321 "use of undefined type id summary '^" +
322 Twine(ForwardRefTypeIds
.begin()->first
) + "'");
327 //===----------------------------------------------------------------------===//
328 // Top-Level Entities
329 //===----------------------------------------------------------------------===//
331 bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback
) {
332 // Delay parsing of the data layout string until the target triple is known.
333 // Then, pass both the the target triple and the tentative data layout string
334 // to DataLayoutCallback, allowing to override the DL string.
335 // This enables importing modules with invalid DL strings.
336 std::string TentativeDLStr
= M
->getDataLayoutStr();
341 switch (Lex
.getKind()) {
342 case lltok::kw_target
:
343 if (parseTargetDefinition(TentativeDLStr
, DLStrLoc
))
346 case lltok::kw_source_filename
:
347 if (parseSourceFileName())
354 // Run the override callback to potentially change the data layout string, and
355 // parse the data layout string.
356 if (auto LayoutOverride
=
357 DataLayoutCallback(M
->getTargetTriple(), TentativeDLStr
)) {
358 TentativeDLStr
= *LayoutOverride
;
361 Expected
<DataLayout
> MaybeDL
= DataLayout::parse(TentativeDLStr
);
363 return error(DLStrLoc
, toString(MaybeDL
.takeError()));
364 M
->setDataLayout(MaybeDL
.get());
368 bool LLParser::parseTopLevelEntities() {
369 // If there is no Module, then parse just the summary index entries.
372 switch (Lex
.getKind()) {
375 case lltok::SummaryID
:
376 if (parseSummaryEntry())
379 case lltok::kw_source_filename
:
380 if (parseSourceFileName())
384 // Skip everything else
390 switch (Lex
.getKind()) {
392 return tokError("expected top-level entity");
393 case lltok::Eof
: return false;
394 case lltok::kw_declare
:
398 case lltok::kw_define
:
402 case lltok::kw_module
:
403 if (parseModuleAsm())
406 case lltok::LocalVarID
:
407 if (parseUnnamedType())
410 case lltok::LocalVar
:
411 if (parseNamedType())
414 case lltok::GlobalID
:
415 if (parseUnnamedGlobal())
418 case lltok::GlobalVar
:
419 if (parseNamedGlobal())
422 case lltok::ComdatVar
: if (parseComdat()) return true; break;
424 if (parseStandaloneMetadata())
427 case lltok::SummaryID
:
428 if (parseSummaryEntry())
431 case lltok::MetadataVar
:
432 if (parseNamedMetadata())
435 case lltok::kw_attributes
:
436 if (parseUnnamedAttrGrp())
439 case lltok::kw_uselistorder
:
440 if (parseUseListOrder())
443 case lltok::kw_uselistorder_bb
:
444 if (parseUseListOrderBB())
452 /// ::= 'module' 'asm' STRINGCONSTANT
453 bool LLParser::parseModuleAsm() {
454 assert(Lex
.getKind() == lltok::kw_module
);
458 if (parseToken(lltok::kw_asm
, "expected 'module asm'") ||
459 parseStringConstant(AsmStr
))
462 M
->appendModuleInlineAsm(AsmStr
);
467 /// ::= 'target' 'triple' '=' STRINGCONSTANT
468 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
469 bool LLParser::parseTargetDefinition(std::string
&TentativeDLStr
,
471 assert(Lex
.getKind() == lltok::kw_target
);
475 return tokError("unknown target property");
476 case lltok::kw_triple
:
478 if (parseToken(lltok::equal
, "expected '=' after target triple") ||
479 parseStringConstant(Str
))
481 M
->setTargetTriple(Str
);
483 case lltok::kw_datalayout
:
485 if (parseToken(lltok::equal
, "expected '=' after target datalayout"))
487 DLStrLoc
= Lex
.getLoc();
488 if (parseStringConstant(TentativeDLStr
))
495 /// ::= 'source_filename' '=' STRINGCONSTANT
496 bool LLParser::parseSourceFileName() {
497 assert(Lex
.getKind() == lltok::kw_source_filename
);
499 if (parseToken(lltok::equal
, "expected '=' after source_filename") ||
500 parseStringConstant(SourceFileName
))
503 M
->setSourceFileName(SourceFileName
);
507 /// parseUnnamedType:
508 /// ::= LocalVarID '=' 'type' type
509 bool LLParser::parseUnnamedType() {
510 LocTy TypeLoc
= Lex
.getLoc();
511 unsigned TypeID
= Lex
.getUIntVal();
512 Lex
.Lex(); // eat LocalVarID;
514 if (parseToken(lltok::equal
, "expected '=' after name") ||
515 parseToken(lltok::kw_type
, "expected 'type' after '='"))
518 Type
*Result
= nullptr;
519 if (parseStructDefinition(TypeLoc
, "", NumberedTypes
[TypeID
], Result
))
522 if (!isa
<StructType
>(Result
)) {
523 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[TypeID
];
525 return error(TypeLoc
, "non-struct types may not be recursive");
526 Entry
.first
= Result
;
527 Entry
.second
= SMLoc();
534 /// ::= LocalVar '=' 'type' type
535 bool LLParser::parseNamedType() {
536 std::string Name
= Lex
.getStrVal();
537 LocTy NameLoc
= Lex
.getLoc();
538 Lex
.Lex(); // eat LocalVar.
540 if (parseToken(lltok::equal
, "expected '=' after name") ||
541 parseToken(lltok::kw_type
, "expected 'type' after name"))
544 Type
*Result
= nullptr;
545 if (parseStructDefinition(NameLoc
, Name
, NamedTypes
[Name
], Result
))
548 if (!isa
<StructType
>(Result
)) {
549 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Name
];
551 return error(NameLoc
, "non-struct types may not be recursive");
552 Entry
.first
= Result
;
553 Entry
.second
= SMLoc();
560 /// ::= 'declare' FunctionHeader
561 bool LLParser::parseDeclare() {
562 assert(Lex
.getKind() == lltok::kw_declare
);
565 std::vector
<std::pair
<unsigned, MDNode
*>> MDs
;
566 while (Lex
.getKind() == lltok::MetadataVar
) {
569 if (parseMetadataAttachment(MDK
, N
))
571 MDs
.push_back({MDK
, N
});
575 if (parseFunctionHeader(F
, false))
578 F
->addMetadata(MD
.first
, *MD
.second
);
583 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
584 bool LLParser::parseDefine() {
585 assert(Lex
.getKind() == lltok::kw_define
);
589 return parseFunctionHeader(F
, true) || parseOptionalFunctionMetadata(*F
) ||
590 parseFunctionBody(*F
);
596 bool LLParser::parseGlobalType(bool &IsConstant
) {
597 if (Lex
.getKind() == lltok::kw_constant
)
599 else if (Lex
.getKind() == lltok::kw_global
)
603 return tokError("expected 'global' or 'constant'");
609 bool LLParser::parseOptionalUnnamedAddr(
610 GlobalVariable::UnnamedAddr
&UnnamedAddr
) {
611 if (EatIfPresent(lltok::kw_unnamed_addr
))
612 UnnamedAddr
= GlobalValue::UnnamedAddr::Global
;
613 else if (EatIfPresent(lltok::kw_local_unnamed_addr
))
614 UnnamedAddr
= GlobalValue::UnnamedAddr::Local
;
616 UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
620 /// parseUnnamedGlobal:
621 /// OptionalVisibility (ALIAS | IFUNC) ...
622 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
623 /// OptionalDLLStorageClass
624 /// ... -> global variable
625 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
626 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
627 /// OptionalVisibility
628 /// OptionalDLLStorageClass
629 /// ... -> global variable
630 bool LLParser::parseUnnamedGlobal() {
631 unsigned VarID
= NumberedVals
.size();
633 LocTy NameLoc
= Lex
.getLoc();
635 // Handle the GlobalID form.
636 if (Lex
.getKind() == lltok::GlobalID
) {
637 if (Lex
.getUIntVal() != VarID
)
638 return error(Lex
.getLoc(),
639 "variable expected to be numbered '%" + Twine(VarID
) + "'");
640 Lex
.Lex(); // eat GlobalID;
642 if (parseToken(lltok::equal
, "expected '=' after name"))
647 unsigned Linkage
, Visibility
, DLLStorageClass
;
649 GlobalVariable::ThreadLocalMode TLM
;
650 GlobalVariable::UnnamedAddr UnnamedAddr
;
651 if (parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
653 parseOptionalThreadLocal(TLM
) || parseOptionalUnnamedAddr(UnnamedAddr
))
656 switch (Lex
.getKind()) {
658 return parseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
659 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
660 case lltok::kw_alias
:
661 case lltok::kw_ifunc
:
662 return parseAliasOrIFunc(Name
, NameLoc
, Linkage
, Visibility
,
663 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
667 /// parseNamedGlobal:
668 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
669 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
670 /// OptionalVisibility OptionalDLLStorageClass
671 /// ... -> global variable
672 bool LLParser::parseNamedGlobal() {
673 assert(Lex
.getKind() == lltok::GlobalVar
);
674 LocTy NameLoc
= Lex
.getLoc();
675 std::string Name
= Lex
.getStrVal();
679 unsigned Linkage
, Visibility
, DLLStorageClass
;
681 GlobalVariable::ThreadLocalMode TLM
;
682 GlobalVariable::UnnamedAddr UnnamedAddr
;
683 if (parseToken(lltok::equal
, "expected '=' in global variable") ||
684 parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
686 parseOptionalThreadLocal(TLM
) || parseOptionalUnnamedAddr(UnnamedAddr
))
689 switch (Lex
.getKind()) {
691 return parseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
692 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
693 case lltok::kw_alias
:
694 case lltok::kw_ifunc
:
695 return parseAliasOrIFunc(Name
, NameLoc
, Linkage
, Visibility
,
696 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
700 bool LLParser::parseComdat() {
701 assert(Lex
.getKind() == lltok::ComdatVar
);
702 std::string Name
= Lex
.getStrVal();
703 LocTy NameLoc
= Lex
.getLoc();
706 if (parseToken(lltok::equal
, "expected '=' here"))
709 if (parseToken(lltok::kw_comdat
, "expected comdat keyword"))
710 return tokError("expected comdat type");
712 Comdat::SelectionKind SK
;
713 switch (Lex
.getKind()) {
715 return tokError("unknown selection kind");
719 case lltok::kw_exactmatch
:
720 SK
= Comdat::ExactMatch
;
722 case lltok::kw_largest
:
723 SK
= Comdat::Largest
;
725 case lltok::kw_nodeduplicate
:
726 SK
= Comdat::NoDeduplicate
;
728 case lltok::kw_samesize
:
729 SK
= Comdat::SameSize
;
734 // See if the comdat was forward referenced, if so, use the comdat.
735 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
736 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
737 if (I
!= ComdatSymTab
.end() && !ForwardRefComdats
.erase(Name
))
738 return error(NameLoc
, "redefinition of comdat '$" + Name
+ "'");
741 if (I
!= ComdatSymTab
.end())
744 C
= M
->getOrInsertComdat(Name
);
745 C
->setSelectionKind(SK
);
751 // ::= '!' STRINGCONSTANT
752 bool LLParser::parseMDString(MDString
*&Result
) {
754 if (parseStringConstant(Str
))
756 Result
= MDString::get(Context
, Str
);
761 // ::= '!' MDNodeNumber
762 bool LLParser::parseMDNodeID(MDNode
*&Result
) {
763 // !{ ..., !42, ... }
764 LocTy IDLoc
= Lex
.getLoc();
766 if (parseUInt32(MID
))
769 // If not a forward reference, just return it now.
770 if (NumberedMetadata
.count(MID
)) {
771 Result
= NumberedMetadata
[MID
];
775 // Otherwise, create MDNode forward reference.
776 auto &FwdRef
= ForwardRefMDNodes
[MID
];
777 FwdRef
= std::make_pair(MDTuple::getTemporary(Context
, std::nullopt
), IDLoc
);
779 Result
= FwdRef
.first
.get();
780 NumberedMetadata
[MID
].reset(Result
);
784 /// parseNamedMetadata:
785 /// !foo = !{ !1, !2 }
786 bool LLParser::parseNamedMetadata() {
787 assert(Lex
.getKind() == lltok::MetadataVar
);
788 std::string Name
= Lex
.getStrVal();
791 if (parseToken(lltok::equal
, "expected '=' here") ||
792 parseToken(lltok::exclaim
, "Expected '!' here") ||
793 parseToken(lltok::lbrace
, "Expected '{' here"))
796 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
797 if (Lex
.getKind() != lltok::rbrace
)
800 // parse DIExpressions inline as a special case. They are still MDNodes,
801 // so they can still appear in named metadata. Remove this logic if they
802 // become plain Metadata.
803 if (Lex
.getKind() == lltok::MetadataVar
&&
804 Lex
.getStrVal() == "DIExpression") {
805 if (parseDIExpression(N
, /*IsDistinct=*/false))
807 // DIArgLists should only appear inline in a function, as they may
808 // contain LocalAsMetadata arguments which require a function context.
809 } else if (Lex
.getKind() == lltok::MetadataVar
&&
810 Lex
.getStrVal() == "DIArgList") {
811 return tokError("found DIArgList outside of function");
812 } else if (parseToken(lltok::exclaim
, "Expected '!' here") ||
817 } while (EatIfPresent(lltok::comma
));
819 return parseToken(lltok::rbrace
, "expected end of metadata node");
822 /// parseStandaloneMetadata:
824 bool LLParser::parseStandaloneMetadata() {
825 assert(Lex
.getKind() == lltok::exclaim
);
827 unsigned MetadataID
= 0;
830 if (parseUInt32(MetadataID
) || parseToken(lltok::equal
, "expected '=' here"))
833 // Detect common error, from old metadata syntax.
834 if (Lex
.getKind() == lltok::Type
)
835 return tokError("unexpected type in metadata definition");
837 bool IsDistinct
= EatIfPresent(lltok::kw_distinct
);
838 if (Lex
.getKind() == lltok::MetadataVar
) {
839 if (parseSpecializedMDNode(Init
, IsDistinct
))
841 } else if (parseToken(lltok::exclaim
, "Expected '!' here") ||
842 parseMDTuple(Init
, IsDistinct
))
845 // See if this was forward referenced, if so, handle it.
846 auto FI
= ForwardRefMDNodes
.find(MetadataID
);
847 if (FI
!= ForwardRefMDNodes
.end()) {
848 auto *ToReplace
= FI
->second
.first
.get();
849 // DIAssignID has its own special forward-reference "replacement" for
850 // attachments (the temporary attachments are never actually attached).
851 if (isa
<DIAssignID
>(Init
)) {
852 for (auto *Inst
: TempDIAssignIDAttachments
[ToReplace
]) {
853 assert(!Inst
->getMetadata(LLVMContext::MD_DIAssignID
) &&
854 "Inst unexpectedly already has DIAssignID attachment");
855 Inst
->setMetadata(LLVMContext::MD_DIAssignID
, Init
);
859 ToReplace
->replaceAllUsesWith(Init
);
860 ForwardRefMDNodes
.erase(FI
);
862 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
864 if (NumberedMetadata
.count(MetadataID
))
865 return tokError("Metadata id is already used");
866 NumberedMetadata
[MetadataID
].reset(Init
);
872 // Skips a single module summary entry.
873 bool LLParser::skipModuleSummaryEntry() {
874 // Each module summary entry consists of a tag for the entry
875 // type, followed by a colon, then the fields which may be surrounded by
876 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
877 // support is in place we will look for the tokens corresponding to the
879 if (Lex
.getKind() != lltok::kw_gv
&& Lex
.getKind() != lltok::kw_module
&&
880 Lex
.getKind() != lltok::kw_typeid
&& Lex
.getKind() != lltok::kw_flags
&&
881 Lex
.getKind() != lltok::kw_blockcount
)
883 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
884 "start of summary entry");
885 if (Lex
.getKind() == lltok::kw_flags
)
886 return parseSummaryIndexFlags();
887 if (Lex
.getKind() == lltok::kw_blockcount
)
888 return parseBlockCount();
890 if (parseToken(lltok::colon
, "expected ':' at start of summary entry") ||
891 parseToken(lltok::lparen
, "expected '(' at start of summary entry"))
893 // Now walk through the parenthesized entry, until the number of open
894 // parentheses goes back down to 0 (the first '(' was parsed above).
895 unsigned NumOpenParen
= 1;
897 switch (Lex
.getKind()) {
905 return tokError("found end of file while parsing summary entry");
907 // Skip everything in between parentheses.
911 } while (NumOpenParen
> 0);
916 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
917 bool LLParser::parseSummaryEntry() {
918 assert(Lex
.getKind() == lltok::SummaryID
);
919 unsigned SummaryID
= Lex
.getUIntVal();
921 // For summary entries, colons should be treated as distinct tokens,
922 // not an indication of the end of a label token.
923 Lex
.setIgnoreColonInIdentifiers(true);
926 if (parseToken(lltok::equal
, "expected '=' here"))
929 // If we don't have an index object, skip the summary entry.
931 return skipModuleSummaryEntry();
934 switch (Lex
.getKind()) {
936 result
= parseGVEntry(SummaryID
);
938 case lltok::kw_module
:
939 result
= parseModuleEntry(SummaryID
);
941 case lltok::kw_typeid
:
942 result
= parseTypeIdEntry(SummaryID
);
944 case lltok::kw_typeidCompatibleVTable
:
945 result
= parseTypeIdCompatibleVtableEntry(SummaryID
);
947 case lltok::kw_flags
:
948 result
= parseSummaryIndexFlags();
950 case lltok::kw_blockcount
:
951 result
= parseBlockCount();
954 result
= error(Lex
.getLoc(), "unexpected summary kind");
957 Lex
.setIgnoreColonInIdentifiers(false);
961 static bool isValidVisibilityForLinkage(unsigned V
, unsigned L
) {
962 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
963 (GlobalValue::VisibilityTypes
)V
== GlobalValue::DefaultVisibility
;
965 static bool isValidDLLStorageClassForLinkage(unsigned S
, unsigned L
) {
966 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
967 (GlobalValue::DLLStorageClassTypes
)S
== GlobalValue::DefaultStorageClass
;
970 // If there was an explicit dso_local, update GV. In the absence of an explicit
971 // dso_local we keep the default value.
972 static void maybeSetDSOLocal(bool DSOLocal
, GlobalValue
&GV
) {
974 GV
.setDSOLocal(true);
977 /// parseAliasOrIFunc:
978 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
979 /// OptionalVisibility OptionalDLLStorageClass
980 /// OptionalThreadLocal OptionalUnnamedAddr
981 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
983 /// AliaseeOrResolver
987 /// ::= ',' 'partition' StringConstant
989 /// Everything through OptionalUnnamedAddr has already been parsed.
991 bool LLParser::parseAliasOrIFunc(const std::string
&Name
, LocTy NameLoc
,
992 unsigned L
, unsigned Visibility
,
993 unsigned DLLStorageClass
, bool DSOLocal
,
994 GlobalVariable::ThreadLocalMode TLM
,
995 GlobalVariable::UnnamedAddr UnnamedAddr
) {
997 if (Lex
.getKind() == lltok::kw_alias
)
999 else if (Lex
.getKind() == lltok::kw_ifunc
)
1002 llvm_unreachable("Not an alias or ifunc!");
1005 GlobalValue::LinkageTypes Linkage
= (GlobalValue::LinkageTypes
) L
;
1007 if(IsAlias
&& !GlobalAlias::isValidLinkage(Linkage
))
1008 return error(NameLoc
, "invalid linkage type for alias");
1010 if (!isValidVisibilityForLinkage(Visibility
, L
))
1011 return error(NameLoc
,
1012 "symbol with local linkage must have default visibility");
1014 if (!isValidDLLStorageClassForLinkage(DLLStorageClass
, L
))
1015 return error(NameLoc
,
1016 "symbol with local linkage cannot have a DLL storage class");
1019 LocTy ExplicitTypeLoc
= Lex
.getLoc();
1020 if (parseType(Ty
) ||
1021 parseToken(lltok::comma
, "expected comma after alias or ifunc's type"))
1025 LocTy AliaseeLoc
= Lex
.getLoc();
1026 if (Lex
.getKind() != lltok::kw_bitcast
&&
1027 Lex
.getKind() != lltok::kw_getelementptr
&&
1028 Lex
.getKind() != lltok::kw_addrspacecast
&&
1029 Lex
.getKind() != lltok::kw_inttoptr
) {
1030 if (parseGlobalTypeAndValue(Aliasee
))
1033 // The bitcast dest type is not present, it is implied by the dest type.
1035 if (parseValID(ID
, /*PFS=*/nullptr))
1037 if (ID
.Kind
!= ValID::t_Constant
)
1038 return error(AliaseeLoc
, "invalid aliasee");
1039 Aliasee
= ID
.ConstantVal
;
1042 Type
*AliaseeType
= Aliasee
->getType();
1043 auto *PTy
= dyn_cast
<PointerType
>(AliaseeType
);
1045 return error(AliaseeLoc
, "An alias or ifunc must have pointer type");
1046 unsigned AddrSpace
= PTy
->getAddressSpace();
1048 GlobalValue
*GVal
= nullptr;
1050 // See if the alias was forward referenced, if so, prepare to replace the
1051 // forward reference.
1052 if (!Name
.empty()) {
1053 auto I
= ForwardRefVals
.find(Name
);
1054 if (I
!= ForwardRefVals
.end()) {
1055 GVal
= I
->second
.first
;
1056 ForwardRefVals
.erase(Name
);
1057 } else if (M
->getNamedValue(Name
)) {
1058 return error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1061 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1062 if (I
!= ForwardRefValIDs
.end()) {
1063 GVal
= I
->second
.first
;
1064 ForwardRefValIDs
.erase(I
);
1068 // Okay, create the alias/ifunc but do not insert it into the module yet.
1069 std::unique_ptr
<GlobalAlias
> GA
;
1070 std::unique_ptr
<GlobalIFunc
> GI
;
1073 GA
.reset(GlobalAlias::create(Ty
, AddrSpace
,
1074 (GlobalValue::LinkageTypes
)Linkage
, Name
,
1075 Aliasee
, /*Parent*/ nullptr));
1078 GI
.reset(GlobalIFunc::create(Ty
, AddrSpace
,
1079 (GlobalValue::LinkageTypes
)Linkage
, Name
,
1080 Aliasee
, /*Parent*/ nullptr));
1083 GV
->setThreadLocalMode(TLM
);
1084 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1085 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1086 GV
->setUnnamedAddr(UnnamedAddr
);
1087 maybeSetDSOLocal(DSOLocal
, *GV
);
1089 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1090 // Now parse them if there are any.
1091 while (Lex
.getKind() == lltok::comma
) {
1094 if (Lex
.getKind() == lltok::kw_partition
) {
1096 GV
->setPartition(Lex
.getStrVal());
1097 if (parseToken(lltok::StringConstant
, "expected partition string"))
1100 return tokError("unknown alias or ifunc property!");
1105 NumberedVals
.push_back(GV
);
1108 // Verify that types agree.
1109 if (GVal
->getType() != GV
->getType())
1112 "forward reference and definition of alias have different types");
1114 // If they agree, just RAUW the old value with the alias and remove the
1115 // forward ref info.
1116 GVal
->replaceAllUsesWith(GV
);
1117 GVal
->eraseFromParent();
1120 // Insert into the module, we know its name won't collide now.
1122 M
->insertAlias(GA
.release());
1124 M
->insertIFunc(GI
.release());
1125 assert(GV
->getName() == Name
&& "Should not be a name conflict!");
1130 static bool isSanitizer(lltok::Kind Kind
) {
1132 case lltok::kw_no_sanitize_address
:
1133 case lltok::kw_no_sanitize_hwaddress
:
1134 case lltok::kw_sanitize_memtag
:
1135 case lltok::kw_sanitize_address_dyninit
:
1142 bool LLParser::parseSanitizer(GlobalVariable
*GV
) {
1143 using SanitizerMetadata
= GlobalValue::SanitizerMetadata
;
1144 SanitizerMetadata Meta
;
1145 if (GV
->hasSanitizerMetadata())
1146 Meta
= GV
->getSanitizerMetadata();
1148 switch (Lex
.getKind()) {
1149 case lltok::kw_no_sanitize_address
:
1150 Meta
.NoAddress
= true;
1152 case lltok::kw_no_sanitize_hwaddress
:
1153 Meta
.NoHWAddress
= true;
1155 case lltok::kw_sanitize_memtag
:
1158 case lltok::kw_sanitize_address_dyninit
:
1159 Meta
.IsDynInit
= true;
1162 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1164 GV
->setSanitizerMetadata(Meta
);
1170 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1171 /// OptionalVisibility OptionalDLLStorageClass
1172 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1173 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1174 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1175 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1176 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1177 /// Const OptionalAttrs
1179 /// Everything up to and including OptionalUnnamedAddr has been parsed
1182 bool LLParser::parseGlobal(const std::string
&Name
, LocTy NameLoc
,
1183 unsigned Linkage
, bool HasLinkage
,
1184 unsigned Visibility
, unsigned DLLStorageClass
,
1185 bool DSOLocal
, GlobalVariable::ThreadLocalMode TLM
,
1186 GlobalVariable::UnnamedAddr UnnamedAddr
) {
1187 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
1188 return error(NameLoc
,
1189 "symbol with local linkage must have default visibility");
1191 if (!isValidDLLStorageClassForLinkage(DLLStorageClass
, Linkage
))
1192 return error(NameLoc
,
1193 "symbol with local linkage cannot have a DLL storage class");
1196 bool IsConstant
, IsExternallyInitialized
;
1197 LocTy IsExternallyInitializedLoc
;
1201 if (parseOptionalAddrSpace(AddrSpace
) ||
1202 parseOptionalToken(lltok::kw_externally_initialized
,
1203 IsExternallyInitialized
,
1204 &IsExternallyInitializedLoc
) ||
1205 parseGlobalType(IsConstant
) || parseType(Ty
, TyLoc
))
1208 // If the linkage is specified and is external, then no initializer is
1210 Constant
*Init
= nullptr;
1212 !GlobalValue::isValidDeclarationLinkage(
1213 (GlobalValue::LinkageTypes
)Linkage
)) {
1214 if (parseGlobalValue(Ty
, Init
))
1218 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
1219 return error(TyLoc
, "invalid type for global variable");
1221 GlobalValue
*GVal
= nullptr;
1223 // See if the global was forward referenced, if so, use the global.
1224 if (!Name
.empty()) {
1225 auto I
= ForwardRefVals
.find(Name
);
1226 if (I
!= ForwardRefVals
.end()) {
1227 GVal
= I
->second
.first
;
1228 ForwardRefVals
.erase(I
);
1229 } else if (M
->getNamedValue(Name
)) {
1230 return error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1233 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1234 if (I
!= ForwardRefValIDs
.end()) {
1235 GVal
= I
->second
.first
;
1236 ForwardRefValIDs
.erase(I
);
1240 GlobalVariable
*GV
= new GlobalVariable(
1241 *M
, Ty
, false, GlobalValue::ExternalLinkage
, nullptr, Name
, nullptr,
1242 GlobalVariable::NotThreadLocal
, AddrSpace
);
1245 NumberedVals
.push_back(GV
);
1247 // Set the parsed properties on the global.
1249 GV
->setInitializer(Init
);
1250 GV
->setConstant(IsConstant
);
1251 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
1252 maybeSetDSOLocal(DSOLocal
, *GV
);
1253 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1254 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1255 GV
->setExternallyInitialized(IsExternallyInitialized
);
1256 GV
->setThreadLocalMode(TLM
);
1257 GV
->setUnnamedAddr(UnnamedAddr
);
1260 if (GVal
->getAddressSpace() != AddrSpace
)
1263 "forward reference and definition of global have different types");
1265 GVal
->replaceAllUsesWith(GV
);
1266 GVal
->eraseFromParent();
1269 // parse attributes on the global.
1270 while (Lex
.getKind() == lltok::comma
) {
1273 if (Lex
.getKind() == lltok::kw_section
) {
1275 GV
->setSection(Lex
.getStrVal());
1276 if (parseToken(lltok::StringConstant
, "expected global section string"))
1278 } else if (Lex
.getKind() == lltok::kw_partition
) {
1280 GV
->setPartition(Lex
.getStrVal());
1281 if (parseToken(lltok::StringConstant
, "expected partition string"))
1283 } else if (Lex
.getKind() == lltok::kw_align
) {
1284 MaybeAlign Alignment
;
1285 if (parseOptionalAlignment(Alignment
))
1288 GV
->setAlignment(*Alignment
);
1289 } else if (Lex
.getKind() == lltok::MetadataVar
) {
1290 if (parseGlobalObjectMetadataAttachment(*GV
))
1292 } else if (isSanitizer(Lex
.getKind())) {
1293 if (parseSanitizer(GV
))
1297 if (parseOptionalComdat(Name
, C
))
1302 return tokError("unknown global variable property!");
1306 AttrBuilder
Attrs(M
->getContext());
1308 std::vector
<unsigned> FwdRefAttrGrps
;
1309 if (parseFnAttributeValuePairs(Attrs
, FwdRefAttrGrps
, false, BuiltinLoc
))
1311 if (Attrs
.hasAttributes() || !FwdRefAttrGrps
.empty()) {
1312 GV
->setAttributes(AttributeSet::get(Context
, Attrs
));
1313 ForwardRefAttrGroups
[GV
] = FwdRefAttrGrps
;
1319 /// parseUnnamedAttrGrp
1320 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1321 bool LLParser::parseUnnamedAttrGrp() {
1322 assert(Lex
.getKind() == lltok::kw_attributes
);
1323 LocTy AttrGrpLoc
= Lex
.getLoc();
1326 if (Lex
.getKind() != lltok::AttrGrpID
)
1327 return tokError("expected attribute group id");
1329 unsigned VarID
= Lex
.getUIntVal();
1330 std::vector
<unsigned> unused
;
1334 if (parseToken(lltok::equal
, "expected '=' here") ||
1335 parseToken(lltok::lbrace
, "expected '{' here"))
1338 auto R
= NumberedAttrBuilders
.find(VarID
);
1339 if (R
== NumberedAttrBuilders
.end())
1340 R
= NumberedAttrBuilders
.emplace(VarID
, AttrBuilder(M
->getContext())).first
;
1342 if (parseFnAttributeValuePairs(R
->second
, unused
, true, BuiltinLoc
) ||
1343 parseToken(lltok::rbrace
, "expected end of attribute group"))
1346 if (!R
->second
.hasAttributes())
1347 return error(AttrGrpLoc
, "attribute group has no attributes");
1352 static Attribute::AttrKind
tokenToAttribute(lltok::Kind Kind
) {
1354 #define GET_ATTR_NAMES
1355 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1356 case lltok::kw_##DISPLAY_NAME: \
1357 return Attribute::ENUM_NAME;
1358 #include "llvm/IR/Attributes.inc"
1360 return Attribute::None
;
1364 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr
, AttrBuilder
&B
,
1366 if (Attribute::isTypeAttrKind(Attr
))
1367 return parseRequiredTypeAttr(B
, Lex
.getKind(), Attr
);
1370 case Attribute::Alignment
: {
1371 MaybeAlign Alignment
;
1375 if (parseToken(lltok::equal
, "expected '=' here") || parseUInt32(Value
))
1377 Alignment
= Align(Value
);
1379 if (parseOptionalAlignment(Alignment
, true))
1382 B
.addAlignmentAttr(Alignment
);
1385 case Attribute::StackAlignment
: {
1389 if (parseToken(lltok::equal
, "expected '=' here") ||
1390 parseUInt32(Alignment
))
1393 if (parseOptionalStackAlignment(Alignment
))
1396 B
.addStackAlignmentAttr(Alignment
);
1399 case Attribute::AllocSize
: {
1400 unsigned ElemSizeArg
;
1401 std::optional
<unsigned> NumElemsArg
;
1402 if (parseAllocSizeArguments(ElemSizeArg
, NumElemsArg
))
1404 B
.addAllocSizeAttr(ElemSizeArg
, NumElemsArg
);
1407 case Attribute::VScaleRange
: {
1408 unsigned MinValue
, MaxValue
;
1409 if (parseVScaleRangeArguments(MinValue
, MaxValue
))
1411 B
.addVScaleRangeAttr(MinValue
,
1412 MaxValue
> 0 ? MaxValue
: std::optional
<unsigned>());
1415 case Attribute::Dereferenceable
: {
1417 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1419 B
.addDereferenceableAttr(Bytes
);
1422 case Attribute::DereferenceableOrNull
: {
1424 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1426 B
.addDereferenceableOrNullAttr(Bytes
);
1429 case Attribute::UWTable
: {
1431 if (parseOptionalUWTableKind(Kind
))
1433 B
.addUWTableAttr(Kind
);
1436 case Attribute::AllocKind
: {
1437 AllocFnKind Kind
= AllocFnKind::Unknown
;
1438 if (parseAllocKind(Kind
))
1440 B
.addAllocKindAttr(Kind
);
1443 case Attribute::Memory
: {
1444 std::optional
<MemoryEffects
> ME
= parseMemoryAttr();
1447 B
.addMemoryAttr(*ME
);
1450 case Attribute::NoFPClass
: {
1451 if (FPClassTest NoFPClass
=
1452 static_cast<FPClassTest
>(parseNoFPClassAttr())) {
1453 B
.addNoFPClassAttr(NoFPClass
);
1460 B
.addAttribute(Attr
);
1466 static bool upgradeMemoryAttr(MemoryEffects
&ME
, lltok::Kind Kind
) {
1468 case lltok::kw_readnone
:
1469 ME
&= MemoryEffects::none();
1471 case lltok::kw_readonly
:
1472 ME
&= MemoryEffects::readOnly();
1474 case lltok::kw_writeonly
:
1475 ME
&= MemoryEffects::writeOnly();
1477 case lltok::kw_argmemonly
:
1478 ME
&= MemoryEffects::argMemOnly();
1480 case lltok::kw_inaccessiblememonly
:
1481 ME
&= MemoryEffects::inaccessibleMemOnly();
1483 case lltok::kw_inaccessiblemem_or_argmemonly
:
1484 ME
&= MemoryEffects::inaccessibleOrArgMemOnly();
1491 /// parseFnAttributeValuePairs
1492 /// ::= <attr> | <attr> '=' <value>
1493 bool LLParser::parseFnAttributeValuePairs(AttrBuilder
&B
,
1494 std::vector
<unsigned> &FwdRefAttrGrps
,
1495 bool InAttrGrp
, LocTy
&BuiltinLoc
) {
1496 bool HaveError
= false;
1500 MemoryEffects ME
= MemoryEffects::unknown();
1502 lltok::Kind Token
= Lex
.getKind();
1503 if (Token
== lltok::rbrace
)
1506 if (Token
== lltok::StringConstant
) {
1507 if (parseStringAttribute(B
))
1512 if (Token
== lltok::AttrGrpID
) {
1513 // Allow a function to reference an attribute group:
1515 // define void @foo() #1 { ... }
1519 "cannot have an attribute group reference in an attribute group");
1521 // Save the reference to the attribute group. We'll fill it in later.
1522 FwdRefAttrGrps
.push_back(Lex
.getUIntVal());
1528 SMLoc Loc
= Lex
.getLoc();
1529 if (Token
== lltok::kw_builtin
)
1532 if (upgradeMemoryAttr(ME
, Token
)) {
1537 Attribute::AttrKind Attr
= tokenToAttribute(Token
);
1538 if (Attr
== Attribute::None
) {
1541 return error(Lex
.getLoc(), "unterminated attribute group");
1544 if (parseEnumAttribute(Attr
, B
, InAttrGrp
))
1547 // As a hack, we allow function alignment to be initially parsed as an
1548 // attribute on a function declaration/definition or added to an attribute
1549 // group and later moved to the alignment field.
1550 if (!Attribute::canUseAsFnAttr(Attr
) && Attr
!= Attribute::Alignment
)
1551 HaveError
|= error(Loc
, "this attribute does not apply to functions");
1554 if (ME
!= MemoryEffects::unknown())
1555 B
.addMemoryAttr(ME
);
1559 //===----------------------------------------------------------------------===//
1560 // GlobalValue Reference/Resolution Routines.
1561 //===----------------------------------------------------------------------===//
1563 static inline GlobalValue
*createGlobalFwdRef(Module
*M
, PointerType
*PTy
) {
1564 // The used global type does not matter. We will later RAUW it with a
1565 // global/function of the correct type.
1566 return new GlobalVariable(*M
, Type::getInt8Ty(M
->getContext()), false,
1567 GlobalValue::ExternalWeakLinkage
, nullptr, "",
1568 nullptr, GlobalVariable::NotThreadLocal
,
1569 PTy
->getAddressSpace());
1572 Value
*LLParser::checkValidVariableType(LocTy Loc
, const Twine
&Name
, Type
*Ty
,
1574 Type
*ValTy
= Val
->getType();
1577 if (Ty
->isLabelTy())
1578 error(Loc
, "'" + Name
+ "' is not a basic block");
1580 error(Loc
, "'" + Name
+ "' defined with type '" +
1581 getTypeString(Val
->getType()) + "' but expected '" +
1582 getTypeString(Ty
) + "'");
1586 /// getGlobalVal - Get a value with the specified name or ID, creating a
1587 /// forward reference record if needed. This can return null if the value
1588 /// exists but does not have the right type.
1589 GlobalValue
*LLParser::getGlobalVal(const std::string
&Name
, Type
*Ty
,
1591 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1593 error(Loc
, "global variable reference must have pointer type");
1597 // Look this name up in the normal function symbol table.
1599 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
1601 // If this is a forward reference for the value, see if we already created a
1602 // forward ref record.
1604 auto I
= ForwardRefVals
.find(Name
);
1605 if (I
!= ForwardRefVals
.end())
1606 Val
= I
->second
.first
;
1609 // If we have the value in the symbol table or fwd-ref table, return it.
1611 return cast_or_null
<GlobalValue
>(
1612 checkValidVariableType(Loc
, "@" + Name
, Ty
, Val
));
1614 // Otherwise, create a new forward reference for this value and remember it.
1615 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
);
1616 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1620 GlobalValue
*LLParser::getGlobalVal(unsigned ID
, Type
*Ty
, LocTy Loc
) {
1621 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1623 error(Loc
, "global variable reference must have pointer type");
1627 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
1629 // If this is a forward reference for the value, see if we already created a
1630 // forward ref record.
1632 auto I
= ForwardRefValIDs
.find(ID
);
1633 if (I
!= ForwardRefValIDs
.end())
1634 Val
= I
->second
.first
;
1637 // If we have the value in the symbol table or fwd-ref table, return it.
1639 return cast_or_null
<GlobalValue
>(
1640 checkValidVariableType(Loc
, "@" + Twine(ID
), Ty
, Val
));
1642 // Otherwise, create a new forward reference for this value and remember it.
1643 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
);
1644 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1648 //===----------------------------------------------------------------------===//
1649 // Comdat Reference/Resolution Routines.
1650 //===----------------------------------------------------------------------===//
1652 Comdat
*LLParser::getComdat(const std::string
&Name
, LocTy Loc
) {
1653 // Look this name up in the comdat symbol table.
1654 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
1655 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
1656 if (I
!= ComdatSymTab
.end())
1659 // Otherwise, create a new forward reference for this value and remember it.
1660 Comdat
*C
= M
->getOrInsertComdat(Name
);
1661 ForwardRefComdats
[Name
] = Loc
;
1665 //===----------------------------------------------------------------------===//
1667 //===----------------------------------------------------------------------===//
1669 /// parseToken - If the current token has the specified kind, eat it and return
1670 /// success. Otherwise, emit the specified error and return failure.
1671 bool LLParser::parseToken(lltok::Kind T
, const char *ErrMsg
) {
1672 if (Lex
.getKind() != T
)
1673 return tokError(ErrMsg
);
1678 /// parseStringConstant
1679 /// ::= StringConstant
1680 bool LLParser::parseStringConstant(std::string
&Result
) {
1681 if (Lex
.getKind() != lltok::StringConstant
)
1682 return tokError("expected string constant");
1683 Result
= Lex
.getStrVal();
1690 bool LLParser::parseUInt32(uint32_t &Val
) {
1691 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1692 return tokError("expected integer");
1693 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
1694 if (Val64
!= unsigned(Val64
))
1695 return tokError("expected 32-bit integer (too large)");
1703 bool LLParser::parseUInt64(uint64_t &Val
) {
1704 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1705 return tokError("expected integer");
1706 Val
= Lex
.getAPSIntVal().getLimitedValue();
1712 /// := 'localdynamic'
1713 /// := 'initialexec'
1715 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode
&TLM
) {
1716 switch (Lex
.getKind()) {
1718 return tokError("expected localdynamic, initialexec or localexec");
1719 case lltok::kw_localdynamic
:
1720 TLM
= GlobalVariable::LocalDynamicTLSModel
;
1722 case lltok::kw_initialexec
:
1723 TLM
= GlobalVariable::InitialExecTLSModel
;
1725 case lltok::kw_localexec
:
1726 TLM
= GlobalVariable::LocalExecTLSModel
;
1734 /// parseOptionalThreadLocal
1736 /// := 'thread_local'
1737 /// := 'thread_local' '(' tlsmodel ')'
1738 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode
&TLM
) {
1739 TLM
= GlobalVariable::NotThreadLocal
;
1740 if (!EatIfPresent(lltok::kw_thread_local
))
1743 TLM
= GlobalVariable::GeneralDynamicTLSModel
;
1744 if (Lex
.getKind() == lltok::lparen
) {
1746 return parseTLSModel(TLM
) ||
1747 parseToken(lltok::rparen
, "expected ')' after thread local model");
1752 /// parseOptionalAddrSpace
1754 /// := 'addrspace' '(' uint32 ')'
1755 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace
, unsigned DefaultAS
) {
1756 AddrSpace
= DefaultAS
;
1757 if (!EatIfPresent(lltok::kw_addrspace
))
1760 auto ParseAddrspaceValue
= [&](unsigned &AddrSpace
) -> bool {
1761 if (Lex
.getKind() == lltok::StringConstant
) {
1762 auto AddrSpaceStr
= Lex
.getStrVal();
1763 if (AddrSpaceStr
== "A") {
1764 AddrSpace
= M
->getDataLayout().getAllocaAddrSpace();
1765 } else if (AddrSpaceStr
== "G") {
1766 AddrSpace
= M
->getDataLayout().getDefaultGlobalsAddressSpace();
1767 } else if (AddrSpaceStr
== "P") {
1768 AddrSpace
= M
->getDataLayout().getProgramAddressSpace();
1770 return tokError("invalid symbolic addrspace '" + AddrSpaceStr
+ "'");
1775 if (Lex
.getKind() != lltok::APSInt
)
1776 return tokError("expected integer or string constant");
1777 SMLoc Loc
= Lex
.getLoc();
1778 if (parseUInt32(AddrSpace
))
1780 if (!isUInt
<24>(AddrSpace
))
1781 return error(Loc
, "invalid address space, must be a 24-bit integer");
1785 return parseToken(lltok::lparen
, "expected '(' in address space") ||
1786 ParseAddrspaceValue(AddrSpace
) ||
1787 parseToken(lltok::rparen
, "expected ')' in address space");
1790 /// parseStringAttribute
1791 /// := StringConstant
1792 /// := StringConstant '=' StringConstant
1793 bool LLParser::parseStringAttribute(AttrBuilder
&B
) {
1794 std::string Attr
= Lex
.getStrVal();
1797 if (EatIfPresent(lltok::equal
) && parseStringConstant(Val
))
1799 B
.addAttribute(Attr
, Val
);
1803 /// Parse a potentially empty list of parameter or return attributes.
1804 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder
&B
, bool IsParam
) {
1805 bool HaveError
= false;
1810 lltok::Kind Token
= Lex
.getKind();
1811 if (Token
== lltok::StringConstant
) {
1812 if (parseStringAttribute(B
))
1817 SMLoc Loc
= Lex
.getLoc();
1818 Attribute::AttrKind Attr
= tokenToAttribute(Token
);
1819 if (Attr
== Attribute::None
)
1822 if (parseEnumAttribute(Attr
, B
, /* InAttrGroup */ false))
1825 if (IsParam
&& !Attribute::canUseAsParamAttr(Attr
))
1826 HaveError
|= error(Loc
, "this attribute does not apply to parameters");
1827 if (!IsParam
&& !Attribute::canUseAsRetAttr(Attr
))
1828 HaveError
|= error(Loc
, "this attribute does not apply to return values");
1832 static unsigned parseOptionalLinkageAux(lltok::Kind Kind
, bool &HasLinkage
) {
1837 return GlobalValue::ExternalLinkage
;
1838 case lltok::kw_private
:
1839 return GlobalValue::PrivateLinkage
;
1840 case lltok::kw_internal
:
1841 return GlobalValue::InternalLinkage
;
1842 case lltok::kw_weak
:
1843 return GlobalValue::WeakAnyLinkage
;
1844 case lltok::kw_weak_odr
:
1845 return GlobalValue::WeakODRLinkage
;
1846 case lltok::kw_linkonce
:
1847 return GlobalValue::LinkOnceAnyLinkage
;
1848 case lltok::kw_linkonce_odr
:
1849 return GlobalValue::LinkOnceODRLinkage
;
1850 case lltok::kw_available_externally
:
1851 return GlobalValue::AvailableExternallyLinkage
;
1852 case lltok::kw_appending
:
1853 return GlobalValue::AppendingLinkage
;
1854 case lltok::kw_common
:
1855 return GlobalValue::CommonLinkage
;
1856 case lltok::kw_extern_weak
:
1857 return GlobalValue::ExternalWeakLinkage
;
1858 case lltok::kw_external
:
1859 return GlobalValue::ExternalLinkage
;
1863 /// parseOptionalLinkage
1870 /// ::= 'linkonce_odr'
1871 /// ::= 'available_externally'
1874 /// ::= 'extern_weak'
1876 bool LLParser::parseOptionalLinkage(unsigned &Res
, bool &HasLinkage
,
1877 unsigned &Visibility
,
1878 unsigned &DLLStorageClass
, bool &DSOLocal
) {
1879 Res
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
1882 parseOptionalDSOLocal(DSOLocal
);
1883 parseOptionalVisibility(Visibility
);
1884 parseOptionalDLLStorageClass(DLLStorageClass
);
1886 if (DSOLocal
&& DLLStorageClass
== GlobalValue::DLLImportStorageClass
) {
1887 return error(Lex
.getLoc(), "dso_location and DLL-StorageClass mismatch");
1893 void LLParser::parseOptionalDSOLocal(bool &DSOLocal
) {
1894 switch (Lex
.getKind()) {
1898 case lltok::kw_dso_local
:
1902 case lltok::kw_dso_preemptable
:
1909 /// parseOptionalVisibility
1915 void LLParser::parseOptionalVisibility(unsigned &Res
) {
1916 switch (Lex
.getKind()) {
1918 Res
= GlobalValue::DefaultVisibility
;
1920 case lltok::kw_default
:
1921 Res
= GlobalValue::DefaultVisibility
;
1923 case lltok::kw_hidden
:
1924 Res
= GlobalValue::HiddenVisibility
;
1926 case lltok::kw_protected
:
1927 Res
= GlobalValue::ProtectedVisibility
;
1933 /// parseOptionalDLLStorageClass
1938 void LLParser::parseOptionalDLLStorageClass(unsigned &Res
) {
1939 switch (Lex
.getKind()) {
1941 Res
= GlobalValue::DefaultStorageClass
;
1943 case lltok::kw_dllimport
:
1944 Res
= GlobalValue::DLLImportStorageClass
;
1946 case lltok::kw_dllexport
:
1947 Res
= GlobalValue::DLLExportStorageClass
;
1953 /// parseOptionalCallingConv
1957 /// ::= 'intel_ocl_bicc'
1959 /// ::= 'cfguard_checkcc'
1960 /// ::= 'x86_stdcallcc'
1961 /// ::= 'x86_fastcallcc'
1962 /// ::= 'x86_thiscallcc'
1963 /// ::= 'x86_vectorcallcc'
1964 /// ::= 'arm_apcscc'
1965 /// ::= 'arm_aapcscc'
1966 /// ::= 'arm_aapcs_vfpcc'
1967 /// ::= 'aarch64_vector_pcs'
1968 /// ::= 'aarch64_sve_vector_pcs'
1969 /// ::= 'aarch64_sme_preservemost_from_x0'
1970 /// ::= 'aarch64_sme_preservemost_from_x2'
1971 /// ::= 'msp430_intrcc'
1972 /// ::= 'avr_intrcc'
1973 /// ::= 'avr_signalcc'
1974 /// ::= 'ptx_kernel'
1975 /// ::= 'ptx_device'
1977 /// ::= 'spir_kernel'
1978 /// ::= 'x86_64_sysvcc'
1980 /// ::= 'webkit_jscc'
1982 /// ::= 'preserve_mostcc'
1983 /// ::= 'preserve_allcc'
1986 /// ::= 'swifttailcc'
1987 /// ::= 'x86_intrcc'
1990 /// ::= 'cxx_fast_tlscc'
1998 /// ::= 'amdgpu_cs_chain'
1999 /// ::= 'amdgpu_cs_chain_preserve'
2000 /// ::= 'amdgpu_kernel'
2002 /// ::= 'm68k_rtdcc'
2005 bool LLParser::parseOptionalCallingConv(unsigned &CC
) {
2006 switch (Lex
.getKind()) {
2007 default: CC
= CallingConv::C
; return false;
2008 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
2009 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
2010 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
2011 case lltok::kw_cfguard_checkcc
: CC
= CallingConv::CFGuard_Check
; break;
2012 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
2013 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
2014 case lltok::kw_x86_regcallcc
: CC
= CallingConv::X86_RegCall
; break;
2015 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
2016 case lltok::kw_x86_vectorcallcc
:CC
= CallingConv::X86_VectorCall
; break;
2017 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
2018 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
2019 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
2020 case lltok::kw_aarch64_vector_pcs
:CC
= CallingConv::AArch64_VectorCall
; break;
2021 case lltok::kw_aarch64_sve_vector_pcs
:
2022 CC
= CallingConv::AArch64_SVE_VectorCall
;
2024 case lltok::kw_aarch64_sme_preservemost_from_x0
:
2025 CC
= CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
;
2027 case lltok::kw_aarch64_sme_preservemost_from_x2
:
2028 CC
= CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
;
2030 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
2031 case lltok::kw_avr_intrcc
: CC
= CallingConv::AVR_INTR
; break;
2032 case lltok::kw_avr_signalcc
: CC
= CallingConv::AVR_SIGNAL
; break;
2033 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
2034 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
2035 case lltok::kw_spir_kernel
: CC
= CallingConv::SPIR_KERNEL
; break;
2036 case lltok::kw_spir_func
: CC
= CallingConv::SPIR_FUNC
; break;
2037 case lltok::kw_intel_ocl_bicc
: CC
= CallingConv::Intel_OCL_BI
; break;
2038 case lltok::kw_x86_64_sysvcc
: CC
= CallingConv::X86_64_SysV
; break;
2039 case lltok::kw_win64cc
: CC
= CallingConv::Win64
; break;
2040 case lltok::kw_webkit_jscc
: CC
= CallingConv::WebKit_JS
; break;
2041 case lltok::kw_anyregcc
: CC
= CallingConv::AnyReg
; break;
2042 case lltok::kw_preserve_mostcc
:CC
= CallingConv::PreserveMost
; break;
2043 case lltok::kw_preserve_allcc
: CC
= CallingConv::PreserveAll
; break;
2044 case lltok::kw_ghccc
: CC
= CallingConv::GHC
; break;
2045 case lltok::kw_swiftcc
: CC
= CallingConv::Swift
; break;
2046 case lltok::kw_swifttailcc
: CC
= CallingConv::SwiftTail
; break;
2047 case lltok::kw_x86_intrcc
: CC
= CallingConv::X86_INTR
; break;
2048 case lltok::kw_hhvmcc
:
2049 CC
= CallingConv::DUMMY_HHVM
;
2051 case lltok::kw_hhvm_ccc
:
2052 CC
= CallingConv::DUMMY_HHVM_C
;
2054 case lltok::kw_cxx_fast_tlscc
: CC
= CallingConv::CXX_FAST_TLS
; break;
2055 case lltok::kw_amdgpu_vs
: CC
= CallingConv::AMDGPU_VS
; break;
2056 case lltok::kw_amdgpu_gfx
: CC
= CallingConv::AMDGPU_Gfx
; break;
2057 case lltok::kw_amdgpu_ls
: CC
= CallingConv::AMDGPU_LS
; break;
2058 case lltok::kw_amdgpu_hs
: CC
= CallingConv::AMDGPU_HS
; break;
2059 case lltok::kw_amdgpu_es
: CC
= CallingConv::AMDGPU_ES
; break;
2060 case lltok::kw_amdgpu_gs
: CC
= CallingConv::AMDGPU_GS
; break;
2061 case lltok::kw_amdgpu_ps
: CC
= CallingConv::AMDGPU_PS
; break;
2062 case lltok::kw_amdgpu_cs
: CC
= CallingConv::AMDGPU_CS
; break;
2063 case lltok::kw_amdgpu_cs_chain
:
2064 CC
= CallingConv::AMDGPU_CS_Chain
;
2066 case lltok::kw_amdgpu_cs_chain_preserve
:
2067 CC
= CallingConv::AMDGPU_CS_ChainPreserve
;
2069 case lltok::kw_amdgpu_kernel
: CC
= CallingConv::AMDGPU_KERNEL
; break;
2070 case lltok::kw_tailcc
: CC
= CallingConv::Tail
; break;
2071 case lltok::kw_m68k_rtdcc
: CC
= CallingConv::M68k_RTD
; break;
2072 case lltok::kw_cc
: {
2074 return parseUInt32(CC
);
2082 /// parseMetadataAttachment
2084 bool LLParser::parseMetadataAttachment(unsigned &Kind
, MDNode
*&MD
) {
2085 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata attachment");
2087 std::string Name
= Lex
.getStrVal();
2088 Kind
= M
->getMDKindID(Name
);
2091 return parseMDNode(MD
);
2094 /// parseInstructionMetadata
2095 /// ::= !dbg !42 (',' !dbg !57)*
2096 bool LLParser::parseInstructionMetadata(Instruction
&Inst
) {
2098 if (Lex
.getKind() != lltok::MetadataVar
)
2099 return tokError("expected metadata after comma");
2103 if (parseMetadataAttachment(MDK
, N
))
2106 if (MDK
== LLVMContext::MD_DIAssignID
)
2107 TempDIAssignIDAttachments
[N
].push_back(&Inst
);
2109 Inst
.setMetadata(MDK
, N
);
2111 if (MDK
== LLVMContext::MD_tbaa
)
2112 InstsWithTBAATag
.push_back(&Inst
);
2114 // If this is the end of the list, we're done.
2115 } while (EatIfPresent(lltok::comma
));
2119 /// parseGlobalObjectMetadataAttachment
2121 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject
&GO
) {
2124 if (parseMetadataAttachment(MDK
, N
))
2127 GO
.addMetadata(MDK
, *N
);
2131 /// parseOptionalFunctionMetadata
2133 bool LLParser::parseOptionalFunctionMetadata(Function
&F
) {
2134 while (Lex
.getKind() == lltok::MetadataVar
)
2135 if (parseGlobalObjectMetadataAttachment(F
))
2140 /// parseOptionalAlignment
2143 bool LLParser::parseOptionalAlignment(MaybeAlign
&Alignment
, bool AllowParens
) {
2144 Alignment
= std::nullopt
;
2145 if (!EatIfPresent(lltok::kw_align
))
2147 LocTy AlignLoc
= Lex
.getLoc();
2150 LocTy ParenLoc
= Lex
.getLoc();
2151 bool HaveParens
= false;
2153 if (EatIfPresent(lltok::lparen
))
2157 if (parseUInt64(Value
))
2160 if (HaveParens
&& !EatIfPresent(lltok::rparen
))
2161 return error(ParenLoc
, "expected ')'");
2163 if (!isPowerOf2_64(Value
))
2164 return error(AlignLoc
, "alignment is not a power of two");
2165 if (Value
> Value::MaximumAlignment
)
2166 return error(AlignLoc
, "huge alignments are not supported yet");
2167 Alignment
= Align(Value
);
2171 /// parseOptionalDerefAttrBytes
2173 /// ::= AttrKind '(' 4 ')'
2175 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2176 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind
,
2178 assert((AttrKind
== lltok::kw_dereferenceable
||
2179 AttrKind
== lltok::kw_dereferenceable_or_null
) &&
2183 if (!EatIfPresent(AttrKind
))
2185 LocTy ParenLoc
= Lex
.getLoc();
2186 if (!EatIfPresent(lltok::lparen
))
2187 return error(ParenLoc
, "expected '('");
2188 LocTy DerefLoc
= Lex
.getLoc();
2189 if (parseUInt64(Bytes
))
2191 ParenLoc
= Lex
.getLoc();
2192 if (!EatIfPresent(lltok::rparen
))
2193 return error(ParenLoc
, "expected ')'");
2195 return error(DerefLoc
, "dereferenceable bytes must be non-zero");
2199 bool LLParser::parseOptionalUWTableKind(UWTableKind
&Kind
) {
2201 Kind
= UWTableKind::Default
;
2202 if (!EatIfPresent(lltok::lparen
))
2204 LocTy KindLoc
= Lex
.getLoc();
2205 if (Lex
.getKind() == lltok::kw_sync
)
2206 Kind
= UWTableKind::Sync
;
2207 else if (Lex
.getKind() == lltok::kw_async
)
2208 Kind
= UWTableKind::Async
;
2210 return error(KindLoc
, "expected unwind table kind");
2212 return parseToken(lltok::rparen
, "expected ')'");
2215 bool LLParser::parseAllocKind(AllocFnKind
&Kind
) {
2217 LocTy ParenLoc
= Lex
.getLoc();
2218 if (!EatIfPresent(lltok::lparen
))
2219 return error(ParenLoc
, "expected '('");
2220 LocTy KindLoc
= Lex
.getLoc();
2222 if (parseStringConstant(Arg
))
2223 return error(KindLoc
, "expected allockind value");
2224 for (StringRef A
: llvm::split(Arg
, ",")) {
2226 Kind
|= AllocFnKind::Alloc
;
2227 } else if (A
== "realloc") {
2228 Kind
|= AllocFnKind::Realloc
;
2229 } else if (A
== "free") {
2230 Kind
|= AllocFnKind::Free
;
2231 } else if (A
== "uninitialized") {
2232 Kind
|= AllocFnKind::Uninitialized
;
2233 } else if (A
== "zeroed") {
2234 Kind
|= AllocFnKind::Zeroed
;
2235 } else if (A
== "aligned") {
2236 Kind
|= AllocFnKind::Aligned
;
2238 return error(KindLoc
, Twine("unknown allockind ") + A
);
2241 ParenLoc
= Lex
.getLoc();
2242 if (!EatIfPresent(lltok::rparen
))
2243 return error(ParenLoc
, "expected ')'");
2244 if (Kind
== AllocFnKind::Unknown
)
2245 return error(KindLoc
, "expected allockind value");
2249 static std::optional
<MemoryEffects::Location
> keywordToLoc(lltok::Kind Tok
) {
2251 case lltok::kw_argmem
:
2252 return IRMemLocation::ArgMem
;
2253 case lltok::kw_inaccessiblemem
:
2254 return IRMemLocation::InaccessibleMem
;
2256 return std::nullopt
;
2260 static std::optional
<ModRefInfo
> keywordToModRef(lltok::Kind Tok
) {
2262 case lltok::kw_none
:
2263 return ModRefInfo::NoModRef
;
2264 case lltok::kw_read
:
2265 return ModRefInfo::Ref
;
2266 case lltok::kw_write
:
2267 return ModRefInfo::Mod
;
2268 case lltok::kw_readwrite
:
2269 return ModRefInfo::ModRef
;
2271 return std::nullopt
;
2275 std::optional
<MemoryEffects
> LLParser::parseMemoryAttr() {
2276 MemoryEffects ME
= MemoryEffects::none();
2278 // We use syntax like memory(argmem: read), so the colon should not be
2279 // interpreted as a label terminator.
2280 Lex
.setIgnoreColonInIdentifiers(true);
2281 auto _
= make_scope_exit([&] { Lex
.setIgnoreColonInIdentifiers(false); });
2284 if (!EatIfPresent(lltok::lparen
)) {
2285 tokError("expected '('");
2286 return std::nullopt
;
2289 bool SeenLoc
= false;
2291 std::optional
<IRMemLocation
> Loc
= keywordToLoc(Lex
.getKind());
2294 if (!EatIfPresent(lltok::colon
)) {
2295 tokError("expected ':' after location");
2296 return std::nullopt
;
2300 std::optional
<ModRefInfo
> MR
= keywordToModRef(Lex
.getKind());
2303 tokError("expected memory location (argmem, inaccessiblemem) "
2304 "or access kind (none, read, write, readwrite)");
2306 tokError("expected access kind (none, read, write, readwrite)");
2307 return std::nullopt
;
2313 ME
= ME
.getWithModRef(*Loc
, *MR
);
2316 tokError("default access kind must be specified first");
2317 return std::nullopt
;
2319 ME
= MemoryEffects(*MR
);
2322 if (EatIfPresent(lltok::rparen
))
2324 } while (EatIfPresent(lltok::comma
));
2326 tokError("unterminated memory attribute");
2327 return std::nullopt
;
2330 static unsigned keywordToFPClassTest(lltok::Kind Tok
) {
2336 case lltok::kw_snan
:
2338 case lltok::kw_qnan
:
2342 case lltok::kw_ninf
:
2344 case lltok::kw_pinf
:
2346 case lltok::kw_norm
:
2348 case lltok::kw_nnorm
:
2350 case lltok::kw_pnorm
:
2354 case lltok::kw_nsub
:
2355 return fcNegSubnormal
;
2356 case lltok::kw_psub
:
2357 return fcPosSubnormal
;
2358 case lltok::kw_zero
:
2360 case lltok::kw_nzero
:
2362 case lltok::kw_pzero
:
2369 unsigned LLParser::parseNoFPClassAttr() {
2370 unsigned Mask
= fcNone
;
2373 if (!EatIfPresent(lltok::lparen
)) {
2374 tokError("expected '('");
2380 unsigned TestMask
= keywordToFPClassTest(Lex
.getKind());
2381 if (TestMask
!= 0) {
2383 // TODO: Disallow overlapping masks to avoid copy paste errors
2384 } else if (Mask
== 0 && Lex
.getKind() == lltok::APSInt
&&
2385 !parseUInt64(Value
)) {
2386 if (Value
== 0 || (Value
& ~static_cast<unsigned>(fcAllFlags
)) != 0) {
2387 error(Lex
.getLoc(), "invalid mask value for 'nofpclass'");
2391 if (!EatIfPresent(lltok::rparen
)) {
2392 error(Lex
.getLoc(), "expected ')'");
2398 error(Lex
.getLoc(), "expected nofpclass test mask");
2403 if (EatIfPresent(lltok::rparen
))
2407 llvm_unreachable("unterminated nofpclass attribute");
2410 /// parseOptionalCommaAlign
2414 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2416 bool LLParser::parseOptionalCommaAlign(MaybeAlign
&Alignment
,
2417 bool &AteExtraComma
) {
2418 AteExtraComma
= false;
2419 while (EatIfPresent(lltok::comma
)) {
2420 // Metadata at the end is an early exit.
2421 if (Lex
.getKind() == lltok::MetadataVar
) {
2422 AteExtraComma
= true;
2426 if (Lex
.getKind() != lltok::kw_align
)
2427 return error(Lex
.getLoc(), "expected metadata or 'align'");
2429 if (parseOptionalAlignment(Alignment
))
2436 /// parseOptionalCommaAddrSpace
2438 /// ::= ',' addrspace(1)
2440 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2442 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace
, LocTy
&Loc
,
2443 bool &AteExtraComma
) {
2444 AteExtraComma
= false;
2445 while (EatIfPresent(lltok::comma
)) {
2446 // Metadata at the end is an early exit.
2447 if (Lex
.getKind() == lltok::MetadataVar
) {
2448 AteExtraComma
= true;
2453 if (Lex
.getKind() != lltok::kw_addrspace
)
2454 return error(Lex
.getLoc(), "expected metadata or 'addrspace'");
2456 if (parseOptionalAddrSpace(AddrSpace
))
2463 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg
,
2464 std::optional
<unsigned> &HowManyArg
) {
2467 auto StartParen
= Lex
.getLoc();
2468 if (!EatIfPresent(lltok::lparen
))
2469 return error(StartParen
, "expected '('");
2471 if (parseUInt32(BaseSizeArg
))
2474 if (EatIfPresent(lltok::comma
)) {
2475 auto HowManyAt
= Lex
.getLoc();
2477 if (parseUInt32(HowMany
))
2479 if (HowMany
== BaseSizeArg
)
2480 return error(HowManyAt
,
2481 "'allocsize' indices can't refer to the same parameter");
2482 HowManyArg
= HowMany
;
2484 HowManyArg
= std::nullopt
;
2486 auto EndParen
= Lex
.getLoc();
2487 if (!EatIfPresent(lltok::rparen
))
2488 return error(EndParen
, "expected ')'");
2492 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue
,
2493 unsigned &MaxValue
) {
2496 auto StartParen
= Lex
.getLoc();
2497 if (!EatIfPresent(lltok::lparen
))
2498 return error(StartParen
, "expected '('");
2500 if (parseUInt32(MinValue
))
2503 if (EatIfPresent(lltok::comma
)) {
2504 if (parseUInt32(MaxValue
))
2507 MaxValue
= MinValue
;
2509 auto EndParen
= Lex
.getLoc();
2510 if (!EatIfPresent(lltok::rparen
))
2511 return error(EndParen
, "expected ')'");
2515 /// parseScopeAndOrdering
2516 /// if isAtomic: ::= SyncScope? AtomicOrdering
2519 /// This sets Scope and Ordering to the parsed values.
2520 bool LLParser::parseScopeAndOrdering(bool IsAtomic
, SyncScope::ID
&SSID
,
2521 AtomicOrdering
&Ordering
) {
2525 return parseScope(SSID
) || parseOrdering(Ordering
);
2529 /// ::= syncscope("singlethread" | "<target scope>")?
2531 /// This sets synchronization scope ID to the ID of the parsed value.
2532 bool LLParser::parseScope(SyncScope::ID
&SSID
) {
2533 SSID
= SyncScope::System
;
2534 if (EatIfPresent(lltok::kw_syncscope
)) {
2535 auto StartParenAt
= Lex
.getLoc();
2536 if (!EatIfPresent(lltok::lparen
))
2537 return error(StartParenAt
, "Expected '(' in syncscope");
2540 auto SSNAt
= Lex
.getLoc();
2541 if (parseStringConstant(SSN
))
2542 return error(SSNAt
, "Expected synchronization scope name");
2544 auto EndParenAt
= Lex
.getLoc();
2545 if (!EatIfPresent(lltok::rparen
))
2546 return error(EndParenAt
, "Expected ')' in syncscope");
2548 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2555 /// ::= AtomicOrdering
2557 /// This sets Ordering to the parsed value.
2558 bool LLParser::parseOrdering(AtomicOrdering
&Ordering
) {
2559 switch (Lex
.getKind()) {
2561 return tokError("Expected ordering on atomic instruction");
2562 case lltok::kw_unordered
: Ordering
= AtomicOrdering::Unordered
; break;
2563 case lltok::kw_monotonic
: Ordering
= AtomicOrdering::Monotonic
; break;
2564 // Not specified yet:
2565 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2566 case lltok::kw_acquire
: Ordering
= AtomicOrdering::Acquire
; break;
2567 case lltok::kw_release
: Ordering
= AtomicOrdering::Release
; break;
2568 case lltok::kw_acq_rel
: Ordering
= AtomicOrdering::AcquireRelease
; break;
2569 case lltok::kw_seq_cst
:
2570 Ordering
= AtomicOrdering::SequentiallyConsistent
;
2577 /// parseOptionalStackAlignment
2579 /// ::= 'alignstack' '(' 4 ')'
2580 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment
) {
2582 if (!EatIfPresent(lltok::kw_alignstack
))
2584 LocTy ParenLoc
= Lex
.getLoc();
2585 if (!EatIfPresent(lltok::lparen
))
2586 return error(ParenLoc
, "expected '('");
2587 LocTy AlignLoc
= Lex
.getLoc();
2588 if (parseUInt32(Alignment
))
2590 ParenLoc
= Lex
.getLoc();
2591 if (!EatIfPresent(lltok::rparen
))
2592 return error(ParenLoc
, "expected ')'");
2593 if (!isPowerOf2_32(Alignment
))
2594 return error(AlignLoc
, "stack alignment is not a power of two");
2598 /// parseIndexList - This parses the index list for an insert/extractvalue
2599 /// instruction. This sets AteExtraComma in the case where we eat an extra
2600 /// comma at the end of the line and find that it is followed by metadata.
2601 /// Clients that don't allow metadata can call the version of this function that
2602 /// only takes one argument.
2605 /// ::= (',' uint32)+
2607 bool LLParser::parseIndexList(SmallVectorImpl
<unsigned> &Indices
,
2608 bool &AteExtraComma
) {
2609 AteExtraComma
= false;
2611 if (Lex
.getKind() != lltok::comma
)
2612 return tokError("expected ',' as start of index list");
2614 while (EatIfPresent(lltok::comma
)) {
2615 if (Lex
.getKind() == lltok::MetadataVar
) {
2616 if (Indices
.empty())
2617 return tokError("expected index");
2618 AteExtraComma
= true;
2622 if (parseUInt32(Idx
))
2624 Indices
.push_back(Idx
);
2630 //===----------------------------------------------------------------------===//
2632 //===----------------------------------------------------------------------===//
2634 /// parseType - parse a type.
2635 bool LLParser::parseType(Type
*&Result
, const Twine
&Msg
, bool AllowVoid
) {
2636 SMLoc TypeLoc
= Lex
.getLoc();
2637 switch (Lex
.getKind()) {
2639 return tokError(Msg
);
2641 // Type ::= 'float' | 'void' (etc)
2642 Result
= Lex
.getTyVal();
2645 // Handle "ptr" opaque pointer type.
2647 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2648 if (Result
->isPointerTy()) {
2650 if (parseOptionalAddrSpace(AddrSpace
))
2652 Result
= PointerType::get(getContext(), AddrSpace
);
2654 // Give a nice error for 'ptr*'.
2655 if (Lex
.getKind() == lltok::star
)
2656 return tokError("ptr* is invalid - use ptr instead");
2658 // Fall through to parsing the type suffixes only if this 'ptr' is a
2659 // function return. Otherwise, return success, implicitly rejecting other
2661 if (Lex
.getKind() != lltok::lparen
)
2665 case lltok::kw_target
: {
2666 // Type ::= TargetExtType
2667 if (parseTargetExtType(Result
))
2672 // Type ::= StructType
2673 if (parseAnonStructType(Result
, false))
2676 case lltok::lsquare
:
2677 // Type ::= '[' ... ']'
2678 Lex
.Lex(); // eat the lsquare.
2679 if (parseArrayVectorType(Result
, false))
2682 case lltok::less
: // Either vector or packed struct.
2683 // Type ::= '<' ... '>'
2685 if (Lex
.getKind() == lltok::lbrace
) {
2686 if (parseAnonStructType(Result
, true) ||
2687 parseToken(lltok::greater
, "expected '>' at end of packed struct"))
2689 } else if (parseArrayVectorType(Result
, true))
2692 case lltok::LocalVar
: {
2694 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Lex
.getStrVal()];
2696 // If the type hasn't been defined yet, create a forward definition and
2697 // remember where that forward def'n was seen (in case it never is defined).
2699 Entry
.first
= StructType::create(Context
, Lex
.getStrVal());
2700 Entry
.second
= Lex
.getLoc();
2702 Result
= Entry
.first
;
2707 case lltok::LocalVarID
: {
2709 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[Lex
.getUIntVal()];
2711 // If the type hasn't been defined yet, create a forward definition and
2712 // remember where that forward def'n was seen (in case it never is defined).
2714 Entry
.first
= StructType::create(Context
);
2715 Entry
.second
= Lex
.getLoc();
2717 Result
= Entry
.first
;
2723 // parse the type suffixes.
2725 switch (Lex
.getKind()) {
2728 if (!AllowVoid
&& Result
->isVoidTy())
2729 return error(TypeLoc
, "void type only allowed for function results");
2732 // Type ::= Type '*'
2734 if (Result
->isLabelTy())
2735 return tokError("basic block pointers are invalid");
2736 if (Result
->isVoidTy())
2737 return tokError("pointers to void are invalid - use i8* instead");
2738 if (!PointerType::isValidElementType(Result
))
2739 return tokError("pointer to this type is invalid");
2740 Result
= PointerType::getUnqual(Result
);
2744 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2745 case lltok::kw_addrspace
: {
2746 if (Result
->isLabelTy())
2747 return tokError("basic block pointers are invalid");
2748 if (Result
->isVoidTy())
2749 return tokError("pointers to void are invalid; use i8* instead");
2750 if (!PointerType::isValidElementType(Result
))
2751 return tokError("pointer to this type is invalid");
2753 if (parseOptionalAddrSpace(AddrSpace
) ||
2754 parseToken(lltok::star
, "expected '*' in address space"))
2757 Result
= PointerType::get(Result
, AddrSpace
);
2761 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2763 if (parseFunctionType(Result
))
2770 /// parseParameterList
2772 /// ::= '(' Arg (',' Arg)* ')'
2774 /// ::= Type OptionalAttributes Value OptionalAttributes
2775 bool LLParser::parseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
2776 PerFunctionState
&PFS
, bool IsMustTailCall
,
2777 bool InVarArgsFunc
) {
2778 if (parseToken(lltok::lparen
, "expected '(' in call"))
2781 while (Lex
.getKind() != lltok::rparen
) {
2782 // If this isn't the first argument, we need a comma.
2783 if (!ArgList
.empty() &&
2784 parseToken(lltok::comma
, "expected ',' in argument list"))
2787 // parse an ellipsis if this is a musttail call in a variadic function.
2788 if (Lex
.getKind() == lltok::dotdotdot
) {
2789 const char *Msg
= "unexpected ellipsis in argument list for ";
2790 if (!IsMustTailCall
)
2791 return tokError(Twine(Msg
) + "non-musttail call");
2793 return tokError(Twine(Msg
) + "musttail call in non-varargs function");
2794 Lex
.Lex(); // Lex the '...', it is purely for readability.
2795 return parseToken(lltok::rparen
, "expected ')' at end of argument list");
2798 // parse the argument.
2800 Type
*ArgTy
= nullptr;
2802 if (parseType(ArgTy
, ArgLoc
))
2805 AttrBuilder
ArgAttrs(M
->getContext());
2807 if (ArgTy
->isMetadataTy()) {
2808 if (parseMetadataAsValue(V
, PFS
))
2811 // Otherwise, handle normal operands.
2812 if (parseOptionalParamAttrs(ArgAttrs
) || parseValue(ArgTy
, V
, PFS
))
2815 ArgList
.push_back(ParamInfo(
2816 ArgLoc
, V
, AttributeSet::get(V
->getContext(), ArgAttrs
)));
2819 if (IsMustTailCall
&& InVarArgsFunc
)
2820 return tokError("expected '...' at end of argument list for musttail call "
2821 "in varargs function");
2823 Lex
.Lex(); // Lex the ')'.
2827 /// parseRequiredTypeAttr
2828 /// ::= attrname(<ty>)
2829 bool LLParser::parseRequiredTypeAttr(AttrBuilder
&B
, lltok::Kind AttrToken
,
2830 Attribute::AttrKind AttrKind
) {
2832 if (!EatIfPresent(AttrToken
))
2834 if (!EatIfPresent(lltok::lparen
))
2835 return error(Lex
.getLoc(), "expected '('");
2838 if (!EatIfPresent(lltok::rparen
))
2839 return error(Lex
.getLoc(), "expected ')'");
2841 B
.addTypeAttr(AttrKind
, Ty
);
2845 /// parseOptionalOperandBundles
2847 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2850 /// ::= bundle-tag '(' ')'
2851 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2853 /// bundle-tag ::= String Constant
2854 bool LLParser::parseOptionalOperandBundles(
2855 SmallVectorImpl
<OperandBundleDef
> &BundleList
, PerFunctionState
&PFS
) {
2856 LocTy BeginLoc
= Lex
.getLoc();
2857 if (!EatIfPresent(lltok::lsquare
))
2860 while (Lex
.getKind() != lltok::rsquare
) {
2861 // If this isn't the first operand bundle, we need a comma.
2862 if (!BundleList
.empty() &&
2863 parseToken(lltok::comma
, "expected ',' in input list"))
2867 if (parseStringConstant(Tag
))
2870 if (parseToken(lltok::lparen
, "expected '(' in operand bundle"))
2873 std::vector
<Value
*> Inputs
;
2874 while (Lex
.getKind() != lltok::rparen
) {
2875 // If this isn't the first input, we need a comma.
2876 if (!Inputs
.empty() &&
2877 parseToken(lltok::comma
, "expected ',' in input list"))
2881 Value
*Input
= nullptr;
2882 if (parseType(Ty
) || parseValue(Ty
, Input
, PFS
))
2884 Inputs
.push_back(Input
);
2887 BundleList
.emplace_back(std::move(Tag
), std::move(Inputs
));
2889 Lex
.Lex(); // Lex the ')'.
2892 if (BundleList
.empty())
2893 return error(BeginLoc
, "operand bundle set must not be empty");
2895 Lex
.Lex(); // Lex the ']'.
2899 /// parseArgumentList - parse the argument list for a function type or function
2901 /// ::= '(' ArgTypeListI ')'
2905 /// ::= ArgTypeList ',' '...'
2906 /// ::= ArgType (',' ArgType)*
2908 bool LLParser::parseArgumentList(SmallVectorImpl
<ArgInfo
> &ArgList
,
2910 unsigned CurValID
= 0;
2912 assert(Lex
.getKind() == lltok::lparen
);
2913 Lex
.Lex(); // eat the (.
2915 if (Lex
.getKind() == lltok::rparen
) {
2917 } else if (Lex
.getKind() == lltok::dotdotdot
) {
2921 LocTy TypeLoc
= Lex
.getLoc();
2922 Type
*ArgTy
= nullptr;
2923 AttrBuilder
Attrs(M
->getContext());
2926 if (parseType(ArgTy
) || parseOptionalParamAttrs(Attrs
))
2929 if (ArgTy
->isVoidTy())
2930 return error(TypeLoc
, "argument can not have void type");
2932 if (Lex
.getKind() == lltok::LocalVar
) {
2933 Name
= Lex
.getStrVal();
2935 } else if (Lex
.getKind() == lltok::LocalVarID
) {
2936 if (Lex
.getUIntVal() != CurValID
)
2937 return error(TypeLoc
, "argument expected to be numbered '%" +
2938 Twine(CurValID
) + "'");
2943 if (!FunctionType::isValidArgumentType(ArgTy
))
2944 return error(TypeLoc
, "invalid type for function argument");
2946 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2947 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2950 while (EatIfPresent(lltok::comma
)) {
2951 // Handle ... at end of arg list.
2952 if (EatIfPresent(lltok::dotdotdot
)) {
2957 // Otherwise must be an argument type.
2958 TypeLoc
= Lex
.getLoc();
2959 if (parseType(ArgTy
) || parseOptionalParamAttrs(Attrs
))
2962 if (ArgTy
->isVoidTy())
2963 return error(TypeLoc
, "argument can not have void type");
2965 if (Lex
.getKind() == lltok::LocalVar
) {
2966 Name
= Lex
.getStrVal();
2969 if (Lex
.getKind() == lltok::LocalVarID
) {
2970 if (Lex
.getUIntVal() != CurValID
)
2971 return error(TypeLoc
, "argument expected to be numbered '%" +
2972 Twine(CurValID
) + "'");
2979 if (!ArgTy
->isFirstClassType())
2980 return error(TypeLoc
, "invalid type for function argument");
2982 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2983 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2988 return parseToken(lltok::rparen
, "expected ')' at end of argument list");
2991 /// parseFunctionType
2992 /// ::= Type ArgumentList OptionalAttrs
2993 bool LLParser::parseFunctionType(Type
*&Result
) {
2994 assert(Lex
.getKind() == lltok::lparen
);
2996 if (!FunctionType::isValidReturnType(Result
))
2997 return tokError("invalid function return type");
2999 SmallVector
<ArgInfo
, 8> ArgList
;
3001 if (parseArgumentList(ArgList
, IsVarArg
))
3004 // Reject names on the arguments lists.
3005 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3006 if (!ArgList
[i
].Name
.empty())
3007 return error(ArgList
[i
].Loc
, "argument name invalid in function type");
3008 if (ArgList
[i
].Attrs
.hasAttributes())
3009 return error(ArgList
[i
].Loc
,
3010 "argument attributes invalid in function type");
3013 SmallVector
<Type
*, 16> ArgListTy
;
3014 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3015 ArgListTy
.push_back(ArgList
[i
].Ty
);
3017 Result
= FunctionType::get(Result
, ArgListTy
, IsVarArg
);
3021 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
3023 bool LLParser::parseAnonStructType(Type
*&Result
, bool Packed
) {
3024 SmallVector
<Type
*, 8> Elts
;
3025 if (parseStructBody(Elts
))
3028 Result
= StructType::get(Context
, Elts
, Packed
);
3032 /// parseStructDefinition - parse a struct in a 'type' definition.
3033 bool LLParser::parseStructDefinition(SMLoc TypeLoc
, StringRef Name
,
3034 std::pair
<Type
*, LocTy
> &Entry
,
3036 // If the type was already defined, diagnose the redefinition.
3037 if (Entry
.first
&& !Entry
.second
.isValid())
3038 return error(TypeLoc
, "redefinition of type");
3040 // If we have opaque, just return without filling in the definition for the
3041 // struct. This counts as a definition as far as the .ll file goes.
3042 if (EatIfPresent(lltok::kw_opaque
)) {
3043 // This type is being defined, so clear the location to indicate this.
3044 Entry
.second
= SMLoc();
3046 // If this type number has never been uttered, create it.
3048 Entry
.first
= StructType::create(Context
, Name
);
3049 ResultTy
= Entry
.first
;
3053 // If the type starts with '<', then it is either a packed struct or a vector.
3054 bool isPacked
= EatIfPresent(lltok::less
);
3056 // If we don't have a struct, then we have a random type alias, which we
3057 // accept for compatibility with old files. These types are not allowed to be
3058 // forward referenced and not allowed to be recursive.
3059 if (Lex
.getKind() != lltok::lbrace
) {
3061 return error(TypeLoc
, "forward references to non-struct type");
3065 return parseArrayVectorType(ResultTy
, true);
3066 return parseType(ResultTy
);
3069 // This type is being defined, so clear the location to indicate this.
3070 Entry
.second
= SMLoc();
3072 // If this type number has never been uttered, create it.
3074 Entry
.first
= StructType::create(Context
, Name
);
3076 StructType
*STy
= cast
<StructType
>(Entry
.first
);
3078 SmallVector
<Type
*, 8> Body
;
3079 if (parseStructBody(Body
) ||
3080 (isPacked
&& parseToken(lltok::greater
, "expected '>' in packed struct")))
3083 STy
->setBody(Body
, isPacked
);
3088 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3091 /// ::= '{' Type (',' Type)* '}'
3092 /// ::= '<' '{' '}' '>'
3093 /// ::= '<' '{' Type (',' Type)* '}' '>'
3094 bool LLParser::parseStructBody(SmallVectorImpl
<Type
*> &Body
) {
3095 assert(Lex
.getKind() == lltok::lbrace
);
3096 Lex
.Lex(); // Consume the '{'
3098 // Handle the empty struct.
3099 if (EatIfPresent(lltok::rbrace
))
3102 LocTy EltTyLoc
= Lex
.getLoc();
3108 if (!StructType::isValidElementType(Ty
))
3109 return error(EltTyLoc
, "invalid element type for struct");
3111 while (EatIfPresent(lltok::comma
)) {
3112 EltTyLoc
= Lex
.getLoc();
3116 if (!StructType::isValidElementType(Ty
))
3117 return error(EltTyLoc
, "invalid element type for struct");
3122 return parseToken(lltok::rbrace
, "expected '}' at end of struct");
3125 /// parseArrayVectorType - parse an array or vector type, assuming the first
3126 /// token has already been consumed.
3128 /// ::= '[' APSINTVAL 'x' Types ']'
3129 /// ::= '<' APSINTVAL 'x' Types '>'
3130 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3131 bool LLParser::parseArrayVectorType(Type
*&Result
, bool IsVector
) {
3132 bool Scalable
= false;
3134 if (IsVector
&& Lex
.getKind() == lltok::kw_vscale
) {
3135 Lex
.Lex(); // consume the 'vscale'
3136 if (parseToken(lltok::kw_x
, "expected 'x' after vscale"))
3142 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
3143 Lex
.getAPSIntVal().getBitWidth() > 64)
3144 return tokError("expected number in address space");
3146 LocTy SizeLoc
= Lex
.getLoc();
3147 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
3150 if (parseToken(lltok::kw_x
, "expected 'x' after element count"))
3153 LocTy TypeLoc
= Lex
.getLoc();
3154 Type
*EltTy
= nullptr;
3155 if (parseType(EltTy
))
3158 if (parseToken(IsVector
? lltok::greater
: lltok::rsquare
,
3159 "expected end of sequential type"))
3164 return error(SizeLoc
, "zero element vector is illegal");
3165 if ((unsigned)Size
!= Size
)
3166 return error(SizeLoc
, "size too large for vector");
3167 if (!VectorType::isValidElementType(EltTy
))
3168 return error(TypeLoc
, "invalid vector element type");
3169 Result
= VectorType::get(EltTy
, unsigned(Size
), Scalable
);
3171 if (!ArrayType::isValidElementType(EltTy
))
3172 return error(TypeLoc
, "invalid array element type");
3173 Result
= ArrayType::get(EltTy
, Size
);
3178 /// parseTargetExtType - handle target extension type syntax
3180 /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3182 /// TargetExtTypeParams
3184 /// ::= ',' Type TargetExtTypeParams
3186 /// TargetExtIntParams
3188 /// ::= ',' uint32 TargetExtIntParams
3189 bool LLParser::parseTargetExtType(Type
*&Result
) {
3190 Lex
.Lex(); // Eat the 'target' keyword.
3192 // Get the mandatory type name.
3193 std::string TypeName
;
3194 if (parseToken(lltok::lparen
, "expected '(' in target extension type") ||
3195 parseStringConstant(TypeName
))
3198 // Parse all of the integer and type parameters at the same time; the use of
3199 // SeenInt will allow us to catch cases where type parameters follow integer
3201 SmallVector
<Type
*> TypeParams
;
3202 SmallVector
<unsigned> IntParams
;
3203 bool SeenInt
= false;
3204 while (Lex
.getKind() == lltok::comma
) {
3205 Lex
.Lex(); // Eat the comma.
3207 if (Lex
.getKind() == lltok::APSInt
) {
3210 if (parseUInt32(IntVal
))
3212 IntParams
.push_back(IntVal
);
3213 } else if (SeenInt
) {
3214 // The only other kind of parameter we support is type parameters, which
3215 // must precede the integer parameters. This is therefore an error.
3216 return tokError("expected uint32 param");
3219 if (parseType(TypeParam
, /*AllowVoid=*/true))
3221 TypeParams
.push_back(TypeParam
);
3225 if (parseToken(lltok::rparen
, "expected ')' in target extension type"))
3228 Result
= TargetExtType::get(Context
, TypeName
, TypeParams
, IntParams
);
3232 //===----------------------------------------------------------------------===//
3233 // Function Semantic Analysis.
3234 //===----------------------------------------------------------------------===//
3236 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
3238 : P(p
), F(f
), FunctionNumber(functionNumber
) {
3240 // Insert unnamed arguments into the NumberedVals list.
3241 for (Argument
&A
: F
.args())
3243 NumberedVals
.push_back(&A
);
3246 LLParser::PerFunctionState::~PerFunctionState() {
3247 // If there were any forward referenced non-basicblock values, delete them.
3249 for (const auto &P
: ForwardRefVals
) {
3250 if (isa
<BasicBlock
>(P
.second
.first
))
3252 P
.second
.first
->replaceAllUsesWith(
3253 UndefValue::get(P
.second
.first
->getType()));
3254 P
.second
.first
->deleteValue();
3257 for (const auto &P
: ForwardRefValIDs
) {
3258 if (isa
<BasicBlock
>(P
.second
.first
))
3260 P
.second
.first
->replaceAllUsesWith(
3261 UndefValue::get(P
.second
.first
->getType()));
3262 P
.second
.first
->deleteValue();
3266 bool LLParser::PerFunctionState::finishFunction() {
3267 if (!ForwardRefVals
.empty())
3268 return P
.error(ForwardRefVals
.begin()->second
.second
,
3269 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
3271 if (!ForwardRefValIDs
.empty())
3272 return P
.error(ForwardRefValIDs
.begin()->second
.second
,
3273 "use of undefined value '%" +
3274 Twine(ForwardRefValIDs
.begin()->first
) + "'");
3278 /// getVal - Get a value with the specified name or ID, creating a
3279 /// forward reference record if needed. This can return null if the value
3280 /// exists but does not have the right type.
3281 Value
*LLParser::PerFunctionState::getVal(const std::string
&Name
, Type
*Ty
,
3283 // Look this name up in the normal function symbol table.
3284 Value
*Val
= F
.getValueSymbolTable()->lookup(Name
);
3286 // If this is a forward reference for the value, see if we already created a
3287 // forward ref record.
3289 auto I
= ForwardRefVals
.find(Name
);
3290 if (I
!= ForwardRefVals
.end())
3291 Val
= I
->second
.first
;
3294 // If we have the value in the symbol table or fwd-ref table, return it.
3296 return P
.checkValidVariableType(Loc
, "%" + Name
, Ty
, Val
);
3298 // Don't make placeholders with invalid type.
3299 if (!Ty
->isFirstClassType()) {
3300 P
.error(Loc
, "invalid use of a non-first-class type");
3304 // Otherwise, create a new forward reference for this value and remember it.
3306 if (Ty
->isLabelTy()) {
3307 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
3309 FwdVal
= new Argument(Ty
, Name
);
3311 if (FwdVal
->getName() != Name
) {
3312 P
.error(Loc
, "name is too long which can result in name collisions, "
3313 "consider making the name shorter or "
3314 "increasing -non-global-value-max-name-size");
3318 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
3322 Value
*LLParser::PerFunctionState::getVal(unsigned ID
, Type
*Ty
, LocTy Loc
) {
3323 // Look this name up in the normal function symbol table.
3324 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
3326 // If this is a forward reference for the value, see if we already created a
3327 // forward ref record.
3329 auto I
= ForwardRefValIDs
.find(ID
);
3330 if (I
!= ForwardRefValIDs
.end())
3331 Val
= I
->second
.first
;
3334 // If we have the value in the symbol table or fwd-ref table, return it.
3336 return P
.checkValidVariableType(Loc
, "%" + Twine(ID
), Ty
, Val
);
3338 if (!Ty
->isFirstClassType()) {
3339 P
.error(Loc
, "invalid use of a non-first-class type");
3343 // Otherwise, create a new forward reference for this value and remember it.
3345 if (Ty
->isLabelTy()) {
3346 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
3348 FwdVal
= new Argument(Ty
);
3351 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
3355 /// setInstName - After an instruction is parsed and inserted into its
3356 /// basic block, this installs its name.
3357 bool LLParser::PerFunctionState::setInstName(int NameID
,
3358 const std::string
&NameStr
,
3359 LocTy NameLoc
, Instruction
*Inst
) {
3360 // If this instruction has void type, it cannot have a name or ID specified.
3361 if (Inst
->getType()->isVoidTy()) {
3362 if (NameID
!= -1 || !NameStr
.empty())
3363 return P
.error(NameLoc
, "instructions returning void cannot have a name");
3367 // If this was a numbered instruction, verify that the instruction is the
3368 // expected value and resolve any forward references.
3369 if (NameStr
.empty()) {
3370 // If neither a name nor an ID was specified, just use the next ID.
3372 NameID
= NumberedVals
.size();
3374 if (unsigned(NameID
) != NumberedVals
.size())
3375 return P
.error(NameLoc
, "instruction expected to be numbered '%" +
3376 Twine(NumberedVals
.size()) + "'");
3378 auto FI
= ForwardRefValIDs
.find(NameID
);
3379 if (FI
!= ForwardRefValIDs
.end()) {
3380 Value
*Sentinel
= FI
->second
.first
;
3381 if (Sentinel
->getType() != Inst
->getType())
3382 return P
.error(NameLoc
, "instruction forward referenced with type '" +
3383 getTypeString(FI
->second
.first
->getType()) +
3386 Sentinel
->replaceAllUsesWith(Inst
);
3387 Sentinel
->deleteValue();
3388 ForwardRefValIDs
.erase(FI
);
3391 NumberedVals
.push_back(Inst
);
3395 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3396 auto FI
= ForwardRefVals
.find(NameStr
);
3397 if (FI
!= ForwardRefVals
.end()) {
3398 Value
*Sentinel
= FI
->second
.first
;
3399 if (Sentinel
->getType() != Inst
->getType())
3400 return P
.error(NameLoc
, "instruction forward referenced with type '" +
3401 getTypeString(FI
->second
.first
->getType()) +
3404 Sentinel
->replaceAllUsesWith(Inst
);
3405 Sentinel
->deleteValue();
3406 ForwardRefVals
.erase(FI
);
3409 // Set the name on the instruction.
3410 Inst
->setName(NameStr
);
3412 if (Inst
->getName() != NameStr
)
3413 return P
.error(NameLoc
, "multiple definition of local value named '" +
3418 /// getBB - Get a basic block with the specified name or ID, creating a
3419 /// forward reference record if needed.
3420 BasicBlock
*LLParser::PerFunctionState::getBB(const std::string
&Name
,
3422 return dyn_cast_or_null
<BasicBlock
>(
3423 getVal(Name
, Type::getLabelTy(F
.getContext()), Loc
));
3426 BasicBlock
*LLParser::PerFunctionState::getBB(unsigned ID
, LocTy Loc
) {
3427 return dyn_cast_or_null
<BasicBlock
>(
3428 getVal(ID
, Type::getLabelTy(F
.getContext()), Loc
));
3431 /// defineBB - Define the specified basic block, which is either named or
3432 /// unnamed. If there is an error, this returns null otherwise it returns
3433 /// the block being defined.
3434 BasicBlock
*LLParser::PerFunctionState::defineBB(const std::string
&Name
,
3435 int NameID
, LocTy Loc
) {
3438 if (NameID
!= -1 && unsigned(NameID
) != NumberedVals
.size()) {
3439 P
.error(Loc
, "label expected to be numbered '" +
3440 Twine(NumberedVals
.size()) + "'");
3443 BB
= getBB(NumberedVals
.size(), Loc
);
3445 P
.error(Loc
, "unable to create block numbered '" +
3446 Twine(NumberedVals
.size()) + "'");
3450 BB
= getBB(Name
, Loc
);
3452 P
.error(Loc
, "unable to create block named '" + Name
+ "'");
3457 // Move the block to the end of the function. Forward ref'd blocks are
3458 // inserted wherever they happen to be referenced.
3459 F
.splice(F
.end(), &F
, BB
->getIterator());
3461 // Remove the block from forward ref sets.
3463 ForwardRefValIDs
.erase(NumberedVals
.size());
3464 NumberedVals
.push_back(BB
);
3466 // BB forward references are already in the function symbol table.
3467 ForwardRefVals
.erase(Name
);
3473 //===----------------------------------------------------------------------===//
3475 //===----------------------------------------------------------------------===//
3477 /// parseValID - parse an abstract value that doesn't necessarily have a
3478 /// type implied. For example, if we parse "4" we don't know what integer type
3479 /// it has. The value will later be combined with its type and checked for
3480 /// basic correctness. PFS is used to convert function-local operands of
3481 /// metadata (since metadata operands are not just parsed here but also
3482 /// converted to values). PFS can be null when we are not parsing metadata
3483 /// values inside a function.
3484 bool LLParser::parseValID(ValID
&ID
, PerFunctionState
*PFS
, Type
*ExpectedTy
) {
3485 ID
.Loc
= Lex
.getLoc();
3486 switch (Lex
.getKind()) {
3488 return tokError("expected value token");
3489 case lltok::GlobalID
: // @42
3490 ID
.UIntVal
= Lex
.getUIntVal();
3491 ID
.Kind
= ValID::t_GlobalID
;
3493 case lltok::GlobalVar
: // @foo
3494 ID
.StrVal
= Lex
.getStrVal();
3495 ID
.Kind
= ValID::t_GlobalName
;
3497 case lltok::LocalVarID
: // %42
3498 ID
.UIntVal
= Lex
.getUIntVal();
3499 ID
.Kind
= ValID::t_LocalID
;
3501 case lltok::LocalVar
: // %foo
3502 ID
.StrVal
= Lex
.getStrVal();
3503 ID
.Kind
= ValID::t_LocalName
;
3506 ID
.APSIntVal
= Lex
.getAPSIntVal();
3507 ID
.Kind
= ValID::t_APSInt
;
3509 case lltok::APFloat
:
3510 ID
.APFloatVal
= Lex
.getAPFloatVal();
3511 ID
.Kind
= ValID::t_APFloat
;
3513 case lltok::kw_true
:
3514 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
3515 ID
.Kind
= ValID::t_Constant
;
3517 case lltok::kw_false
:
3518 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
3519 ID
.Kind
= ValID::t_Constant
;
3521 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
3522 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
3523 case lltok::kw_poison
: ID
.Kind
= ValID::t_Poison
; break;
3524 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
3525 case lltok::kw_none
: ID
.Kind
= ValID::t_None
; break;
3527 case lltok::lbrace
: {
3528 // ValID ::= '{' ConstVector '}'
3530 SmallVector
<Constant
*, 16> Elts
;
3531 if (parseGlobalValueVector(Elts
) ||
3532 parseToken(lltok::rbrace
, "expected end of struct constant"))
3535 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3536 ID
.UIntVal
= Elts
.size();
3537 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3538 Elts
.size() * sizeof(Elts
[0]));
3539 ID
.Kind
= ValID::t_ConstantStruct
;
3543 // ValID ::= '<' ConstVector '>' --> Vector.
3544 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3546 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
3548 SmallVector
<Constant
*, 16> Elts
;
3549 LocTy FirstEltLoc
= Lex
.getLoc();
3550 if (parseGlobalValueVector(Elts
) ||
3552 parseToken(lltok::rbrace
, "expected end of packed struct")) ||
3553 parseToken(lltok::greater
, "expected end of constant"))
3556 if (isPackedStruct
) {
3557 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3558 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3559 Elts
.size() * sizeof(Elts
[0]));
3560 ID
.UIntVal
= Elts
.size();
3561 ID
.Kind
= ValID::t_PackedConstantStruct
;
3566 return error(ID
.Loc
, "constant vector must not be empty");
3568 if (!Elts
[0]->getType()->isIntegerTy() &&
3569 !Elts
[0]->getType()->isFloatingPointTy() &&
3570 !Elts
[0]->getType()->isPointerTy())
3573 "vector elements must have integer, pointer or floating point type");
3575 // Verify that all the vector elements have the same type.
3576 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
3577 if (Elts
[i
]->getType() != Elts
[0]->getType())
3578 return error(FirstEltLoc
, "vector element #" + Twine(i
) +
3579 " is not of type '" +
3580 getTypeString(Elts
[0]->getType()));
3582 ID
.ConstantVal
= ConstantVector::get(Elts
);
3583 ID
.Kind
= ValID::t_Constant
;
3586 case lltok::lsquare
: { // Array Constant
3588 SmallVector
<Constant
*, 16> Elts
;
3589 LocTy FirstEltLoc
= Lex
.getLoc();
3590 if (parseGlobalValueVector(Elts
) ||
3591 parseToken(lltok::rsquare
, "expected end of array constant"))
3594 // Handle empty element.
3596 // Use undef instead of an array because it's inconvenient to determine
3597 // the element type at this point, there being no elements to examine.
3598 ID
.Kind
= ValID::t_EmptyArray
;
3602 if (!Elts
[0]->getType()->isFirstClassType())
3603 return error(FirstEltLoc
, "invalid array element type: " +
3604 getTypeString(Elts
[0]->getType()));
3606 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
3608 // Verify all elements are correct type!
3609 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
3610 if (Elts
[i
]->getType() != Elts
[0]->getType())
3611 return error(FirstEltLoc
, "array element #" + Twine(i
) +
3612 " is not of type '" +
3613 getTypeString(Elts
[0]->getType()));
3616 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
);
3617 ID
.Kind
= ValID::t_Constant
;
3620 case lltok::kw_c
: // c "foo"
3622 ID
.ConstantVal
= ConstantDataArray::getString(Context
, Lex
.getStrVal(),
3624 if (parseToken(lltok::StringConstant
, "expected string"))
3626 ID
.Kind
= ValID::t_Constant
;
3629 case lltok::kw_asm
: {
3630 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3632 bool HasSideEffect
, AlignStack
, AsmDialect
, CanThrow
;
3634 if (parseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
3635 parseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
3636 parseOptionalToken(lltok::kw_inteldialect
, AsmDialect
) ||
3637 parseOptionalToken(lltok::kw_unwind
, CanThrow
) ||
3638 parseStringConstant(ID
.StrVal
) ||
3639 parseToken(lltok::comma
, "expected comma in inline asm expression") ||
3640 parseToken(lltok::StringConstant
, "expected constraint string"))
3642 ID
.StrVal2
= Lex
.getStrVal();
3643 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
) << 1) |
3644 (unsigned(AsmDialect
) << 2) | (unsigned(CanThrow
) << 3);
3645 ID
.Kind
= ValID::t_InlineAsm
;
3649 case lltok::kw_blockaddress
: {
3650 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3655 if (parseToken(lltok::lparen
, "expected '(' in block address expression") ||
3656 parseValID(Fn
, PFS
) ||
3657 parseToken(lltok::comma
,
3658 "expected comma in block address expression") ||
3659 parseValID(Label
, PFS
) ||
3660 parseToken(lltok::rparen
, "expected ')' in block address expression"))
3663 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3664 return error(Fn
.Loc
, "expected function name in blockaddress");
3665 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
3666 return error(Label
.Loc
, "expected basic block name in blockaddress");
3668 // Try to find the function (but skip it if it's forward-referenced).
3669 GlobalValue
*GV
= nullptr;
3670 if (Fn
.Kind
== ValID::t_GlobalID
) {
3671 if (Fn
.UIntVal
< NumberedVals
.size())
3672 GV
= NumberedVals
[Fn
.UIntVal
];
3673 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3674 GV
= M
->getNamedValue(Fn
.StrVal
);
3676 Function
*F
= nullptr;
3678 // Confirm that it's actually a function with a definition.
3679 if (!isa
<Function
>(GV
))
3680 return error(Fn
.Loc
, "expected function name in blockaddress");
3681 F
= cast
<Function
>(GV
);
3682 if (F
->isDeclaration())
3683 return error(Fn
.Loc
, "cannot take blockaddress inside a declaration");
3687 // Make a global variable as a placeholder for this reference.
3688 GlobalValue
*&FwdRef
=
3689 ForwardRefBlockAddresses
.insert(std::make_pair(
3691 std::map
<ValID
, GlobalValue
*>()))
3692 .first
->second
.insert(std::make_pair(std::move(Label
), nullptr))
3697 // If we know the type that the blockaddress is being assigned to,
3698 // we can use the address space of that type.
3699 if (!ExpectedTy
->isPointerTy())
3700 return error(ID
.Loc
,
3701 "type of blockaddress must be a pointer and not '" +
3702 getTypeString(ExpectedTy
) + "'");
3703 FwdDeclAS
= ExpectedTy
->getPointerAddressSpace();
3705 // Otherwise, we default the address space of the current function.
3706 FwdDeclAS
= PFS
->getFunction().getAddressSpace();
3708 llvm_unreachable("Unknown address space for blockaddress");
3710 FwdRef
= new GlobalVariable(
3711 *M
, Type::getInt8Ty(Context
), false, GlobalValue::InternalLinkage
,
3712 nullptr, "", nullptr, GlobalValue::NotThreadLocal
, FwdDeclAS
);
3715 ID
.ConstantVal
= FwdRef
;
3716 ID
.Kind
= ValID::t_Constant
;
3720 // We found the function; now find the basic block. Don't use PFS, since we
3721 // might be inside a constant expression.
3723 if (BlockAddressPFS
&& F
== &BlockAddressPFS
->getFunction()) {
3724 if (Label
.Kind
== ValID::t_LocalID
)
3725 BB
= BlockAddressPFS
->getBB(Label
.UIntVal
, Label
.Loc
);
3727 BB
= BlockAddressPFS
->getBB(Label
.StrVal
, Label
.Loc
);
3729 return error(Label
.Loc
, "referenced value is not a basic block");
3731 if (Label
.Kind
== ValID::t_LocalID
)
3732 return error(Label
.Loc
, "cannot take address of numeric label after "
3733 "the function is defined");
3734 BB
= dyn_cast_or_null
<BasicBlock
>(
3735 F
->getValueSymbolTable()->lookup(Label
.StrVal
));
3737 return error(Label
.Loc
, "referenced value is not a basic block");
3740 ID
.ConstantVal
= BlockAddress::get(F
, BB
);
3741 ID
.Kind
= ValID::t_Constant
;
3745 case lltok::kw_dso_local_equivalent
: {
3746 // ValID ::= 'dso_local_equivalent' @foo
3751 if (parseValID(Fn
, PFS
))
3754 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3755 return error(Fn
.Loc
,
3756 "expected global value name in dso_local_equivalent");
3758 // Try to find the function (but skip it if it's forward-referenced).
3759 GlobalValue
*GV
= nullptr;
3760 if (Fn
.Kind
== ValID::t_GlobalID
) {
3761 if (Fn
.UIntVal
< NumberedVals
.size())
3762 GV
= NumberedVals
[Fn
.UIntVal
];
3763 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3764 GV
= M
->getNamedValue(Fn
.StrVal
);
3768 // Make a placeholder global variable as a placeholder for this reference.
3769 auto &FwdRefMap
= (Fn
.Kind
== ValID::t_GlobalID
)
3770 ? ForwardRefDSOLocalEquivalentIDs
3771 : ForwardRefDSOLocalEquivalentNames
;
3772 GlobalValue
*&FwdRef
= FwdRefMap
.try_emplace(Fn
, nullptr).first
->second
;
3774 FwdRef
= new GlobalVariable(*M
, Type::getInt8Ty(Context
), false,
3775 GlobalValue::InternalLinkage
, nullptr, "",
3776 nullptr, GlobalValue::NotThreadLocal
);
3779 ID
.ConstantVal
= FwdRef
;
3780 ID
.Kind
= ValID::t_Constant
;
3784 if (!GV
->getValueType()->isFunctionTy())
3785 return error(Fn
.Loc
, "expected a function, alias to function, or ifunc "
3786 "in dso_local_equivalent");
3788 ID
.ConstantVal
= DSOLocalEquivalent::get(GV
);
3789 ID
.Kind
= ValID::t_Constant
;
3793 case lltok::kw_no_cfi
: {
3794 // ValID ::= 'no_cfi' @foo
3797 if (parseValID(ID
, PFS
))
3800 if (ID
.Kind
!= ValID::t_GlobalID
&& ID
.Kind
!= ValID::t_GlobalName
)
3801 return error(ID
.Loc
, "expected global value name in no_cfi");
3807 case lltok::kw_trunc
:
3808 case lltok::kw_zext
:
3809 case lltok::kw_sext
:
3810 case lltok::kw_fptrunc
:
3811 case lltok::kw_fpext
:
3812 case lltok::kw_bitcast
:
3813 case lltok::kw_addrspacecast
:
3814 case lltok::kw_uitofp
:
3815 case lltok::kw_sitofp
:
3816 case lltok::kw_fptoui
:
3817 case lltok::kw_fptosi
:
3818 case lltok::kw_inttoptr
:
3819 case lltok::kw_ptrtoint
: {
3820 unsigned Opc
= Lex
.getUIntVal();
3821 Type
*DestTy
= nullptr;
3824 if (parseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
3825 parseGlobalTypeAndValue(SrcVal
) ||
3826 parseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
3827 parseType(DestTy
) ||
3828 parseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
3830 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
3831 return error(ID
.Loc
, "invalid cast opcode for cast from '" +
3832 getTypeString(SrcVal
->getType()) + "' to '" +
3833 getTypeString(DestTy
) + "'");
3834 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
3836 ID
.Kind
= ValID::t_Constant
;
3839 case lltok::kw_extractvalue
:
3840 return error(ID
.Loc
, "extractvalue constexprs are no longer supported");
3841 case lltok::kw_insertvalue
:
3842 return error(ID
.Loc
, "insertvalue constexprs are no longer supported");
3843 case lltok::kw_udiv
:
3844 return error(ID
.Loc
, "udiv constexprs are no longer supported");
3845 case lltok::kw_sdiv
:
3846 return error(ID
.Loc
, "sdiv constexprs are no longer supported");
3847 case lltok::kw_urem
:
3848 return error(ID
.Loc
, "urem constexprs are no longer supported");
3849 case lltok::kw_srem
:
3850 return error(ID
.Loc
, "srem constexprs are no longer supported");
3851 case lltok::kw_fadd
:
3852 return error(ID
.Loc
, "fadd constexprs are no longer supported");
3853 case lltok::kw_fsub
:
3854 return error(ID
.Loc
, "fsub constexprs are no longer supported");
3855 case lltok::kw_fmul
:
3856 return error(ID
.Loc
, "fmul constexprs are no longer supported");
3857 case lltok::kw_fdiv
:
3858 return error(ID
.Loc
, "fdiv constexprs are no longer supported");
3859 case lltok::kw_frem
:
3860 return error(ID
.Loc
, "frem constexprs are no longer supported");
3862 return error(ID
.Loc
, "and constexprs are no longer supported");
3864 return error(ID
.Loc
, "or constexprs are no longer supported");
3865 case lltok::kw_fneg
:
3866 return error(ID
.Loc
, "fneg constexprs are no longer supported");
3867 case lltok::kw_select
:
3868 return error(ID
.Loc
, "select constexprs are no longer supported");
3869 case lltok::kw_icmp
:
3870 case lltok::kw_fcmp
: {
3871 unsigned PredVal
, Opc
= Lex
.getUIntVal();
3872 Constant
*Val0
, *Val1
;
3874 if (parseCmpPredicate(PredVal
, Opc
) ||
3875 parseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
3876 parseGlobalTypeAndValue(Val0
) ||
3877 parseToken(lltok::comma
, "expected comma in compare constantexpr") ||
3878 parseGlobalTypeAndValue(Val1
) ||
3879 parseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
3882 if (Val0
->getType() != Val1
->getType())
3883 return error(ID
.Loc
, "compare operands must have the same type");
3885 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
3887 if (Opc
== Instruction::FCmp
) {
3888 if (!Val0
->getType()->isFPOrFPVectorTy())
3889 return error(ID
.Loc
, "fcmp requires floating point operands");
3890 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
3892 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
3893 if (!Val0
->getType()->isIntOrIntVectorTy() &&
3894 !Val0
->getType()->isPtrOrPtrVectorTy())
3895 return error(ID
.Loc
, "icmp requires pointer or integer operands");
3896 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
3898 ID
.Kind
= ValID::t_Constant
;
3902 // Binary Operators.
3907 case lltok::kw_lshr
:
3908 case lltok::kw_ashr
:
3909 case lltok::kw_xor
: {
3913 unsigned Opc
= Lex
.getUIntVal();
3914 Constant
*Val0
, *Val1
;
3916 if (Opc
== Instruction::Add
|| Opc
== Instruction::Sub
||
3917 Opc
== Instruction::Mul
|| Opc
== Instruction::Shl
) {
3918 if (EatIfPresent(lltok::kw_nuw
))
3920 if (EatIfPresent(lltok::kw_nsw
)) {
3922 if (EatIfPresent(lltok::kw_nuw
))
3925 } else if (Opc
== Instruction::SDiv
|| Opc
== Instruction::UDiv
||
3926 Opc
== Instruction::LShr
|| Opc
== Instruction::AShr
) {
3927 if (EatIfPresent(lltok::kw_exact
))
3930 if (parseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
3931 parseGlobalTypeAndValue(Val0
) ||
3932 parseToken(lltok::comma
, "expected comma in binary constantexpr") ||
3933 parseGlobalTypeAndValue(Val1
) ||
3934 parseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
3936 if (Val0
->getType() != Val1
->getType())
3937 return error(ID
.Loc
, "operands of constexpr must have same type");
3938 // Check that the type is valid for the operator.
3939 if (!Val0
->getType()->isIntOrIntVectorTy())
3940 return error(ID
.Loc
,
3941 "constexpr requires integer or integer vector operands");
3943 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3944 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3945 if (Exact
) Flags
|= PossiblyExactOperator::IsExact
;
3946 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
3947 ID
.Kind
= ValID::t_Constant
;
3951 case lltok::kw_getelementptr
:
3952 case lltok::kw_shufflevector
:
3953 case lltok::kw_insertelement
:
3954 case lltok::kw_extractelement
: {
3955 unsigned Opc
= Lex
.getUIntVal();
3956 SmallVector
<Constant
*, 16> Elts
;
3957 bool InBounds
= false;
3961 if (Opc
== Instruction::GetElementPtr
)
3962 InBounds
= EatIfPresent(lltok::kw_inbounds
);
3964 if (parseToken(lltok::lparen
, "expected '(' in constantexpr"))
3967 if (Opc
== Instruction::GetElementPtr
) {
3968 if (parseType(Ty
) ||
3969 parseToken(lltok::comma
, "expected comma after getelementptr's type"))
3973 std::optional
<unsigned> InRangeOp
;
3974 if (parseGlobalValueVector(
3975 Elts
, Opc
== Instruction::GetElementPtr
? &InRangeOp
: nullptr) ||
3976 parseToken(lltok::rparen
, "expected ')' in constantexpr"))
3979 if (Opc
== Instruction::GetElementPtr
) {
3980 if (Elts
.size() == 0 ||
3981 !Elts
[0]->getType()->isPtrOrPtrVectorTy())
3982 return error(ID
.Loc
, "base of getelementptr must be a pointer");
3984 Type
*BaseType
= Elts
[0]->getType();
3986 BaseType
->isVectorTy()
3987 ? cast
<FixedVectorType
>(BaseType
)->getNumElements()
3990 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
3991 for (Constant
*Val
: Indices
) {
3992 Type
*ValTy
= Val
->getType();
3993 if (!ValTy
->isIntOrIntVectorTy())
3994 return error(ID
.Loc
, "getelementptr index must be an integer");
3995 if (auto *ValVTy
= dyn_cast
<VectorType
>(ValTy
)) {
3996 unsigned ValNumEl
= cast
<FixedVectorType
>(ValVTy
)->getNumElements();
3997 if (GEPWidth
&& (ValNumEl
!= GEPWidth
))
4000 "getelementptr vector index has a wrong number of elements");
4001 // GEPWidth may have been unknown because the base is a scalar,
4002 // but it is known now.
4003 GEPWidth
= ValNumEl
;
4007 SmallPtrSet
<Type
*, 4> Visited
;
4008 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
4009 return error(ID
.Loc
, "base element of getelementptr must be sized");
4011 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
4012 return error(ID
.Loc
, "invalid getelementptr indices");
4015 if (*InRangeOp
== 0)
4016 return error(ID
.Loc
,
4017 "inrange keyword may not appear on pointer operand");
4021 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Ty
, Elts
[0], Indices
,
4022 InBounds
, InRangeOp
);
4023 } else if (Opc
== Instruction::ShuffleVector
) {
4024 if (Elts
.size() != 3)
4025 return error(ID
.Loc
, "expected three operands to shufflevector");
4026 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
4027 return error(ID
.Loc
, "invalid operands to shufflevector");
4028 SmallVector
<int, 16> Mask
;
4029 ShuffleVectorInst::getShuffleMask(cast
<Constant
>(Elts
[2]), Mask
);
4030 ID
.ConstantVal
= ConstantExpr::getShuffleVector(Elts
[0], Elts
[1], Mask
);
4031 } else if (Opc
== Instruction::ExtractElement
) {
4032 if (Elts
.size() != 2)
4033 return error(ID
.Loc
, "expected two operands to extractelement");
4034 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
4035 return error(ID
.Loc
, "invalid extractelement operands");
4036 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
4038 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
4039 if (Elts
.size() != 3)
4040 return error(ID
.Loc
, "expected three operands to insertelement");
4041 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
4042 return error(ID
.Loc
, "invalid insertelement operands");
4044 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
4047 ID
.Kind
= ValID::t_Constant
;
4056 /// parseGlobalValue - parse a global value with the specified type.
4057 bool LLParser::parseGlobalValue(Type
*Ty
, Constant
*&C
) {
4061 bool Parsed
= parseValID(ID
, /*PFS=*/nullptr, Ty
) ||
4062 convertValIDToValue(Ty
, ID
, V
, nullptr);
4063 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
4064 return error(ID
.Loc
, "global values must be constants");
4068 bool LLParser::parseGlobalTypeAndValue(Constant
*&V
) {
4070 return parseType(Ty
) || parseGlobalValue(Ty
, V
);
4073 bool LLParser::parseOptionalComdat(StringRef GlobalName
, Comdat
*&C
) {
4076 LocTy KwLoc
= Lex
.getLoc();
4077 if (!EatIfPresent(lltok::kw_comdat
))
4080 if (EatIfPresent(lltok::lparen
)) {
4081 if (Lex
.getKind() != lltok::ComdatVar
)
4082 return tokError("expected comdat variable");
4083 C
= getComdat(Lex
.getStrVal(), Lex
.getLoc());
4085 if (parseToken(lltok::rparen
, "expected ')' after comdat var"))
4088 if (GlobalName
.empty())
4089 return tokError("comdat cannot be unnamed");
4090 C
= getComdat(std::string(GlobalName
), KwLoc
);
4096 /// parseGlobalValueVector
4098 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
4099 bool LLParser::parseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
,
4100 std::optional
<unsigned> *InRangeOp
) {
4102 if (Lex
.getKind() == lltok::rbrace
||
4103 Lex
.getKind() == lltok::rsquare
||
4104 Lex
.getKind() == lltok::greater
||
4105 Lex
.getKind() == lltok::rparen
)
4109 if (InRangeOp
&& !*InRangeOp
&& EatIfPresent(lltok::kw_inrange
))
4110 *InRangeOp
= Elts
.size();
4113 if (parseGlobalTypeAndValue(C
))
4116 } while (EatIfPresent(lltok::comma
));
4121 bool LLParser::parseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
4122 SmallVector
<Metadata
*, 16> Elts
;
4123 if (parseMDNodeVector(Elts
))
4126 MD
= (IsDistinct
? MDTuple::getDistinct
: MDTuple::get
)(Context
, Elts
);
4133 /// ::= !DILocation(...)
4134 bool LLParser::parseMDNode(MDNode
*&N
) {
4135 if (Lex
.getKind() == lltok::MetadataVar
)
4136 return parseSpecializedMDNode(N
);
4138 return parseToken(lltok::exclaim
, "expected '!' here") || parseMDNodeTail(N
);
4141 bool LLParser::parseMDNodeTail(MDNode
*&N
) {
4143 if (Lex
.getKind() == lltok::lbrace
)
4144 return parseMDTuple(N
);
4147 return parseMDNodeID(N
);
4152 /// Structure to represent an optional metadata field.
4153 template <class FieldTy
> struct MDFieldImpl
{
4154 typedef MDFieldImpl ImplTy
;
4158 void assign(FieldTy Val
) {
4160 this->Val
= std::move(Val
);
4163 explicit MDFieldImpl(FieldTy Default
)
4164 : Val(std::move(Default
)), Seen(false) {}
4167 /// Structure to represent an optional metadata field that
4168 /// can be of either type (A or B) and encapsulates the
4169 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4170 /// to reimplement the specifics for representing each Field.
4171 template <class FieldTypeA
, class FieldTypeB
> struct MDEitherFieldImpl
{
4172 typedef MDEitherFieldImpl
<FieldTypeA
, FieldTypeB
> ImplTy
;
4183 void assign(FieldTypeA A
) {
4185 this->A
= std::move(A
);
4189 void assign(FieldTypeB B
) {
4191 this->B
= std::move(B
);
4195 explicit MDEitherFieldImpl(FieldTypeA DefaultA
, FieldTypeB DefaultB
)
4196 : A(std::move(DefaultA
)), B(std::move(DefaultB
)), Seen(false),
4197 WhatIs(IsInvalid
) {}
4200 struct MDUnsignedField
: public MDFieldImpl
<uint64_t> {
4203 MDUnsignedField(uint64_t Default
= 0, uint64_t Max
= UINT64_MAX
)
4204 : ImplTy(Default
), Max(Max
) {}
4207 struct LineField
: public MDUnsignedField
{
4208 LineField() : MDUnsignedField(0, UINT32_MAX
) {}
4211 struct ColumnField
: public MDUnsignedField
{
4212 ColumnField() : MDUnsignedField(0, UINT16_MAX
) {}
4215 struct DwarfTagField
: public MDUnsignedField
{
4216 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user
) {}
4217 DwarfTagField(dwarf::Tag DefaultTag
)
4218 : MDUnsignedField(DefaultTag
, dwarf::DW_TAG_hi_user
) {}
4221 struct DwarfMacinfoTypeField
: public MDUnsignedField
{
4222 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext
) {}
4223 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType
)
4224 : MDUnsignedField(DefaultType
, dwarf::DW_MACINFO_vendor_ext
) {}
4227 struct DwarfAttEncodingField
: public MDUnsignedField
{
4228 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user
) {}
4231 struct DwarfVirtualityField
: public MDUnsignedField
{
4232 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max
) {}
4235 struct DwarfLangField
: public MDUnsignedField
{
4236 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user
) {}
4239 struct DwarfCCField
: public MDUnsignedField
{
4240 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user
) {}
4243 struct EmissionKindField
: public MDUnsignedField
{
4244 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind
) {}
4247 struct NameTableKindField
: public MDUnsignedField
{
4248 NameTableKindField()
4251 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind
) {}
4254 struct DIFlagField
: public MDFieldImpl
<DINode::DIFlags
> {
4255 DIFlagField() : MDFieldImpl(DINode::FlagZero
) {}
4258 struct DISPFlagField
: public MDFieldImpl
<DISubprogram::DISPFlags
> {
4259 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero
) {}
4262 struct MDAPSIntField
: public MDFieldImpl
<APSInt
> {
4263 MDAPSIntField() : ImplTy(APSInt()) {}
4266 struct MDSignedField
: public MDFieldImpl
<int64_t> {
4267 int64_t Min
= INT64_MIN
;
4268 int64_t Max
= INT64_MAX
;
4270 MDSignedField(int64_t Default
= 0)
4271 : ImplTy(Default
) {}
4272 MDSignedField(int64_t Default
, int64_t Min
, int64_t Max
)
4273 : ImplTy(Default
), Min(Min
), Max(Max
) {}
4276 struct MDBoolField
: public MDFieldImpl
<bool> {
4277 MDBoolField(bool Default
= false) : ImplTy(Default
) {}
4280 struct MDField
: public MDFieldImpl
<Metadata
*> {
4283 MDField(bool AllowNull
= true) : ImplTy(nullptr), AllowNull(AllowNull
) {}
4286 struct MDStringField
: public MDFieldImpl
<MDString
*> {
4288 MDStringField(bool AllowEmpty
= true)
4289 : ImplTy(nullptr), AllowEmpty(AllowEmpty
) {}
4292 struct MDFieldList
: public MDFieldImpl
<SmallVector
<Metadata
*, 4>> {
4293 MDFieldList() : ImplTy(SmallVector
<Metadata
*, 4>()) {}
4296 struct ChecksumKindField
: public MDFieldImpl
<DIFile::ChecksumKind
> {
4297 ChecksumKindField(DIFile::ChecksumKind CSKind
) : ImplTy(CSKind
) {}
4300 struct MDSignedOrMDField
: MDEitherFieldImpl
<MDSignedField
, MDField
> {
4301 MDSignedOrMDField(int64_t Default
= 0, bool AllowNull
= true)
4302 : ImplTy(MDSignedField(Default
), MDField(AllowNull
)) {}
4304 MDSignedOrMDField(int64_t Default
, int64_t Min
, int64_t Max
,
4305 bool AllowNull
= true)
4306 : ImplTy(MDSignedField(Default
, Min
, Max
), MDField(AllowNull
)) {}
4308 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
4309 bool isMDField() const { return WhatIs
== IsTypeB
; }
4310 int64_t getMDSignedValue() const {
4311 assert(isMDSignedField() && "Wrong field type");
4314 Metadata
*getMDFieldValue() const {
4315 assert(isMDField() && "Wrong field type");
4320 } // end anonymous namespace
4325 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDAPSIntField
&Result
) {
4326 if (Lex
.getKind() != lltok::APSInt
)
4327 return tokError("expected integer");
4329 Result
.assign(Lex
.getAPSIntVal());
4335 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4336 MDUnsignedField
&Result
) {
4337 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
4338 return tokError("expected unsigned integer");
4340 auto &U
= Lex
.getAPSIntVal();
4341 if (U
.ugt(Result
.Max
))
4342 return tokError("value for '" + Name
+ "' too large, limit is " +
4344 Result
.assign(U
.getZExtValue());
4345 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4351 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, LineField
&Result
) {
4352 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4355 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, ColumnField
&Result
) {
4356 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4360 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfTagField
&Result
) {
4361 if (Lex
.getKind() == lltok::APSInt
)
4362 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4364 if (Lex
.getKind() != lltok::DwarfTag
)
4365 return tokError("expected DWARF tag");
4367 unsigned Tag
= dwarf::getTag(Lex
.getStrVal());
4368 if (Tag
== dwarf::DW_TAG_invalid
)
4369 return tokError("invalid DWARF tag" + Twine(" '") + Lex
.getStrVal() + "'");
4370 assert(Tag
<= Result
.Max
&& "Expected valid DWARF tag");
4378 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4379 DwarfMacinfoTypeField
&Result
) {
4380 if (Lex
.getKind() == lltok::APSInt
)
4381 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4383 if (Lex
.getKind() != lltok::DwarfMacinfo
)
4384 return tokError("expected DWARF macinfo type");
4386 unsigned Macinfo
= dwarf::getMacinfo(Lex
.getStrVal());
4387 if (Macinfo
== dwarf::DW_MACINFO_invalid
)
4388 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4389 Lex
.getStrVal() + "'");
4390 assert(Macinfo
<= Result
.Max
&& "Expected valid DWARF macinfo type");
4392 Result
.assign(Macinfo
);
4398 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4399 DwarfVirtualityField
&Result
) {
4400 if (Lex
.getKind() == lltok::APSInt
)
4401 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4403 if (Lex
.getKind() != lltok::DwarfVirtuality
)
4404 return tokError("expected DWARF virtuality code");
4406 unsigned Virtuality
= dwarf::getVirtuality(Lex
.getStrVal());
4407 if (Virtuality
== dwarf::DW_VIRTUALITY_invalid
)
4408 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4409 Lex
.getStrVal() + "'");
4410 assert(Virtuality
<= Result
.Max
&& "Expected valid DWARF virtuality code");
4411 Result
.assign(Virtuality
);
4417 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfLangField
&Result
) {
4418 if (Lex
.getKind() == lltok::APSInt
)
4419 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4421 if (Lex
.getKind() != lltok::DwarfLang
)
4422 return tokError("expected DWARF language");
4424 unsigned Lang
= dwarf::getLanguage(Lex
.getStrVal());
4426 return tokError("invalid DWARF language" + Twine(" '") + Lex
.getStrVal() +
4428 assert(Lang
<= Result
.Max
&& "Expected valid DWARF language");
4429 Result
.assign(Lang
);
4435 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfCCField
&Result
) {
4436 if (Lex
.getKind() == lltok::APSInt
)
4437 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4439 if (Lex
.getKind() != lltok::DwarfCC
)
4440 return tokError("expected DWARF calling convention");
4442 unsigned CC
= dwarf::getCallingConvention(Lex
.getStrVal());
4444 return tokError("invalid DWARF calling convention" + Twine(" '") +
4445 Lex
.getStrVal() + "'");
4446 assert(CC
<= Result
.Max
&& "Expected valid DWARF calling convention");
4453 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4454 EmissionKindField
&Result
) {
4455 if (Lex
.getKind() == lltok::APSInt
)
4456 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4458 if (Lex
.getKind() != lltok::EmissionKind
)
4459 return tokError("expected emission kind");
4461 auto Kind
= DICompileUnit::getEmissionKind(Lex
.getStrVal());
4463 return tokError("invalid emission kind" + Twine(" '") + Lex
.getStrVal() +
4465 assert(*Kind
<= Result
.Max
&& "Expected valid emission kind");
4466 Result
.assign(*Kind
);
4472 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4473 NameTableKindField
&Result
) {
4474 if (Lex
.getKind() == lltok::APSInt
)
4475 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4477 if (Lex
.getKind() != lltok::NameTableKind
)
4478 return tokError("expected nameTable kind");
4480 auto Kind
= DICompileUnit::getNameTableKind(Lex
.getStrVal());
4482 return tokError("invalid nameTable kind" + Twine(" '") + Lex
.getStrVal() +
4484 assert(((unsigned)*Kind
) <= Result
.Max
&& "Expected valid nameTable kind");
4485 Result
.assign((unsigned)*Kind
);
4491 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4492 DwarfAttEncodingField
&Result
) {
4493 if (Lex
.getKind() == lltok::APSInt
)
4494 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4496 if (Lex
.getKind() != lltok::DwarfAttEncoding
)
4497 return tokError("expected DWARF type attribute encoding");
4499 unsigned Encoding
= dwarf::getAttributeEncoding(Lex
.getStrVal());
4501 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4502 Lex
.getStrVal() + "'");
4503 assert(Encoding
<= Result
.Max
&& "Expected valid DWARF language");
4504 Result
.assign(Encoding
);
4511 /// ::= DIFlagVector
4512 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4514 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DIFlagField
&Result
) {
4516 // parser for a single flag.
4517 auto parseFlag
= [&](DINode::DIFlags
&Val
) {
4518 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4519 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4520 bool Res
= parseUInt32(TempVal
);
4521 Val
= static_cast<DINode::DIFlags
>(TempVal
);
4525 if (Lex
.getKind() != lltok::DIFlag
)
4526 return tokError("expected debug info flag");
4528 Val
= DINode::getFlag(Lex
.getStrVal());
4530 return tokError(Twine("invalid debug info flag '") + Lex
.getStrVal() +
4536 // parse the flags and combine them together.
4537 DINode::DIFlags Combined
= DINode::FlagZero
;
4539 DINode::DIFlags Val
;
4543 } while (EatIfPresent(lltok::bar
));
4545 Result
.assign(Combined
);
4551 /// ::= DISPFlagVector
4552 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4554 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DISPFlagField
&Result
) {
4556 // parser for a single flag.
4557 auto parseFlag
= [&](DISubprogram::DISPFlags
&Val
) {
4558 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4559 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4560 bool Res
= parseUInt32(TempVal
);
4561 Val
= static_cast<DISubprogram::DISPFlags
>(TempVal
);
4565 if (Lex
.getKind() != lltok::DISPFlag
)
4566 return tokError("expected debug info flag");
4568 Val
= DISubprogram::getFlag(Lex
.getStrVal());
4570 return tokError(Twine("invalid subprogram debug info flag '") +
4571 Lex
.getStrVal() + "'");
4576 // parse the flags and combine them together.
4577 DISubprogram::DISPFlags Combined
= DISubprogram::SPFlagZero
;
4579 DISubprogram::DISPFlags Val
;
4583 } while (EatIfPresent(lltok::bar
));
4585 Result
.assign(Combined
);
4590 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDSignedField
&Result
) {
4591 if (Lex
.getKind() != lltok::APSInt
)
4592 return tokError("expected signed integer");
4594 auto &S
= Lex
.getAPSIntVal();
4596 return tokError("value for '" + Name
+ "' too small, limit is " +
4599 return tokError("value for '" + Name
+ "' too large, limit is " +
4601 Result
.assign(S
.getExtValue());
4602 assert(Result
.Val
>= Result
.Min
&& "Expected value in range");
4603 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4609 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDBoolField
&Result
) {
4610 switch (Lex
.getKind()) {
4612 return tokError("expected 'true' or 'false'");
4613 case lltok::kw_true
:
4614 Result
.assign(true);
4616 case lltok::kw_false
:
4617 Result
.assign(false);
4625 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDField
&Result
) {
4626 if (Lex
.getKind() == lltok::kw_null
) {
4627 if (!Result
.AllowNull
)
4628 return tokError("'" + Name
+ "' cannot be null");
4630 Result
.assign(nullptr);
4635 if (parseMetadata(MD
, nullptr))
4643 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4644 MDSignedOrMDField
&Result
) {
4645 // Try to parse a signed int.
4646 if (Lex
.getKind() == lltok::APSInt
) {
4647 MDSignedField Res
= Result
.A
;
4648 if (!parseMDField(Loc
, Name
, Res
)) {
4655 // Otherwise, try to parse as an MDField.
4656 MDField Res
= Result
.B
;
4657 if (!parseMDField(Loc
, Name
, Res
)) {
4666 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDStringField
&Result
) {
4667 LocTy ValueLoc
= Lex
.getLoc();
4669 if (parseStringConstant(S
))
4672 if (!Result
.AllowEmpty
&& S
.empty())
4673 return error(ValueLoc
, "'" + Name
+ "' cannot be empty");
4675 Result
.assign(S
.empty() ? nullptr : MDString::get(Context
, S
));
4680 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDFieldList
&Result
) {
4681 SmallVector
<Metadata
*, 4> MDs
;
4682 if (parseMDNodeVector(MDs
))
4685 Result
.assign(std::move(MDs
));
4690 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4691 ChecksumKindField
&Result
) {
4692 std::optional
<DIFile::ChecksumKind
> CSKind
=
4693 DIFile::getChecksumKind(Lex
.getStrVal());
4695 if (Lex
.getKind() != lltok::ChecksumKind
|| !CSKind
)
4696 return tokError("invalid checksum kind" + Twine(" '") + Lex
.getStrVal() +
4699 Result
.assign(*CSKind
);
4704 } // end namespace llvm
4706 template <class ParserTy
>
4707 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField
) {
4709 if (Lex
.getKind() != lltok::LabelStr
)
4710 return tokError("expected field label here");
4714 } while (EatIfPresent(lltok::comma
));
4719 template <class ParserTy
>
4720 bool LLParser::parseMDFieldsImpl(ParserTy ParseField
, LocTy
&ClosingLoc
) {
4721 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4724 if (parseToken(lltok::lparen
, "expected '(' here"))
4726 if (Lex
.getKind() != lltok::rparen
)
4727 if (parseMDFieldsImplBody(ParseField
))
4730 ClosingLoc
= Lex
.getLoc();
4731 return parseToken(lltok::rparen
, "expected ')' here");
4734 template <class FieldTy
>
4735 bool LLParser::parseMDField(StringRef Name
, FieldTy
&Result
) {
4737 return tokError("field '" + Name
+ "' cannot be specified more than once");
4739 LocTy Loc
= Lex
.getLoc();
4741 return parseMDField(Loc
, Name
, Result
);
4744 bool LLParser::parseSpecializedMDNode(MDNode
*&N
, bool IsDistinct
) {
4745 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4747 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4748 if (Lex.getStrVal() == #CLASS) \
4749 return parse##CLASS(N, IsDistinct);
4750 #include "llvm/IR/Metadata.def"
4752 return tokError("expected metadata type");
4755 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4756 #define NOP_FIELD(NAME, TYPE, INIT)
4757 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4759 return error(ClosingLoc, "missing required field '" #NAME "'");
4760 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4761 if (Lex.getStrVal() == #NAME) \
4762 return parseMDField(#NAME, NAME);
4763 #define PARSE_MD_FIELDS() \
4764 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4767 if (parseMDFieldsImpl( \
4769 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4770 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4775 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4777 #define GET_OR_DISTINCT(CLASS, ARGS) \
4778 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4780 /// parseDILocationFields:
4781 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4782 /// isImplicitCode: true)
4783 bool LLParser::parseDILocation(MDNode
*&Result
, bool IsDistinct
) {
4784 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4785 OPTIONAL(line, LineField, ); \
4786 OPTIONAL(column, ColumnField, ); \
4787 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4788 OPTIONAL(inlinedAt, MDField, ); \
4789 OPTIONAL(isImplicitCode, MDBoolField, (false));
4791 #undef VISIT_MD_FIELDS
4794 GET_OR_DISTINCT(DILocation
, (Context
, line
.Val
, column
.Val
, scope
.Val
,
4795 inlinedAt
.Val
, isImplicitCode
.Val
));
4799 /// parseDIAssignID:
4800 /// ::= distinct !DIAssignID()
4801 bool LLParser::parseDIAssignID(MDNode
*&Result
, bool IsDistinct
) {
4803 return Lex
.Error("missing 'distinct', required for !DIAssignID()");
4807 // Now eat the parens.
4808 if (parseToken(lltok::lparen
, "expected '(' here"))
4810 if (parseToken(lltok::rparen
, "expected ')' here"))
4813 Result
= DIAssignID::getDistinct(Context
);
4817 /// parseGenericDINode:
4818 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4819 bool LLParser::parseGenericDINode(MDNode
*&Result
, bool IsDistinct
) {
4820 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4821 REQUIRED(tag, DwarfTagField, ); \
4822 OPTIONAL(header, MDStringField, ); \
4823 OPTIONAL(operands, MDFieldList, );
4825 #undef VISIT_MD_FIELDS
4827 Result
= GET_OR_DISTINCT(GenericDINode
,
4828 (Context
, tag
.Val
, header
.Val
, operands
.Val
));
4832 /// parseDISubrange:
4833 /// ::= !DISubrange(count: 30, lowerBound: 2)
4834 /// ::= !DISubrange(count: !node, lowerBound: 2)
4835 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4836 bool LLParser::parseDISubrange(MDNode
*&Result
, bool IsDistinct
) {
4837 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4838 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4839 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4840 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4841 OPTIONAL(stride, MDSignedOrMDField, );
4843 #undef VISIT_MD_FIELDS
4845 Metadata
*Count
= nullptr;
4846 Metadata
*LowerBound
= nullptr;
4847 Metadata
*UpperBound
= nullptr;
4848 Metadata
*Stride
= nullptr;
4850 auto convToMetadata
= [&](MDSignedOrMDField Bound
) -> Metadata
* {
4851 if (Bound
.isMDSignedField())
4852 return ConstantAsMetadata::get(ConstantInt::getSigned(
4853 Type::getInt64Ty(Context
), Bound
.getMDSignedValue()));
4854 if (Bound
.isMDField())
4855 return Bound
.getMDFieldValue();
4859 Count
= convToMetadata(count
);
4860 LowerBound
= convToMetadata(lowerBound
);
4861 UpperBound
= convToMetadata(upperBound
);
4862 Stride
= convToMetadata(stride
);
4864 Result
= GET_OR_DISTINCT(DISubrange
,
4865 (Context
, Count
, LowerBound
, UpperBound
, Stride
));
4870 /// parseDIGenericSubrange:
4871 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4873 bool LLParser::parseDIGenericSubrange(MDNode
*&Result
, bool IsDistinct
) {
4874 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4875 OPTIONAL(count, MDSignedOrMDField, ); \
4876 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4877 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4878 OPTIONAL(stride, MDSignedOrMDField, );
4880 #undef VISIT_MD_FIELDS
4882 auto ConvToMetadata
= [&](MDSignedOrMDField Bound
) -> Metadata
* {
4883 if (Bound
.isMDSignedField())
4884 return DIExpression::get(
4885 Context
, {dwarf::DW_OP_consts
,
4886 static_cast<uint64_t>(Bound
.getMDSignedValue())});
4887 if (Bound
.isMDField())
4888 return Bound
.getMDFieldValue();
4892 Metadata
*Count
= ConvToMetadata(count
);
4893 Metadata
*LowerBound
= ConvToMetadata(lowerBound
);
4894 Metadata
*UpperBound
= ConvToMetadata(upperBound
);
4895 Metadata
*Stride
= ConvToMetadata(stride
);
4897 Result
= GET_OR_DISTINCT(DIGenericSubrange
,
4898 (Context
, Count
, LowerBound
, UpperBound
, Stride
));
4903 /// parseDIEnumerator:
4904 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4905 bool LLParser::parseDIEnumerator(MDNode
*&Result
, bool IsDistinct
) {
4906 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4907 REQUIRED(name, MDStringField, ); \
4908 REQUIRED(value, MDAPSIntField, ); \
4909 OPTIONAL(isUnsigned, MDBoolField, (false));
4911 #undef VISIT_MD_FIELDS
4913 if (isUnsigned
.Val
&& value
.Val
.isNegative())
4914 return tokError("unsigned enumerator with negative value");
4916 APSInt
Value(value
.Val
);
4917 // Add a leading zero so that unsigned values with the msb set are not
4918 // mistaken for negative values when used for signed enumerators.
4919 if (!isUnsigned
.Val
&& value
.Val
.isUnsigned() && value
.Val
.isSignBitSet())
4920 Value
= Value
.zext(Value
.getBitWidth() + 1);
4923 GET_OR_DISTINCT(DIEnumerator
, (Context
, Value
, isUnsigned
.Val
, name
.Val
));
4928 /// parseDIBasicType:
4929 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4930 /// encoding: DW_ATE_encoding, flags: 0)
4931 bool LLParser::parseDIBasicType(MDNode
*&Result
, bool IsDistinct
) {
4932 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4933 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4934 OPTIONAL(name, MDStringField, ); \
4935 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4936 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4937 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4938 OPTIONAL(flags, DIFlagField, );
4940 #undef VISIT_MD_FIELDS
4942 Result
= GET_OR_DISTINCT(DIBasicType
, (Context
, tag
.Val
, name
.Val
, size
.Val
,
4943 align
.Val
, encoding
.Val
, flags
.Val
));
4947 /// parseDIStringType:
4948 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4949 bool LLParser::parseDIStringType(MDNode
*&Result
, bool IsDistinct
) {
4950 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4951 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4952 OPTIONAL(name, MDStringField, ); \
4953 OPTIONAL(stringLength, MDField, ); \
4954 OPTIONAL(stringLengthExpression, MDField, ); \
4955 OPTIONAL(stringLocationExpression, MDField, ); \
4956 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4957 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4958 OPTIONAL(encoding, DwarfAttEncodingField, );
4960 #undef VISIT_MD_FIELDS
4962 Result
= GET_OR_DISTINCT(
4964 (Context
, tag
.Val
, name
.Val
, stringLength
.Val
, stringLengthExpression
.Val
,
4965 stringLocationExpression
.Val
, size
.Val
, align
.Val
, encoding
.Val
));
4969 /// parseDIDerivedType:
4970 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4971 /// line: 7, scope: !1, baseType: !2, size: 32,
4972 /// align: 32, offset: 0, flags: 0, extraData: !3,
4973 /// dwarfAddressSpace: 3)
4974 bool LLParser::parseDIDerivedType(MDNode
*&Result
, bool IsDistinct
) {
4975 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4976 REQUIRED(tag, DwarfTagField, ); \
4977 OPTIONAL(name, MDStringField, ); \
4978 OPTIONAL(file, MDField, ); \
4979 OPTIONAL(line, LineField, ); \
4980 OPTIONAL(scope, MDField, ); \
4981 REQUIRED(baseType, MDField, ); \
4982 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4983 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4984 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4985 OPTIONAL(flags, DIFlagField, ); \
4986 OPTIONAL(extraData, MDField, ); \
4987 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
4988 OPTIONAL(annotations, MDField, );
4990 #undef VISIT_MD_FIELDS
4992 std::optional
<unsigned> DWARFAddressSpace
;
4993 if (dwarfAddressSpace
.Val
!= UINT32_MAX
)
4994 DWARFAddressSpace
= dwarfAddressSpace
.Val
;
4996 Result
= GET_OR_DISTINCT(DIDerivedType
,
4997 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4998 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
,
4999 offset
.Val
, DWARFAddressSpace
, flags
.Val
,
5000 extraData
.Val
, annotations
.Val
));
5004 bool LLParser::parseDICompositeType(MDNode
*&Result
, bool IsDistinct
) {
5005 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5006 REQUIRED(tag, DwarfTagField, ); \
5007 OPTIONAL(name, MDStringField, ); \
5008 OPTIONAL(file, MDField, ); \
5009 OPTIONAL(line, LineField, ); \
5010 OPTIONAL(scope, MDField, ); \
5011 OPTIONAL(baseType, MDField, ); \
5012 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5013 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5014 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5015 OPTIONAL(flags, DIFlagField, ); \
5016 OPTIONAL(elements, MDField, ); \
5017 OPTIONAL(runtimeLang, DwarfLangField, ); \
5018 OPTIONAL(vtableHolder, MDField, ); \
5019 OPTIONAL(templateParams, MDField, ); \
5020 OPTIONAL(identifier, MDStringField, ); \
5021 OPTIONAL(discriminator, MDField, ); \
5022 OPTIONAL(dataLocation, MDField, ); \
5023 OPTIONAL(associated, MDField, ); \
5024 OPTIONAL(allocated, MDField, ); \
5025 OPTIONAL(rank, MDSignedOrMDField, ); \
5026 OPTIONAL(annotations, MDField, );
5028 #undef VISIT_MD_FIELDS
5030 Metadata
*Rank
= nullptr;
5031 if (rank
.isMDSignedField())
5032 Rank
= ConstantAsMetadata::get(ConstantInt::getSigned(
5033 Type::getInt64Ty(Context
), rank
.getMDSignedValue()));
5034 else if (rank
.isMDField())
5035 Rank
= rank
.getMDFieldValue();
5037 // If this has an identifier try to build an ODR type.
5039 if (auto *CT
= DICompositeType::buildODRType(
5040 Context
, *identifier
.Val
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
5041 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
, offset
.Val
, flags
.Val
,
5042 elements
.Val
, runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
,
5043 discriminator
.Val
, dataLocation
.Val
, associated
.Val
, allocated
.Val
,
5044 Rank
, annotations
.Val
)) {
5049 // Create a new node, and save it in the context if it belongs in the type
5051 Result
= GET_OR_DISTINCT(
5053 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
, scope
.Val
, baseType
.Val
,
5054 size
.Val
, align
.Val
, offset
.Val
, flags
.Val
, elements
.Val
,
5055 runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
, identifier
.Val
,
5056 discriminator
.Val
, dataLocation
.Val
, associated
.Val
, allocated
.Val
, Rank
,
5061 bool LLParser::parseDISubroutineType(MDNode
*&Result
, bool IsDistinct
) {
5062 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5063 OPTIONAL(flags, DIFlagField, ); \
5064 OPTIONAL(cc, DwarfCCField, ); \
5065 REQUIRED(types, MDField, );
5067 #undef VISIT_MD_FIELDS
5069 Result
= GET_OR_DISTINCT(DISubroutineType
,
5070 (Context
, flags
.Val
, cc
.Val
, types
.Val
));
5074 /// parseDIFileType:
5075 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5076 /// checksumkind: CSK_MD5,
5077 /// checksum: "000102030405060708090a0b0c0d0e0f",
5078 /// source: "source file contents")
5079 bool LLParser::parseDIFile(MDNode
*&Result
, bool IsDistinct
) {
5080 // The default constructed value for checksumkind is required, but will never
5081 // be used, as the parser checks if the field was actually Seen before using
5083 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5084 REQUIRED(filename, MDStringField, ); \
5085 REQUIRED(directory, MDStringField, ); \
5086 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5087 OPTIONAL(checksum, MDStringField, ); \
5088 OPTIONAL(source, MDStringField, );
5090 #undef VISIT_MD_FIELDS
5092 std::optional
<DIFile::ChecksumInfo
<MDString
*>> OptChecksum
;
5093 if (checksumkind
.Seen
&& checksum
.Seen
)
5094 OptChecksum
.emplace(checksumkind
.Val
, checksum
.Val
);
5095 else if (checksumkind
.Seen
|| checksum
.Seen
)
5096 return Lex
.Error("'checksumkind' and 'checksum' must be provided together");
5098 MDString
*Source
= nullptr;
5100 Source
= source
.Val
;
5101 Result
= GET_OR_DISTINCT(
5102 DIFile
, (Context
, filename
.Val
, directory
.Val
, OptChecksum
, Source
));
5106 /// parseDICompileUnit:
5107 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5108 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5109 /// splitDebugFilename: "abc.debug",
5110 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5111 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5112 /// sysroot: "/", sdk: "MacOSX.sdk")
5113 bool LLParser::parseDICompileUnit(MDNode
*&Result
, bool IsDistinct
) {
5115 return Lex
.Error("missing 'distinct', required for !DICompileUnit");
5117 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5118 REQUIRED(language, DwarfLangField, ); \
5119 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5120 OPTIONAL(producer, MDStringField, ); \
5121 OPTIONAL(isOptimized, MDBoolField, ); \
5122 OPTIONAL(flags, MDStringField, ); \
5123 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5124 OPTIONAL(splitDebugFilename, MDStringField, ); \
5125 OPTIONAL(emissionKind, EmissionKindField, ); \
5126 OPTIONAL(enums, MDField, ); \
5127 OPTIONAL(retainedTypes, MDField, ); \
5128 OPTIONAL(globals, MDField, ); \
5129 OPTIONAL(imports, MDField, ); \
5130 OPTIONAL(macros, MDField, ); \
5131 OPTIONAL(dwoId, MDUnsignedField, ); \
5132 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5133 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5134 OPTIONAL(nameTableKind, NameTableKindField, ); \
5135 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5136 OPTIONAL(sysroot, MDStringField, ); \
5137 OPTIONAL(sdk, MDStringField, );
5139 #undef VISIT_MD_FIELDS
5141 Result
= DICompileUnit::getDistinct(
5142 Context
, language
.Val
, file
.Val
, producer
.Val
, isOptimized
.Val
, flags
.Val
,
5143 runtimeVersion
.Val
, splitDebugFilename
.Val
, emissionKind
.Val
, enums
.Val
,
5144 retainedTypes
.Val
, globals
.Val
, imports
.Val
, macros
.Val
, dwoId
.Val
,
5145 splitDebugInlining
.Val
, debugInfoForProfiling
.Val
, nameTableKind
.Val
,
5146 rangesBaseAddress
.Val
, sysroot
.Val
, sdk
.Val
);
5150 /// parseDISubprogram:
5151 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5152 /// file: !1, line: 7, type: !2, isLocal: false,
5153 /// isDefinition: true, scopeLine: 8, containingType: !3,
5154 /// virtuality: DW_VIRTUALTIY_pure_virtual,
5155 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5156 /// spFlags: 10, isOptimized: false, templateParams: !4,
5157 /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5158 /// annotations: !8)
5159 bool LLParser::parseDISubprogram(MDNode
*&Result
, bool IsDistinct
) {
5160 auto Loc
= Lex
.getLoc();
5161 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5162 OPTIONAL(scope, MDField, ); \
5163 OPTIONAL(name, MDStringField, ); \
5164 OPTIONAL(linkageName, MDStringField, ); \
5165 OPTIONAL(file, MDField, ); \
5166 OPTIONAL(line, LineField, ); \
5167 OPTIONAL(type, MDField, ); \
5168 OPTIONAL(isLocal, MDBoolField, ); \
5169 OPTIONAL(isDefinition, MDBoolField, (true)); \
5170 OPTIONAL(scopeLine, LineField, ); \
5171 OPTIONAL(containingType, MDField, ); \
5172 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5173 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5174 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5175 OPTIONAL(flags, DIFlagField, ); \
5176 OPTIONAL(spFlags, DISPFlagField, ); \
5177 OPTIONAL(isOptimized, MDBoolField, ); \
5178 OPTIONAL(unit, MDField, ); \
5179 OPTIONAL(templateParams, MDField, ); \
5180 OPTIONAL(declaration, MDField, ); \
5181 OPTIONAL(retainedNodes, MDField, ); \
5182 OPTIONAL(thrownTypes, MDField, ); \
5183 OPTIONAL(annotations, MDField, ); \
5184 OPTIONAL(targetFuncName, MDStringField, );
5186 #undef VISIT_MD_FIELDS
5188 // An explicit spFlags field takes precedence over individual fields in
5189 // older IR versions.
5190 DISubprogram::DISPFlags SPFlags
=
5191 spFlags
.Seen
? spFlags
.Val
5192 : DISubprogram::toSPFlags(isLocal
.Val
, isDefinition
.Val
,
5193 isOptimized
.Val
, virtuality
.Val
);
5194 if ((SPFlags
& DISubprogram::SPFlagDefinition
) && !IsDistinct
)
5197 "missing 'distinct', required for !DISubprogram that is a Definition");
5198 Result
= GET_OR_DISTINCT(
5200 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
, line
.Val
,
5201 type
.Val
, scopeLine
.Val
, containingType
.Val
, virtualIndex
.Val
,
5202 thisAdjustment
.Val
, flags
.Val
, SPFlags
, unit
.Val
, templateParams
.Val
,
5203 declaration
.Val
, retainedNodes
.Val
, thrownTypes
.Val
, annotations
.Val
,
5204 targetFuncName
.Val
));
5208 /// parseDILexicalBlock:
5209 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5210 bool LLParser::parseDILexicalBlock(MDNode
*&Result
, bool IsDistinct
) {
5211 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5212 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5213 OPTIONAL(file, MDField, ); \
5214 OPTIONAL(line, LineField, ); \
5215 OPTIONAL(column, ColumnField, );
5217 #undef VISIT_MD_FIELDS
5219 Result
= GET_OR_DISTINCT(
5220 DILexicalBlock
, (Context
, scope
.Val
, file
.Val
, line
.Val
, column
.Val
));
5224 /// parseDILexicalBlockFile:
5225 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5226 bool LLParser::parseDILexicalBlockFile(MDNode
*&Result
, bool IsDistinct
) {
5227 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5228 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5229 OPTIONAL(file, MDField, ); \
5230 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5232 #undef VISIT_MD_FIELDS
5234 Result
= GET_OR_DISTINCT(DILexicalBlockFile
,
5235 (Context
, scope
.Val
, file
.Val
, discriminator
.Val
));
5239 /// parseDICommonBlock:
5240 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5241 bool LLParser::parseDICommonBlock(MDNode
*&Result
, bool IsDistinct
) {
5242 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5243 REQUIRED(scope, MDField, ); \
5244 OPTIONAL(declaration, MDField, ); \
5245 OPTIONAL(name, MDStringField, ); \
5246 OPTIONAL(file, MDField, ); \
5247 OPTIONAL(line, LineField, );
5249 #undef VISIT_MD_FIELDS
5251 Result
= GET_OR_DISTINCT(DICommonBlock
,
5252 (Context
, scope
.Val
, declaration
.Val
, name
.Val
,
5253 file
.Val
, line
.Val
));
5257 /// parseDINamespace:
5258 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5259 bool LLParser::parseDINamespace(MDNode
*&Result
, bool IsDistinct
) {
5260 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5261 REQUIRED(scope, MDField, ); \
5262 OPTIONAL(name, MDStringField, ); \
5263 OPTIONAL(exportSymbols, MDBoolField, );
5265 #undef VISIT_MD_FIELDS
5267 Result
= GET_OR_DISTINCT(DINamespace
,
5268 (Context
, scope
.Val
, name
.Val
, exportSymbols
.Val
));
5273 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5275 bool LLParser::parseDIMacro(MDNode
*&Result
, bool IsDistinct
) {
5276 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5277 REQUIRED(type, DwarfMacinfoTypeField, ); \
5278 OPTIONAL(line, LineField, ); \
5279 REQUIRED(name, MDStringField, ); \
5280 OPTIONAL(value, MDStringField, );
5282 #undef VISIT_MD_FIELDS
5284 Result
= GET_OR_DISTINCT(DIMacro
,
5285 (Context
, type
.Val
, line
.Val
, name
.Val
, value
.Val
));
5289 /// parseDIMacroFile:
5290 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5291 bool LLParser::parseDIMacroFile(MDNode
*&Result
, bool IsDistinct
) {
5292 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5293 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5294 OPTIONAL(line, LineField, ); \
5295 REQUIRED(file, MDField, ); \
5296 OPTIONAL(nodes, MDField, );
5298 #undef VISIT_MD_FIELDS
5300 Result
= GET_OR_DISTINCT(DIMacroFile
,
5301 (Context
, type
.Val
, line
.Val
, file
.Val
, nodes
.Val
));
5306 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5307 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5308 /// file: !1, line: 4, isDecl: false)
5309 bool LLParser::parseDIModule(MDNode
*&Result
, bool IsDistinct
) {
5310 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5311 REQUIRED(scope, MDField, ); \
5312 REQUIRED(name, MDStringField, ); \
5313 OPTIONAL(configMacros, MDStringField, ); \
5314 OPTIONAL(includePath, MDStringField, ); \
5315 OPTIONAL(apinotes, MDStringField, ); \
5316 OPTIONAL(file, MDField, ); \
5317 OPTIONAL(line, LineField, ); \
5318 OPTIONAL(isDecl, MDBoolField, );
5320 #undef VISIT_MD_FIELDS
5322 Result
= GET_OR_DISTINCT(DIModule
, (Context
, file
.Val
, scope
.Val
, name
.Val
,
5323 configMacros
.Val
, includePath
.Val
,
5324 apinotes
.Val
, line
.Val
, isDecl
.Val
));
5328 /// parseDITemplateTypeParameter:
5329 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5330 bool LLParser::parseDITemplateTypeParameter(MDNode
*&Result
, bool IsDistinct
) {
5331 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5332 OPTIONAL(name, MDStringField, ); \
5333 REQUIRED(type, MDField, ); \
5334 OPTIONAL(defaulted, MDBoolField, );
5336 #undef VISIT_MD_FIELDS
5338 Result
= GET_OR_DISTINCT(DITemplateTypeParameter
,
5339 (Context
, name
.Val
, type
.Val
, defaulted
.Val
));
5343 /// parseDITemplateValueParameter:
5344 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5345 /// name: "V", type: !1, defaulted: false,
5347 bool LLParser::parseDITemplateValueParameter(MDNode
*&Result
, bool IsDistinct
) {
5348 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5349 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5350 OPTIONAL(name, MDStringField, ); \
5351 OPTIONAL(type, MDField, ); \
5352 OPTIONAL(defaulted, MDBoolField, ); \
5353 REQUIRED(value, MDField, );
5356 #undef VISIT_MD_FIELDS
5358 Result
= GET_OR_DISTINCT(
5359 DITemplateValueParameter
,
5360 (Context
, tag
.Val
, name
.Val
, type
.Val
, defaulted
.Val
, value
.Val
));
5364 /// parseDIGlobalVariable:
5365 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5366 /// file: !1, line: 7, type: !2, isLocal: false,
5367 /// isDefinition: true, templateParams: !3,
5368 /// declaration: !4, align: 8)
5369 bool LLParser::parseDIGlobalVariable(MDNode
*&Result
, bool IsDistinct
) {
5370 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5371 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5372 OPTIONAL(scope, MDField, ); \
5373 OPTIONAL(linkageName, MDStringField, ); \
5374 OPTIONAL(file, MDField, ); \
5375 OPTIONAL(line, LineField, ); \
5376 OPTIONAL(type, MDField, ); \
5377 OPTIONAL(isLocal, MDBoolField, ); \
5378 OPTIONAL(isDefinition, MDBoolField, (true)); \
5379 OPTIONAL(templateParams, MDField, ); \
5380 OPTIONAL(declaration, MDField, ); \
5381 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5382 OPTIONAL(annotations, MDField, );
5384 #undef VISIT_MD_FIELDS
5387 GET_OR_DISTINCT(DIGlobalVariable
,
5388 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
,
5389 line
.Val
, type
.Val
, isLocal
.Val
, isDefinition
.Val
,
5390 declaration
.Val
, templateParams
.Val
, align
.Val
,
5395 /// parseDILocalVariable:
5396 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5397 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5399 /// ::= !DILocalVariable(scope: !0, name: "foo",
5400 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5402 bool LLParser::parseDILocalVariable(MDNode
*&Result
, bool IsDistinct
) {
5403 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5404 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5405 OPTIONAL(name, MDStringField, ); \
5406 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5407 OPTIONAL(file, MDField, ); \
5408 OPTIONAL(line, LineField, ); \
5409 OPTIONAL(type, MDField, ); \
5410 OPTIONAL(flags, DIFlagField, ); \
5411 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5412 OPTIONAL(annotations, MDField, );
5414 #undef VISIT_MD_FIELDS
5416 Result
= GET_OR_DISTINCT(DILocalVariable
,
5417 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
,
5418 type
.Val
, arg
.Val
, flags
.Val
, align
.Val
,
5424 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5425 bool LLParser::parseDILabel(MDNode
*&Result
, bool IsDistinct
) {
5426 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5427 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5428 REQUIRED(name, MDStringField, ); \
5429 REQUIRED(file, MDField, ); \
5430 REQUIRED(line, LineField, );
5432 #undef VISIT_MD_FIELDS
5434 Result
= GET_OR_DISTINCT(DILabel
,
5435 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
));
5439 /// parseDIExpression:
5440 /// ::= !DIExpression(0, 7, -1)
5441 bool LLParser::parseDIExpression(MDNode
*&Result
, bool IsDistinct
) {
5442 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
5445 if (parseToken(lltok::lparen
, "expected '(' here"))
5448 SmallVector
<uint64_t, 8> Elements
;
5449 if (Lex
.getKind() != lltok::rparen
)
5451 if (Lex
.getKind() == lltok::DwarfOp
) {
5452 if (unsigned Op
= dwarf::getOperationEncoding(Lex
.getStrVal())) {
5454 Elements
.push_back(Op
);
5457 return tokError(Twine("invalid DWARF op '") + Lex
.getStrVal() + "'");
5460 if (Lex
.getKind() == lltok::DwarfAttEncoding
) {
5461 if (unsigned Op
= dwarf::getAttributeEncoding(Lex
.getStrVal())) {
5463 Elements
.push_back(Op
);
5466 return tokError(Twine("invalid DWARF attribute encoding '") +
5467 Lex
.getStrVal() + "'");
5470 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
5471 return tokError("expected unsigned integer");
5473 auto &U
= Lex
.getAPSIntVal();
5474 if (U
.ugt(UINT64_MAX
))
5475 return tokError("element too large, limit is " + Twine(UINT64_MAX
));
5476 Elements
.push_back(U
.getZExtValue());
5478 } while (EatIfPresent(lltok::comma
));
5480 if (parseToken(lltok::rparen
, "expected ')' here"))
5483 Result
= GET_OR_DISTINCT(DIExpression
, (Context
, Elements
));
5487 bool LLParser::parseDIArgList(MDNode
*&Result
, bool IsDistinct
) {
5488 return parseDIArgList(Result
, IsDistinct
, nullptr);
5491 /// ::= !DIArgList(i32 7, i64 %0)
5492 bool LLParser::parseDIArgList(MDNode
*&Result
, bool IsDistinct
,
5493 PerFunctionState
*PFS
) {
5494 assert(PFS
&& "Expected valid function state");
5495 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
5498 if (parseToken(lltok::lparen
, "expected '(' here"))
5501 SmallVector
<ValueAsMetadata
*, 4> Args
;
5502 if (Lex
.getKind() != lltok::rparen
)
5505 if (parseValueAsMetadata(MD
, "expected value-as-metadata operand", PFS
))
5507 Args
.push_back(dyn_cast
<ValueAsMetadata
>(MD
));
5508 } while (EatIfPresent(lltok::comma
));
5510 if (parseToken(lltok::rparen
, "expected ')' here"))
5513 Result
= GET_OR_DISTINCT(DIArgList
, (Context
, Args
));
5517 /// parseDIGlobalVariableExpression:
5518 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5519 bool LLParser::parseDIGlobalVariableExpression(MDNode
*&Result
,
5521 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5522 REQUIRED(var, MDField, ); \
5523 REQUIRED(expr, MDField, );
5525 #undef VISIT_MD_FIELDS
5528 GET_OR_DISTINCT(DIGlobalVariableExpression
, (Context
, var
.Val
, expr
.Val
));
5532 /// parseDIObjCProperty:
5533 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5534 /// getter: "getFoo", attributes: 7, type: !2)
5535 bool LLParser::parseDIObjCProperty(MDNode
*&Result
, bool IsDistinct
) {
5536 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5537 OPTIONAL(name, MDStringField, ); \
5538 OPTIONAL(file, MDField, ); \
5539 OPTIONAL(line, LineField, ); \
5540 OPTIONAL(setter, MDStringField, ); \
5541 OPTIONAL(getter, MDStringField, ); \
5542 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5543 OPTIONAL(type, MDField, );
5545 #undef VISIT_MD_FIELDS
5547 Result
= GET_OR_DISTINCT(DIObjCProperty
,
5548 (Context
, name
.Val
, file
.Val
, line
.Val
, setter
.Val
,
5549 getter
.Val
, attributes
.Val
, type
.Val
));
5553 /// parseDIImportedEntity:
5554 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5555 /// line: 7, name: "foo", elements: !2)
5556 bool LLParser::parseDIImportedEntity(MDNode
*&Result
, bool IsDistinct
) {
5557 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5558 REQUIRED(tag, DwarfTagField, ); \
5559 REQUIRED(scope, MDField, ); \
5560 OPTIONAL(entity, MDField, ); \
5561 OPTIONAL(file, MDField, ); \
5562 OPTIONAL(line, LineField, ); \
5563 OPTIONAL(name, MDStringField, ); \
5564 OPTIONAL(elements, MDField, );
5566 #undef VISIT_MD_FIELDS
5568 Result
= GET_OR_DISTINCT(DIImportedEntity
,
5569 (Context
, tag
.Val
, scope
.Val
, entity
.Val
, file
.Val
,
5570 line
.Val
, name
.Val
, elements
.Val
));
5574 #undef PARSE_MD_FIELD
5576 #undef REQUIRE_FIELD
5577 #undef DECLARE_FIELD
5579 /// parseMetadataAsValue
5580 /// ::= metadata i32 %local
5581 /// ::= metadata i32 @global
5582 /// ::= metadata i32 7
5584 /// ::= metadata !{...}
5585 /// ::= metadata !"string"
5586 bool LLParser::parseMetadataAsValue(Value
*&V
, PerFunctionState
&PFS
) {
5587 // Note: the type 'metadata' has already been parsed.
5589 if (parseMetadata(MD
, &PFS
))
5592 V
= MetadataAsValue::get(Context
, MD
);
5596 /// parseValueAsMetadata
5600 bool LLParser::parseValueAsMetadata(Metadata
*&MD
, const Twine
&TypeMsg
,
5601 PerFunctionState
*PFS
) {
5604 if (parseType(Ty
, TypeMsg
, Loc
))
5606 if (Ty
->isMetadataTy())
5607 return error(Loc
, "invalid metadata-value-metadata roundtrip");
5610 if (parseValue(Ty
, V
, PFS
))
5613 MD
= ValueAsMetadata::get(V
);
5624 /// ::= !DILocation(...)
5625 bool LLParser::parseMetadata(Metadata
*&MD
, PerFunctionState
*PFS
) {
5626 if (Lex
.getKind() == lltok::MetadataVar
) {
5628 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5629 // so parsing this requires a Function State.
5630 if (Lex
.getStrVal() == "DIArgList") {
5631 if (parseDIArgList(N
, false, PFS
))
5633 } else if (parseSpecializedMDNode(N
)) {
5642 if (Lex
.getKind() != lltok::exclaim
)
5643 return parseValueAsMetadata(MD
, "expected metadata operand", PFS
);
5646 assert(Lex
.getKind() == lltok::exclaim
&& "Expected '!' here");
5650 // ::= '!' STRINGCONSTANT
5651 if (Lex
.getKind() == lltok::StringConstant
) {
5653 if (parseMDString(S
))
5663 if (parseMDNodeTail(N
))
5669 //===----------------------------------------------------------------------===//
5670 // Function Parsing.
5671 //===----------------------------------------------------------------------===//
5673 bool LLParser::convertValIDToValue(Type
*Ty
, ValID
&ID
, Value
*&V
,
5674 PerFunctionState
*PFS
) {
5675 if (Ty
->isFunctionTy())
5676 return error(ID
.Loc
, "functions are not values, refer to them as pointers");
5679 case ValID::t_LocalID
:
5681 return error(ID
.Loc
, "invalid use of function-local name");
5682 V
= PFS
->getVal(ID
.UIntVal
, Ty
, ID
.Loc
);
5683 return V
== nullptr;
5684 case ValID::t_LocalName
:
5686 return error(ID
.Loc
, "invalid use of function-local name");
5687 V
= PFS
->getVal(ID
.StrVal
, Ty
, ID
.Loc
);
5688 return V
== nullptr;
5689 case ValID::t_InlineAsm
: {
5691 return error(ID
.Loc
, "invalid type for inline asm constraint string");
5692 if (Error Err
= InlineAsm::verify(ID
.FTy
, ID
.StrVal2
))
5693 return error(ID
.Loc
, toString(std::move(Err
)));
5695 ID
.FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
& 1, (ID
.UIntVal
>> 1) & 1,
5696 InlineAsm::AsmDialect((ID
.UIntVal
>> 2) & 1), (ID
.UIntVal
>> 3) & 1);
5699 case ValID::t_GlobalName
:
5700 V
= getGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
);
5702 V
= NoCFIValue::get(cast
<GlobalValue
>(V
));
5703 return V
== nullptr;
5704 case ValID::t_GlobalID
:
5705 V
= getGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
);
5707 V
= NoCFIValue::get(cast
<GlobalValue
>(V
));
5708 return V
== nullptr;
5709 case ValID::t_APSInt
:
5710 if (!Ty
->isIntegerTy())
5711 return error(ID
.Loc
, "integer constant must have integer type");
5712 ID
.APSIntVal
= ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
5713 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
5715 case ValID::t_APFloat
:
5716 if (!Ty
->isFloatingPointTy() ||
5717 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
5718 return error(ID
.Loc
, "floating point constant invalid for type");
5720 // The lexer has no type info, so builds all half, bfloat, float, and double
5721 // FP constants as double. Fix this here. Long double does not need this.
5722 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble()) {
5723 // Check for signaling before potentially converting and losing that info.
5724 bool IsSNAN
= ID
.APFloatVal
.isSignaling();
5727 ID
.APFloatVal
.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven
,
5729 else if (Ty
->isBFloatTy())
5730 ID
.APFloatVal
.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven
,
5732 else if (Ty
->isFloatTy())
5733 ID
.APFloatVal
.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven
,
5736 // The convert call above may quiet an SNaN, so manufacture another
5737 // SNaN. The bitcast works because the payload (significand) parameter
5738 // is truncated to fit.
5739 APInt Payload
= ID
.APFloatVal
.bitcastToAPInt();
5740 ID
.APFloatVal
= APFloat::getSNaN(ID
.APFloatVal
.getSemantics(),
5741 ID
.APFloatVal
.isNegative(), &Payload
);
5744 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
5746 if (V
->getType() != Ty
)
5747 return error(ID
.Loc
, "floating point constant does not have type '" +
5748 getTypeString(Ty
) + "'");
5752 if (!Ty
->isPointerTy())
5753 return error(ID
.Loc
, "null must be a pointer type");
5754 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
5756 case ValID::t_Undef
:
5757 // FIXME: LabelTy should not be a first-class type.
5758 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5759 return error(ID
.Loc
, "invalid type for undef constant");
5760 V
= UndefValue::get(Ty
);
5762 case ValID::t_EmptyArray
:
5763 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
5764 return error(ID
.Loc
, "invalid empty array initializer");
5765 V
= UndefValue::get(Ty
);
5768 // FIXME: LabelTy should not be a first-class type.
5769 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5770 return error(ID
.Loc
, "invalid type for null constant");
5771 if (auto *TETy
= dyn_cast
<TargetExtType
>(Ty
))
5772 if (!TETy
->hasProperty(TargetExtType::HasZeroInit
))
5773 return error(ID
.Loc
, "invalid type for null constant");
5774 V
= Constant::getNullValue(Ty
);
5777 if (!Ty
->isTokenTy())
5778 return error(ID
.Loc
, "invalid type for none constant");
5779 V
= Constant::getNullValue(Ty
);
5781 case ValID::t_Poison
:
5782 // FIXME: LabelTy should not be a first-class type.
5783 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5784 return error(ID
.Loc
, "invalid type for poison constant");
5785 V
= PoisonValue::get(Ty
);
5787 case ValID::t_Constant
:
5788 if (ID
.ConstantVal
->getType() != Ty
)
5789 return error(ID
.Loc
, "constant expression type mismatch: got type '" +
5790 getTypeString(ID
.ConstantVal
->getType()) +
5791 "' but expected '" + getTypeString(Ty
) + "'");
5794 case ValID::t_ConstantStruct
:
5795 case ValID::t_PackedConstantStruct
:
5796 if (StructType
*ST
= dyn_cast
<StructType
>(Ty
)) {
5797 if (ST
->getNumElements() != ID
.UIntVal
)
5798 return error(ID
.Loc
,
5799 "initializer with struct type has wrong # elements");
5800 if (ST
->isPacked() != (ID
.Kind
== ValID::t_PackedConstantStruct
))
5801 return error(ID
.Loc
, "packed'ness of initializer and type don't match");
5803 // Verify that the elements are compatible with the structtype.
5804 for (unsigned i
= 0, e
= ID
.UIntVal
; i
!= e
; ++i
)
5805 if (ID
.ConstantStructElts
[i
]->getType() != ST
->getElementType(i
))
5808 "element " + Twine(i
) +
5809 " of struct initializer doesn't match struct element type");
5811 V
= ConstantStruct::get(
5812 ST
, ArrayRef(ID
.ConstantStructElts
.get(), ID
.UIntVal
));
5814 return error(ID
.Loc
, "constant expression type mismatch");
5817 llvm_unreachable("Invalid ValID");
5820 bool LLParser::parseConstantValue(Type
*Ty
, Constant
*&C
) {
5823 auto Loc
= Lex
.getLoc();
5824 if (parseValID(ID
, /*PFS=*/nullptr))
5827 case ValID::t_APSInt
:
5828 case ValID::t_APFloat
:
5829 case ValID::t_Undef
:
5830 case ValID::t_Constant
:
5831 case ValID::t_ConstantStruct
:
5832 case ValID::t_PackedConstantStruct
: {
5834 if (convertValIDToValue(Ty
, ID
, V
, /*PFS=*/nullptr))
5836 assert(isa
<Constant
>(V
) && "Expected a constant value");
5837 C
= cast
<Constant
>(V
);
5841 C
= Constant::getNullValue(Ty
);
5844 return error(Loc
, "expected a constant value");
5848 bool LLParser::parseValue(Type
*Ty
, Value
*&V
, PerFunctionState
*PFS
) {
5851 return parseValID(ID
, PFS
, Ty
) ||
5852 convertValIDToValue(Ty
, ID
, V
, PFS
);
5855 bool LLParser::parseTypeAndValue(Value
*&V
, PerFunctionState
*PFS
) {
5857 return parseType(Ty
) || parseValue(Ty
, V
, PFS
);
5860 bool LLParser::parseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
5861 PerFunctionState
&PFS
) {
5864 if (parseTypeAndValue(V
, PFS
))
5866 if (!isa
<BasicBlock
>(V
))
5867 return error(Loc
, "expected a basic block");
5868 BB
= cast
<BasicBlock
>(V
);
5873 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5874 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5875 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5876 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5877 bool LLParser::parseFunctionHeader(Function
*&Fn
, bool IsDefine
) {
5878 // parse the linkage.
5879 LocTy LinkageLoc
= Lex
.getLoc();
5881 unsigned Visibility
;
5882 unsigned DLLStorageClass
;
5884 AttrBuilder
RetAttrs(M
->getContext());
5887 Type
*RetType
= nullptr;
5888 LocTy RetTypeLoc
= Lex
.getLoc();
5889 if (parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
5891 parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
5892 parseType(RetType
, RetTypeLoc
, true /*void allowed*/))
5895 // Verify that the linkage is ok.
5896 switch ((GlobalValue::LinkageTypes
)Linkage
) {
5897 case GlobalValue::ExternalLinkage
:
5898 break; // always ok.
5899 case GlobalValue::ExternalWeakLinkage
:
5901 return error(LinkageLoc
, "invalid linkage for function definition");
5903 case GlobalValue::PrivateLinkage
:
5904 case GlobalValue::InternalLinkage
:
5905 case GlobalValue::AvailableExternallyLinkage
:
5906 case GlobalValue::LinkOnceAnyLinkage
:
5907 case GlobalValue::LinkOnceODRLinkage
:
5908 case GlobalValue::WeakAnyLinkage
:
5909 case GlobalValue::WeakODRLinkage
:
5911 return error(LinkageLoc
, "invalid linkage for function declaration");
5913 case GlobalValue::AppendingLinkage
:
5914 case GlobalValue::CommonLinkage
:
5915 return error(LinkageLoc
, "invalid function linkage type");
5918 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
5919 return error(LinkageLoc
,
5920 "symbol with local linkage must have default visibility");
5922 if (!isValidDLLStorageClassForLinkage(DLLStorageClass
, Linkage
))
5923 return error(LinkageLoc
,
5924 "symbol with local linkage cannot have a DLL storage class");
5926 if (!FunctionType::isValidReturnType(RetType
))
5927 return error(RetTypeLoc
, "invalid function return type");
5929 LocTy NameLoc
= Lex
.getLoc();
5931 std::string FunctionName
;
5932 if (Lex
.getKind() == lltok::GlobalVar
) {
5933 FunctionName
= Lex
.getStrVal();
5934 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
5935 unsigned NameID
= Lex
.getUIntVal();
5937 if (NameID
!= NumberedVals
.size())
5938 return tokError("function expected to be numbered '%" +
5939 Twine(NumberedVals
.size()) + "'");
5941 return tokError("expected function name");
5946 if (Lex
.getKind() != lltok::lparen
)
5947 return tokError("expected '(' in function argument list");
5949 SmallVector
<ArgInfo
, 8> ArgList
;
5951 AttrBuilder
FuncAttrs(M
->getContext());
5952 std::vector
<unsigned> FwdRefAttrGrps
;
5954 std::string Section
;
5955 std::string Partition
;
5956 MaybeAlign Alignment
;
5958 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
5959 unsigned AddrSpace
= 0;
5960 Constant
*Prefix
= nullptr;
5961 Constant
*Prologue
= nullptr;
5962 Constant
*PersonalityFn
= nullptr;
5965 if (parseArgumentList(ArgList
, IsVarArg
) ||
5966 parseOptionalUnnamedAddr(UnnamedAddr
) ||
5967 parseOptionalProgramAddrSpace(AddrSpace
) ||
5968 parseFnAttributeValuePairs(FuncAttrs
, FwdRefAttrGrps
, false,
5970 (EatIfPresent(lltok::kw_section
) && parseStringConstant(Section
)) ||
5971 (EatIfPresent(lltok::kw_partition
) && parseStringConstant(Partition
)) ||
5972 parseOptionalComdat(FunctionName
, C
) ||
5973 parseOptionalAlignment(Alignment
) ||
5974 (EatIfPresent(lltok::kw_gc
) && parseStringConstant(GC
)) ||
5975 (EatIfPresent(lltok::kw_prefix
) && parseGlobalTypeAndValue(Prefix
)) ||
5976 (EatIfPresent(lltok::kw_prologue
) && parseGlobalTypeAndValue(Prologue
)) ||
5977 (EatIfPresent(lltok::kw_personality
) &&
5978 parseGlobalTypeAndValue(PersonalityFn
)))
5981 if (FuncAttrs
.contains(Attribute::Builtin
))
5982 return error(BuiltinLoc
, "'builtin' attribute not valid on function");
5984 // If the alignment was parsed as an attribute, move to the alignment field.
5985 if (MaybeAlign A
= FuncAttrs
.getAlignment()) {
5987 FuncAttrs
.removeAttribute(Attribute::Alignment
);
5990 // Okay, if we got here, the function is syntactically valid. Convert types
5991 // and do semantic checks.
5992 std::vector
<Type
*> ParamTypeList
;
5993 SmallVector
<AttributeSet
, 8> Attrs
;
5995 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5996 ParamTypeList
.push_back(ArgList
[i
].Ty
);
5997 Attrs
.push_back(ArgList
[i
].Attrs
);
6001 AttributeList::get(Context
, AttributeSet::get(Context
, FuncAttrs
),
6002 AttributeSet::get(Context
, RetAttrs
), Attrs
);
6004 if (PAL
.hasParamAttr(0, Attribute::StructRet
) && !RetType
->isVoidTy())
6005 return error(RetTypeLoc
, "functions with 'sret' argument must return void");
6007 FunctionType
*FT
= FunctionType::get(RetType
, ParamTypeList
, IsVarArg
);
6008 PointerType
*PFT
= PointerType::get(FT
, AddrSpace
);
6011 GlobalValue
*FwdFn
= nullptr;
6012 if (!FunctionName
.empty()) {
6013 // If this was a definition of a forward reference, remove the definition
6014 // from the forward reference table and fill in the forward ref.
6015 auto FRVI
= ForwardRefVals
.find(FunctionName
);
6016 if (FRVI
!= ForwardRefVals
.end()) {
6017 FwdFn
= FRVI
->second
.first
;
6018 if (FwdFn
->getType() != PFT
)
6019 return error(FRVI
->second
.second
,
6020 "invalid forward reference to "
6023 "' with wrong type: "
6025 getTypeString(PFT
) + "' but was '" +
6026 getTypeString(FwdFn
->getType()) + "'");
6027 ForwardRefVals
.erase(FRVI
);
6028 } else if ((Fn
= M
->getFunction(FunctionName
))) {
6029 // Reject redefinitions.
6030 return error(NameLoc
,
6031 "invalid redefinition of function '" + FunctionName
+ "'");
6032 } else if (M
->getNamedValue(FunctionName
)) {
6033 return error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
6037 // If this is a definition of a forward referenced function, make sure the
6039 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
6040 if (I
!= ForwardRefValIDs
.end()) {
6041 FwdFn
= I
->second
.first
;
6042 if (FwdFn
->getType() != PFT
)
6043 return error(NameLoc
, "type of definition and forward reference of '@" +
6044 Twine(NumberedVals
.size()) +
6047 getTypeString(PFT
) + "' but was '" +
6048 getTypeString(FwdFn
->getType()) + "'");
6049 ForwardRefValIDs
.erase(I
);
6053 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, AddrSpace
,
6056 assert(Fn
->getAddressSpace() == AddrSpace
&& "Created function in wrong AS");
6058 if (FunctionName
.empty())
6059 NumberedVals
.push_back(Fn
);
6061 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
6062 maybeSetDSOLocal(DSOLocal
, *Fn
);
6063 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
6064 Fn
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
6065 Fn
->setCallingConv(CC
);
6066 Fn
->setAttributes(PAL
);
6067 Fn
->setUnnamedAddr(UnnamedAddr
);
6069 Fn
->setAlignment(*Alignment
);
6070 Fn
->setSection(Section
);
6071 Fn
->setPartition(Partition
);
6073 Fn
->setPersonalityFn(PersonalityFn
);
6074 if (!GC
.empty()) Fn
->setGC(GC
);
6075 Fn
->setPrefixData(Prefix
);
6076 Fn
->setPrologueData(Prologue
);
6077 ForwardRefAttrGroups
[Fn
] = FwdRefAttrGrps
;
6079 // Add all of the arguments we parsed to the function.
6080 Function::arg_iterator ArgIt
= Fn
->arg_begin();
6081 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
6082 // If the argument has a name, insert it into the argument symbol table.
6083 if (ArgList
[i
].Name
.empty()) continue;
6085 // Set the name, if it conflicted, it will be auto-renamed.
6086 ArgIt
->setName(ArgList
[i
].Name
);
6088 if (ArgIt
->getName() != ArgList
[i
].Name
)
6089 return error(ArgList
[i
].Loc
,
6090 "redefinition of argument '%" + ArgList
[i
].Name
+ "'");
6094 FwdFn
->replaceAllUsesWith(Fn
);
6095 FwdFn
->eraseFromParent();
6101 // Check the declaration has no block address forward references.
6103 if (FunctionName
.empty()) {
6104 ID
.Kind
= ValID::t_GlobalID
;
6105 ID
.UIntVal
= NumberedVals
.size() - 1;
6107 ID
.Kind
= ValID::t_GlobalName
;
6108 ID
.StrVal
= FunctionName
;
6110 auto Blocks
= ForwardRefBlockAddresses
.find(ID
);
6111 if (Blocks
!= ForwardRefBlockAddresses
.end())
6112 return error(Blocks
->first
.Loc
,
6113 "cannot take blockaddress inside a declaration");
6117 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6119 if (FunctionNumber
== -1) {
6120 ID
.Kind
= ValID::t_GlobalName
;
6121 ID
.StrVal
= std::string(F
.getName());
6123 ID
.Kind
= ValID::t_GlobalID
;
6124 ID
.UIntVal
= FunctionNumber
;
6127 auto Blocks
= P
.ForwardRefBlockAddresses
.find(ID
);
6128 if (Blocks
== P
.ForwardRefBlockAddresses
.end())
6131 for (const auto &I
: Blocks
->second
) {
6132 const ValID
&BBID
= I
.first
;
6133 GlobalValue
*GV
= I
.second
;
6135 assert((BBID
.Kind
== ValID::t_LocalID
|| BBID
.Kind
== ValID::t_LocalName
) &&
6136 "Expected local id or name");
6138 if (BBID
.Kind
== ValID::t_LocalName
)
6139 BB
= getBB(BBID
.StrVal
, BBID
.Loc
);
6141 BB
= getBB(BBID
.UIntVal
, BBID
.Loc
);
6143 return P
.error(BBID
.Loc
, "referenced value is not a basic block");
6145 Value
*ResolvedVal
= BlockAddress::get(&F
, BB
);
6146 ResolvedVal
= P
.checkValidVariableType(BBID
.Loc
, BBID
.StrVal
, GV
->getType(),
6150 GV
->replaceAllUsesWith(ResolvedVal
);
6151 GV
->eraseFromParent();
6154 P
.ForwardRefBlockAddresses
.erase(Blocks
);
6158 /// parseFunctionBody
6159 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6160 bool LLParser::parseFunctionBody(Function
&Fn
) {
6161 if (Lex
.getKind() != lltok::lbrace
)
6162 return tokError("expected '{' in function body");
6163 Lex
.Lex(); // eat the {.
6165 int FunctionNumber
= -1;
6166 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
6168 PerFunctionState
PFS(*this, Fn
, FunctionNumber
);
6170 // Resolve block addresses and allow basic blocks to be forward-declared
6171 // within this function.
6172 if (PFS
.resolveForwardRefBlockAddresses())
6174 SaveAndRestore
ScopeExit(BlockAddressPFS
, &PFS
);
6176 // We need at least one basic block.
6177 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_uselistorder
)
6178 return tokError("function body requires at least one basic block");
6180 while (Lex
.getKind() != lltok::rbrace
&&
6181 Lex
.getKind() != lltok::kw_uselistorder
)
6182 if (parseBasicBlock(PFS
))
6185 while (Lex
.getKind() != lltok::rbrace
)
6186 if (parseUseListOrder(&PFS
))
6192 // Verify function is ok.
6193 return PFS
.finishFunction();
6197 /// ::= (LabelStr|LabelID)? Instruction*
6198 bool LLParser::parseBasicBlock(PerFunctionState
&PFS
) {
6199 // If this basic block starts out with a name, remember it.
6202 LocTy NameLoc
= Lex
.getLoc();
6203 if (Lex
.getKind() == lltok::LabelStr
) {
6204 Name
= Lex
.getStrVal();
6206 } else if (Lex
.getKind() == lltok::LabelID
) {
6207 NameID
= Lex
.getUIntVal();
6211 BasicBlock
*BB
= PFS
.defineBB(Name
, NameID
, NameLoc
);
6215 std::string NameStr
;
6217 // parse the instructions in this block until we get a terminator.
6220 // This instruction may have three possibilities for a name: a) none
6221 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6222 LocTy NameLoc
= Lex
.getLoc();
6226 if (Lex
.getKind() == lltok::LocalVarID
) {
6227 NameID
= Lex
.getUIntVal();
6229 if (parseToken(lltok::equal
, "expected '=' after instruction id"))
6231 } else if (Lex
.getKind() == lltok::LocalVar
) {
6232 NameStr
= Lex
.getStrVal();
6234 if (parseToken(lltok::equal
, "expected '=' after instruction name"))
6238 switch (parseInstruction(Inst
, BB
, PFS
)) {
6240 llvm_unreachable("Unknown parseInstruction result!");
6241 case InstError
: return true;
6243 Inst
->insertInto(BB
, BB
->end());
6245 // With a normal result, we check to see if the instruction is followed by
6246 // a comma and metadata.
6247 if (EatIfPresent(lltok::comma
))
6248 if (parseInstructionMetadata(*Inst
))
6251 case InstExtraComma
:
6252 Inst
->insertInto(BB
, BB
->end());
6254 // If the instruction parser ate an extra comma at the end of it, it
6255 // *must* be followed by metadata.
6256 if (parseInstructionMetadata(*Inst
))
6261 // Set the name on the instruction.
6262 if (PFS
.setInstName(NameID
, NameStr
, NameLoc
, Inst
))
6264 } while (!Inst
->isTerminator());
6269 //===----------------------------------------------------------------------===//
6270 // Instruction Parsing.
6271 //===----------------------------------------------------------------------===//
6273 /// parseInstruction - parse one of the many different instructions.
6275 int LLParser::parseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
6276 PerFunctionState
&PFS
) {
6277 lltok::Kind Token
= Lex
.getKind();
6278 if (Token
== lltok::Eof
)
6279 return tokError("found end of file when expecting more instructions");
6280 LocTy Loc
= Lex
.getLoc();
6281 unsigned KeywordVal
= Lex
.getUIntVal();
6282 Lex
.Lex(); // Eat the keyword.
6286 return error(Loc
, "expected instruction opcode");
6287 // Terminator Instructions.
6288 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
6290 return parseRet(Inst
, BB
, PFS
);
6292 return parseBr(Inst
, PFS
);
6293 case lltok::kw_switch
:
6294 return parseSwitch(Inst
, PFS
);
6295 case lltok::kw_indirectbr
:
6296 return parseIndirectBr(Inst
, PFS
);
6297 case lltok::kw_invoke
:
6298 return parseInvoke(Inst
, PFS
);
6299 case lltok::kw_resume
:
6300 return parseResume(Inst
, PFS
);
6301 case lltok::kw_cleanupret
:
6302 return parseCleanupRet(Inst
, PFS
);
6303 case lltok::kw_catchret
:
6304 return parseCatchRet(Inst
, PFS
);
6305 case lltok::kw_catchswitch
:
6306 return parseCatchSwitch(Inst
, PFS
);
6307 case lltok::kw_catchpad
:
6308 return parseCatchPad(Inst
, PFS
);
6309 case lltok::kw_cleanuppad
:
6310 return parseCleanupPad(Inst
, PFS
);
6311 case lltok::kw_callbr
:
6312 return parseCallBr(Inst
, PFS
);
6314 case lltok::kw_fneg
: {
6315 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6316 int Res
= parseUnaryOp(Inst
, PFS
, KeywordVal
, /*IsFP*/ true);
6320 Inst
->setFastMathFlags(FMF
);
6323 // Binary Operators.
6327 case lltok::kw_shl
: {
6328 bool NUW
= EatIfPresent(lltok::kw_nuw
);
6329 bool NSW
= EatIfPresent(lltok::kw_nsw
);
6330 if (!NUW
) NUW
= EatIfPresent(lltok::kw_nuw
);
6332 if (parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ false))
6335 if (NUW
) cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
6336 if (NSW
) cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
6339 case lltok::kw_fadd
:
6340 case lltok::kw_fsub
:
6341 case lltok::kw_fmul
:
6342 case lltok::kw_fdiv
:
6343 case lltok::kw_frem
: {
6344 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6345 int Res
= parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ true);
6349 Inst
->setFastMathFlags(FMF
);
6353 case lltok::kw_sdiv
:
6354 case lltok::kw_udiv
:
6355 case lltok::kw_lshr
:
6356 case lltok::kw_ashr
: {
6357 bool Exact
= EatIfPresent(lltok::kw_exact
);
6359 if (parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ false))
6361 if (Exact
) cast
<BinaryOperator
>(Inst
)->setIsExact(true);
6365 case lltok::kw_urem
:
6366 case lltok::kw_srem
:
6367 return parseArithmetic(Inst
, PFS
, KeywordVal
,
6372 return parseLogical(Inst
, PFS
, KeywordVal
);
6373 case lltok::kw_icmp
:
6374 return parseCompare(Inst
, PFS
, KeywordVal
);
6375 case lltok::kw_fcmp
: {
6376 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6377 int Res
= parseCompare(Inst
, PFS
, KeywordVal
);
6381 Inst
->setFastMathFlags(FMF
);
6386 case lltok::kw_zext
: {
6387 bool NonNeg
= EatIfPresent(lltok::kw_nneg
);
6388 bool Res
= parseCast(Inst
, PFS
, KeywordVal
);
6395 case lltok::kw_trunc
:
6396 case lltok::kw_sext
:
6397 case lltok::kw_fptrunc
:
6398 case lltok::kw_fpext
:
6399 case lltok::kw_bitcast
:
6400 case lltok::kw_addrspacecast
:
6401 case lltok::kw_uitofp
:
6402 case lltok::kw_sitofp
:
6403 case lltok::kw_fptoui
:
6404 case lltok::kw_fptosi
:
6405 case lltok::kw_inttoptr
:
6406 case lltok::kw_ptrtoint
:
6407 return parseCast(Inst
, PFS
, KeywordVal
);
6409 case lltok::kw_select
: {
6410 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6411 int Res
= parseSelect(Inst
, PFS
);
6415 if (!isa
<FPMathOperator
>(Inst
))
6416 return error(Loc
, "fast-math-flags specified for select without "
6417 "floating-point scalar or vector return type");
6418 Inst
->setFastMathFlags(FMF
);
6422 case lltok::kw_va_arg
:
6423 return parseVAArg(Inst
, PFS
);
6424 case lltok::kw_extractelement
:
6425 return parseExtractElement(Inst
, PFS
);
6426 case lltok::kw_insertelement
:
6427 return parseInsertElement(Inst
, PFS
);
6428 case lltok::kw_shufflevector
:
6429 return parseShuffleVector(Inst
, PFS
);
6430 case lltok::kw_phi
: {
6431 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6432 int Res
= parsePHI(Inst
, PFS
);
6436 if (!isa
<FPMathOperator
>(Inst
))
6437 return error(Loc
, "fast-math-flags specified for phi without "
6438 "floating-point scalar or vector return type");
6439 Inst
->setFastMathFlags(FMF
);
6443 case lltok::kw_landingpad
:
6444 return parseLandingPad(Inst
, PFS
);
6445 case lltok::kw_freeze
:
6446 return parseFreeze(Inst
, PFS
);
6448 case lltok::kw_call
:
6449 return parseCall(Inst
, PFS
, CallInst::TCK_None
);
6450 case lltok::kw_tail
:
6451 return parseCall(Inst
, PFS
, CallInst::TCK_Tail
);
6452 case lltok::kw_musttail
:
6453 return parseCall(Inst
, PFS
, CallInst::TCK_MustTail
);
6454 case lltok::kw_notail
:
6455 return parseCall(Inst
, PFS
, CallInst::TCK_NoTail
);
6457 case lltok::kw_alloca
:
6458 return parseAlloc(Inst
, PFS
);
6459 case lltok::kw_load
:
6460 return parseLoad(Inst
, PFS
);
6461 case lltok::kw_store
:
6462 return parseStore(Inst
, PFS
);
6463 case lltok::kw_cmpxchg
:
6464 return parseCmpXchg(Inst
, PFS
);
6465 case lltok::kw_atomicrmw
:
6466 return parseAtomicRMW(Inst
, PFS
);
6467 case lltok::kw_fence
:
6468 return parseFence(Inst
, PFS
);
6469 case lltok::kw_getelementptr
:
6470 return parseGetElementPtr(Inst
, PFS
);
6471 case lltok::kw_extractvalue
:
6472 return parseExtractValue(Inst
, PFS
);
6473 case lltok::kw_insertvalue
:
6474 return parseInsertValue(Inst
, PFS
);
6478 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6479 bool LLParser::parseCmpPredicate(unsigned &P
, unsigned Opc
) {
6480 if (Opc
== Instruction::FCmp
) {
6481 switch (Lex
.getKind()) {
6483 return tokError("expected fcmp predicate (e.g. 'oeq')");
6484 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
6485 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
6486 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
6487 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
6488 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
6489 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
6490 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
6491 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
6492 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
6493 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
6494 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
6495 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
6496 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
6497 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
6498 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
6499 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
6502 switch (Lex
.getKind()) {
6504 return tokError("expected icmp predicate (e.g. 'eq')");
6505 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
6506 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
6507 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
6508 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
6509 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
6510 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
6511 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
6512 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
6513 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
6514 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
6521 //===----------------------------------------------------------------------===//
6522 // Terminator Instructions.
6523 //===----------------------------------------------------------------------===//
6525 /// parseRet - parse a return instruction.
6526 /// ::= 'ret' void (',' !dbg, !1)*
6527 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6528 bool LLParser::parseRet(Instruction
*&Inst
, BasicBlock
*BB
,
6529 PerFunctionState
&PFS
) {
6530 SMLoc TypeLoc
= Lex
.getLoc();
6532 if (parseType(Ty
, true /*void allowed*/))
6535 Type
*ResType
= PFS
.getFunction().getReturnType();
6537 if (Ty
->isVoidTy()) {
6538 if (!ResType
->isVoidTy())
6539 return error(TypeLoc
, "value doesn't match function result type '" +
6540 getTypeString(ResType
) + "'");
6542 Inst
= ReturnInst::Create(Context
);
6547 if (parseValue(Ty
, RV
, PFS
))
6550 if (ResType
!= RV
->getType())
6551 return error(TypeLoc
, "value doesn't match function result type '" +
6552 getTypeString(ResType
) + "'");
6554 Inst
= ReturnInst::Create(Context
, RV
);
6559 /// ::= 'br' TypeAndValue
6560 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6561 bool LLParser::parseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6564 BasicBlock
*Op1
, *Op2
;
6565 if (parseTypeAndValue(Op0
, Loc
, PFS
))
6568 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
6569 Inst
= BranchInst::Create(BB
);
6573 if (Op0
->getType() != Type::getInt1Ty(Context
))
6574 return error(Loc
, "branch condition must have 'i1' type");
6576 if (parseToken(lltok::comma
, "expected ',' after branch condition") ||
6577 parseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
6578 parseToken(lltok::comma
, "expected ',' after true destination") ||
6579 parseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
6582 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
6588 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6590 /// ::= (TypeAndValue ',' TypeAndValue)*
6591 bool LLParser::parseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6592 LocTy CondLoc
, BBLoc
;
6594 BasicBlock
*DefaultBB
;
6595 if (parseTypeAndValue(Cond
, CondLoc
, PFS
) ||
6596 parseToken(lltok::comma
, "expected ',' after switch condition") ||
6597 parseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
6598 parseToken(lltok::lsquare
, "expected '[' with switch table"))
6601 if (!Cond
->getType()->isIntegerTy())
6602 return error(CondLoc
, "switch condition must have integer type");
6604 // parse the jump table pairs.
6605 SmallPtrSet
<Value
*, 32> SeenCases
;
6606 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
6607 while (Lex
.getKind() != lltok::rsquare
) {
6611 if (parseTypeAndValue(Constant
, CondLoc
, PFS
) ||
6612 parseToken(lltok::comma
, "expected ',' after case value") ||
6613 parseTypeAndBasicBlock(DestBB
, PFS
))
6616 if (!SeenCases
.insert(Constant
).second
)
6617 return error(CondLoc
, "duplicate case value in switch");
6618 if (!isa
<ConstantInt
>(Constant
))
6619 return error(CondLoc
, "case value is not a constant integer");
6621 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
6624 Lex
.Lex(); // Eat the ']'.
6626 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
6627 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
6628 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
6635 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6636 bool LLParser::parseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6639 if (parseTypeAndValue(Address
, AddrLoc
, PFS
) ||
6640 parseToken(lltok::comma
, "expected ',' after indirectbr address") ||
6641 parseToken(lltok::lsquare
, "expected '[' with indirectbr"))
6644 if (!Address
->getType()->isPointerTy())
6645 return error(AddrLoc
, "indirectbr address must have pointer type");
6647 // parse the destination list.
6648 SmallVector
<BasicBlock
*, 16> DestList
;
6650 if (Lex
.getKind() != lltok::rsquare
) {
6652 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6654 DestList
.push_back(DestBB
);
6656 while (EatIfPresent(lltok::comma
)) {
6657 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6659 DestList
.push_back(DestBB
);
6663 if (parseToken(lltok::rsquare
, "expected ']' at end of block list"))
6666 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
6667 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
6668 IBI
->addDestination(DestList
[i
]);
6673 // If RetType is a non-function pointer type, then this is the short syntax
6674 // for the call, which means that RetType is just the return type. Infer the
6675 // rest of the function argument types from the arguments that are present.
6676 bool LLParser::resolveFunctionType(Type
*RetType
,
6677 const SmallVector
<ParamInfo
, 16> &ArgList
,
6678 FunctionType
*&FuncTy
) {
6679 FuncTy
= dyn_cast
<FunctionType
>(RetType
);
6681 // Pull out the types of all of the arguments...
6682 std::vector
<Type
*> ParamTypes
;
6683 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6684 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6686 if (!FunctionType::isValidReturnType(RetType
))
6689 FuncTy
= FunctionType::get(RetType
, ParamTypes
, false);
6695 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6696 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6697 bool LLParser::parseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6698 LocTy CallLoc
= Lex
.getLoc();
6699 AttrBuilder
RetAttrs(M
->getContext()), FnAttrs(M
->getContext());
6700 std::vector
<unsigned> FwdRefAttrGrps
;
6703 unsigned InvokeAddrSpace
;
6704 Type
*RetType
= nullptr;
6707 SmallVector
<ParamInfo
, 16> ArgList
;
6708 SmallVector
<OperandBundleDef
, 2> BundleList
;
6710 BasicBlock
*NormalBB
, *UnwindBB
;
6711 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
6712 parseOptionalProgramAddrSpace(InvokeAddrSpace
) ||
6713 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6714 parseValID(CalleeID
, &PFS
) || parseParameterList(ArgList
, PFS
) ||
6715 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6717 parseOptionalOperandBundles(BundleList
, PFS
) ||
6718 parseToken(lltok::kw_to
, "expected 'to' in invoke") ||
6719 parseTypeAndBasicBlock(NormalBB
, PFS
) ||
6720 parseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
6721 parseTypeAndBasicBlock(UnwindBB
, PFS
))
6724 // If RetType is a non-function pointer type, then this is the short syntax
6725 // for the call, which means that RetType is just the return type. Infer the
6726 // rest of the function argument types from the arguments that are present.
6728 if (resolveFunctionType(RetType
, ArgList
, Ty
))
6729 return error(RetTypeLoc
, "Invalid result type for LLVM function");
6733 // Look up the callee.
6735 if (convertValIDToValue(PointerType::get(Ty
, InvokeAddrSpace
), CalleeID
,
6739 // Set up the Attribute for the function.
6740 SmallVector
<Value
*, 8> Args
;
6741 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6743 // Loop through FunctionType's arguments and ensure they are specified
6744 // correctly. Also, gather any parameter attributes.
6745 FunctionType::param_iterator I
= Ty
->param_begin();
6746 FunctionType::param_iterator E
= Ty
->param_end();
6747 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6748 Type
*ExpectedTy
= nullptr;
6751 } else if (!Ty
->isVarArg()) {
6752 return error(ArgList
[i
].Loc
, "too many arguments specified");
6755 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6756 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6757 getTypeString(ExpectedTy
) + "'");
6758 Args
.push_back(ArgList
[i
].V
);
6759 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6763 return error(CallLoc
, "not enough parameters specified for call");
6765 // Finish off the Attribute and check them
6767 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6768 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6771 InvokeInst::Create(Ty
, Callee
, NormalBB
, UnwindBB
, Args
, BundleList
);
6772 II
->setCallingConv(CC
);
6773 II
->setAttributes(PAL
);
6774 ForwardRefAttrGroups
[II
] = FwdRefAttrGrps
;
6780 /// ::= 'resume' TypeAndValue
6781 bool LLParser::parseResume(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6782 Value
*Exn
; LocTy ExnLoc
;
6783 if (parseTypeAndValue(Exn
, ExnLoc
, PFS
))
6786 ResumeInst
*RI
= ResumeInst::Create(Exn
);
6791 bool LLParser::parseExceptionArgs(SmallVectorImpl
<Value
*> &Args
,
6792 PerFunctionState
&PFS
) {
6793 if (parseToken(lltok::lsquare
, "expected '[' in catchpad/cleanuppad"))
6796 while (Lex
.getKind() != lltok::rsquare
) {
6797 // If this isn't the first argument, we need a comma.
6798 if (!Args
.empty() &&
6799 parseToken(lltok::comma
, "expected ',' in argument list"))
6802 // parse the argument.
6804 Type
*ArgTy
= nullptr;
6805 if (parseType(ArgTy
, ArgLoc
))
6809 if (ArgTy
->isMetadataTy()) {
6810 if (parseMetadataAsValue(V
, PFS
))
6813 if (parseValue(ArgTy
, V
, PFS
))
6819 Lex
.Lex(); // Lex the ']'.
6824 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6825 bool LLParser::parseCleanupRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6826 Value
*CleanupPad
= nullptr;
6828 if (parseToken(lltok::kw_from
, "expected 'from' after cleanupret"))
6831 if (parseValue(Type::getTokenTy(Context
), CleanupPad
, PFS
))
6834 if (parseToken(lltok::kw_unwind
, "expected 'unwind' in cleanupret"))
6837 BasicBlock
*UnwindBB
= nullptr;
6838 if (Lex
.getKind() == lltok::kw_to
) {
6840 if (parseToken(lltok::kw_caller
, "expected 'caller' in cleanupret"))
6843 if (parseTypeAndBasicBlock(UnwindBB
, PFS
)) {
6848 Inst
= CleanupReturnInst::Create(CleanupPad
, UnwindBB
);
6853 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6854 bool LLParser::parseCatchRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6855 Value
*CatchPad
= nullptr;
6857 if (parseToken(lltok::kw_from
, "expected 'from' after catchret"))
6860 if (parseValue(Type::getTokenTy(Context
), CatchPad
, PFS
))
6864 if (parseToken(lltok::kw_to
, "expected 'to' in catchret") ||
6865 parseTypeAndBasicBlock(BB
, PFS
))
6868 Inst
= CatchReturnInst::Create(CatchPad
, BB
);
6872 /// parseCatchSwitch
6873 /// ::= 'catchswitch' within Parent
6874 bool LLParser::parseCatchSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6877 if (parseToken(lltok::kw_within
, "expected 'within' after catchswitch"))
6880 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6881 Lex
.getKind() != lltok::LocalVarID
)
6882 return tokError("expected scope value for catchswitch");
6884 if (parseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6887 if (parseToken(lltok::lsquare
, "expected '[' with catchswitch labels"))
6890 SmallVector
<BasicBlock
*, 32> Table
;
6893 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6895 Table
.push_back(DestBB
);
6896 } while (EatIfPresent(lltok::comma
));
6898 if (parseToken(lltok::rsquare
, "expected ']' after catchswitch labels"))
6901 if (parseToken(lltok::kw_unwind
, "expected 'unwind' after catchswitch scope"))
6904 BasicBlock
*UnwindBB
= nullptr;
6905 if (EatIfPresent(lltok::kw_to
)) {
6906 if (parseToken(lltok::kw_caller
, "expected 'caller' in catchswitch"))
6909 if (parseTypeAndBasicBlock(UnwindBB
, PFS
))
6914 CatchSwitchInst::Create(ParentPad
, UnwindBB
, Table
.size());
6915 for (BasicBlock
*DestBB
: Table
)
6916 CatchSwitch
->addHandler(DestBB
);
6922 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6923 bool LLParser::parseCatchPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6924 Value
*CatchSwitch
= nullptr;
6926 if (parseToken(lltok::kw_within
, "expected 'within' after catchpad"))
6929 if (Lex
.getKind() != lltok::LocalVar
&& Lex
.getKind() != lltok::LocalVarID
)
6930 return tokError("expected scope value for catchpad");
6932 if (parseValue(Type::getTokenTy(Context
), CatchSwitch
, PFS
))
6935 SmallVector
<Value
*, 8> Args
;
6936 if (parseExceptionArgs(Args
, PFS
))
6939 Inst
= CatchPadInst::Create(CatchSwitch
, Args
);
6944 /// ::= 'cleanuppad' within Parent ParamList
6945 bool LLParser::parseCleanupPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6946 Value
*ParentPad
= nullptr;
6948 if (parseToken(lltok::kw_within
, "expected 'within' after cleanuppad"))
6951 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6952 Lex
.getKind() != lltok::LocalVarID
)
6953 return tokError("expected scope value for cleanuppad");
6955 if (parseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6958 SmallVector
<Value
*, 8> Args
;
6959 if (parseExceptionArgs(Args
, PFS
))
6962 Inst
= CleanupPadInst::Create(ParentPad
, Args
);
6966 //===----------------------------------------------------------------------===//
6968 //===----------------------------------------------------------------------===//
6971 /// ::= UnaryOp TypeAndValue ',' Value
6973 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6974 /// operand is allowed.
6975 bool LLParser::parseUnaryOp(Instruction
*&Inst
, PerFunctionState
&PFS
,
6976 unsigned Opc
, bool IsFP
) {
6977 LocTy Loc
; Value
*LHS
;
6978 if (parseTypeAndValue(LHS
, Loc
, PFS
))
6981 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
6982 : LHS
->getType()->isIntOrIntVectorTy();
6985 return error(Loc
, "invalid operand type for instruction");
6987 Inst
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
6992 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6993 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6994 /// '[' LabelList ']'
6995 bool LLParser::parseCallBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6996 LocTy CallLoc
= Lex
.getLoc();
6997 AttrBuilder
RetAttrs(M
->getContext()), FnAttrs(M
->getContext());
6998 std::vector
<unsigned> FwdRefAttrGrps
;
7001 Type
*RetType
= nullptr;
7004 SmallVector
<ParamInfo
, 16> ArgList
;
7005 SmallVector
<OperandBundleDef
, 2> BundleList
;
7007 BasicBlock
*DefaultDest
;
7008 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
7009 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
7010 parseValID(CalleeID
, &PFS
) || parseParameterList(ArgList
, PFS
) ||
7011 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
7013 parseOptionalOperandBundles(BundleList
, PFS
) ||
7014 parseToken(lltok::kw_to
, "expected 'to' in callbr") ||
7015 parseTypeAndBasicBlock(DefaultDest
, PFS
) ||
7016 parseToken(lltok::lsquare
, "expected '[' in callbr"))
7019 // parse the destination list.
7020 SmallVector
<BasicBlock
*, 16> IndirectDests
;
7022 if (Lex
.getKind() != lltok::rsquare
) {
7024 if (parseTypeAndBasicBlock(DestBB
, PFS
))
7026 IndirectDests
.push_back(DestBB
);
7028 while (EatIfPresent(lltok::comma
)) {
7029 if (parseTypeAndBasicBlock(DestBB
, PFS
))
7031 IndirectDests
.push_back(DestBB
);
7035 if (parseToken(lltok::rsquare
, "expected ']' at end of block list"))
7038 // If RetType is a non-function pointer type, then this is the short syntax
7039 // for the call, which means that RetType is just the return type. Infer the
7040 // rest of the function argument types from the arguments that are present.
7042 if (resolveFunctionType(RetType
, ArgList
, Ty
))
7043 return error(RetTypeLoc
, "Invalid result type for LLVM function");
7047 // Look up the callee.
7049 if (convertValIDToValue(PointerType::getUnqual(Ty
), CalleeID
, Callee
, &PFS
))
7052 // Set up the Attribute for the function.
7053 SmallVector
<Value
*, 8> Args
;
7054 SmallVector
<AttributeSet
, 8> ArgAttrs
;
7056 // Loop through FunctionType's arguments and ensure they are specified
7057 // correctly. Also, gather any parameter attributes.
7058 FunctionType::param_iterator I
= Ty
->param_begin();
7059 FunctionType::param_iterator E
= Ty
->param_end();
7060 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
7061 Type
*ExpectedTy
= nullptr;
7064 } else if (!Ty
->isVarArg()) {
7065 return error(ArgList
[i
].Loc
, "too many arguments specified");
7068 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
7069 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
7070 getTypeString(ExpectedTy
) + "'");
7071 Args
.push_back(ArgList
[i
].V
);
7072 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
7076 return error(CallLoc
, "not enough parameters specified for call");
7078 // Finish off the Attribute and check them
7080 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
7081 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
7084 CallBrInst::Create(Ty
, Callee
, DefaultDest
, IndirectDests
, Args
,
7086 CBI
->setCallingConv(CC
);
7087 CBI
->setAttributes(PAL
);
7088 ForwardRefAttrGroups
[CBI
] = FwdRefAttrGrps
;
7093 //===----------------------------------------------------------------------===//
7094 // Binary Operators.
7095 //===----------------------------------------------------------------------===//
7098 /// ::= ArithmeticOps TypeAndValue ',' Value
7100 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7101 /// operand is allowed.
7102 bool LLParser::parseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
7103 unsigned Opc
, bool IsFP
) {
7104 LocTy Loc
; Value
*LHS
, *RHS
;
7105 if (parseTypeAndValue(LHS
, Loc
, PFS
) ||
7106 parseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
7107 parseValue(LHS
->getType(), RHS
, PFS
))
7110 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
7111 : LHS
->getType()->isIntOrIntVectorTy();
7114 return error(Loc
, "invalid operand type for instruction");
7116 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
7121 /// ::= ArithmeticOps TypeAndValue ',' Value {
7122 bool LLParser::parseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
7124 LocTy Loc
; Value
*LHS
, *RHS
;
7125 if (parseTypeAndValue(LHS
, Loc
, PFS
) ||
7126 parseToken(lltok::comma
, "expected ',' in logical operation") ||
7127 parseValue(LHS
->getType(), RHS
, PFS
))
7130 if (!LHS
->getType()->isIntOrIntVectorTy())
7132 "instruction requires integer or integer vector operands");
7134 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
7139 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
7140 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7141 bool LLParser::parseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
7143 // parse the integer/fp comparison predicate.
7147 if (parseCmpPredicate(Pred
, Opc
) || parseTypeAndValue(LHS
, Loc
, PFS
) ||
7148 parseToken(lltok::comma
, "expected ',' after compare value") ||
7149 parseValue(LHS
->getType(), RHS
, PFS
))
7152 if (Opc
== Instruction::FCmp
) {
7153 if (!LHS
->getType()->isFPOrFPVectorTy())
7154 return error(Loc
, "fcmp requires floating point operands");
7155 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
7157 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
7158 if (!LHS
->getType()->isIntOrIntVectorTy() &&
7159 !LHS
->getType()->isPtrOrPtrVectorTy())
7160 return error(Loc
, "icmp requires integer operands");
7161 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
7166 //===----------------------------------------------------------------------===//
7167 // Other Instructions.
7168 //===----------------------------------------------------------------------===//
7171 /// ::= CastOpc TypeAndValue 'to' Type
7172 bool LLParser::parseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
7176 Type
*DestTy
= nullptr;
7177 if (parseTypeAndValue(Op
, Loc
, PFS
) ||
7178 parseToken(lltok::kw_to
, "expected 'to' after cast value") ||
7182 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
7183 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
7184 return error(Loc
, "invalid cast opcode for cast from '" +
7185 getTypeString(Op
->getType()) + "' to '" +
7186 getTypeString(DestTy
) + "'");
7188 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
7193 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7194 bool LLParser::parseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7196 Value
*Op0
, *Op1
, *Op2
;
7197 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7198 parseToken(lltok::comma
, "expected ',' after select condition") ||
7199 parseTypeAndValue(Op1
, PFS
) ||
7200 parseToken(lltok::comma
, "expected ',' after select value") ||
7201 parseTypeAndValue(Op2
, PFS
))
7204 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
7205 return error(Loc
, Reason
);
7207 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
7212 /// ::= 'va_arg' TypeAndValue ',' Type
7213 bool LLParser::parseVAArg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7215 Type
*EltTy
= nullptr;
7217 if (parseTypeAndValue(Op
, PFS
) ||
7218 parseToken(lltok::comma
, "expected ',' after vaarg operand") ||
7219 parseType(EltTy
, TypeLoc
))
7222 if (!EltTy
->isFirstClassType())
7223 return error(TypeLoc
, "va_arg requires operand with first class type");
7225 Inst
= new VAArgInst(Op
, EltTy
);
7229 /// parseExtractElement
7230 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7231 bool LLParser::parseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7234 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7235 parseToken(lltok::comma
, "expected ',' after extract value") ||
7236 parseTypeAndValue(Op1
, PFS
))
7239 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
7240 return error(Loc
, "invalid extractelement operands");
7242 Inst
= ExtractElementInst::Create(Op0
, Op1
);
7246 /// parseInsertElement
7247 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7248 bool LLParser::parseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7250 Value
*Op0
, *Op1
, *Op2
;
7251 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7252 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
7253 parseTypeAndValue(Op1
, PFS
) ||
7254 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
7255 parseTypeAndValue(Op2
, PFS
))
7258 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
7259 return error(Loc
, "invalid insertelement operands");
7261 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
7265 /// parseShuffleVector
7266 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7267 bool LLParser::parseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7269 Value
*Op0
, *Op1
, *Op2
;
7270 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7271 parseToken(lltok::comma
, "expected ',' after shuffle mask") ||
7272 parseTypeAndValue(Op1
, PFS
) ||
7273 parseToken(lltok::comma
, "expected ',' after shuffle value") ||
7274 parseTypeAndValue(Op2
, PFS
))
7277 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
7278 return error(Loc
, "invalid shufflevector operands");
7280 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
7285 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7286 int LLParser::parsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7287 Type
*Ty
= nullptr; LocTy TypeLoc
;
7290 if (parseType(Ty
, TypeLoc
))
7293 if (!Ty
->isFirstClassType())
7294 return error(TypeLoc
, "phi node must have first class type");
7297 bool AteExtraComma
= false;
7298 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
7302 if (Lex
.getKind() != lltok::lsquare
)
7305 } else if (!EatIfPresent(lltok::comma
))
7308 if (Lex
.getKind() == lltok::MetadataVar
) {
7309 AteExtraComma
= true;
7313 if (parseToken(lltok::lsquare
, "expected '[' in phi value list") ||
7314 parseValue(Ty
, Op0
, PFS
) ||
7315 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
7316 parseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
7317 parseToken(lltok::rsquare
, "expected ']' in phi value list"))
7320 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
7323 PHINode
*PN
= PHINode::Create(Ty
, PHIVals
.size());
7324 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
7325 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
7327 return AteExtraComma
? InstExtraComma
: InstNormal
;
7331 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7333 /// ::= 'catch' TypeAndValue
7335 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7336 bool LLParser::parseLandingPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7337 Type
*Ty
= nullptr; LocTy TyLoc
;
7339 if (parseType(Ty
, TyLoc
))
7342 std::unique_ptr
<LandingPadInst
> LP(LandingPadInst::Create(Ty
, 0));
7343 LP
->setCleanup(EatIfPresent(lltok::kw_cleanup
));
7345 while (Lex
.getKind() == lltok::kw_catch
|| Lex
.getKind() == lltok::kw_filter
){
7346 LandingPadInst::ClauseType CT
;
7347 if (EatIfPresent(lltok::kw_catch
))
7348 CT
= LandingPadInst::Catch
;
7349 else if (EatIfPresent(lltok::kw_filter
))
7350 CT
= LandingPadInst::Filter
;
7352 return tokError("expected 'catch' or 'filter' clause type");
7356 if (parseTypeAndValue(V
, VLoc
, PFS
))
7359 // A 'catch' type expects a non-array constant. A filter clause expects an
7361 if (CT
== LandingPadInst::Catch
) {
7362 if (isa
<ArrayType
>(V
->getType()))
7363 error(VLoc
, "'catch' clause has an invalid type");
7365 if (!isa
<ArrayType
>(V
->getType()))
7366 error(VLoc
, "'filter' clause has an invalid type");
7369 Constant
*CV
= dyn_cast
<Constant
>(V
);
7371 return error(VLoc
, "clause argument must be a constant");
7375 Inst
= LP
.release();
7380 /// ::= 'freeze' Type Value
7381 bool LLParser::parseFreeze(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7384 if (parseTypeAndValue(Op
, Loc
, PFS
))
7387 Inst
= new FreezeInst(Op
);
7392 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7393 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7394 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7395 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7396 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7397 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7398 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7399 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7400 bool LLParser::parseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
7401 CallInst::TailCallKind TCK
) {
7402 AttrBuilder
RetAttrs(M
->getContext()), FnAttrs(M
->getContext());
7403 std::vector
<unsigned> FwdRefAttrGrps
;
7405 unsigned CallAddrSpace
;
7407 Type
*RetType
= nullptr;
7410 SmallVector
<ParamInfo
, 16> ArgList
;
7411 SmallVector
<OperandBundleDef
, 2> BundleList
;
7412 LocTy CallLoc
= Lex
.getLoc();
7414 if (TCK
!= CallInst::TCK_None
&&
7415 parseToken(lltok::kw_call
,
7416 "expected 'tail call', 'musttail call', or 'notail call'"))
7419 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
7421 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
7422 parseOptionalProgramAddrSpace(CallAddrSpace
) ||
7423 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
7424 parseValID(CalleeID
, &PFS
) ||
7425 parseParameterList(ArgList
, PFS
, TCK
== CallInst::TCK_MustTail
,
7426 PFS
.getFunction().isVarArg()) ||
7427 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false, BuiltinLoc
) ||
7428 parseOptionalOperandBundles(BundleList
, PFS
))
7431 // If RetType is a non-function pointer type, then this is the short syntax
7432 // for the call, which means that RetType is just the return type. Infer the
7433 // rest of the function argument types from the arguments that are present.
7435 if (resolveFunctionType(RetType
, ArgList
, Ty
))
7436 return error(RetTypeLoc
, "Invalid result type for LLVM function");
7440 // Look up the callee.
7442 if (convertValIDToValue(PointerType::get(Ty
, CallAddrSpace
), CalleeID
, Callee
,
7446 // Set up the Attribute for the function.
7447 SmallVector
<AttributeSet
, 8> Attrs
;
7449 SmallVector
<Value
*, 8> Args
;
7451 // Loop through FunctionType's arguments and ensure they are specified
7452 // correctly. Also, gather any parameter attributes.
7453 FunctionType::param_iterator I
= Ty
->param_begin();
7454 FunctionType::param_iterator E
= Ty
->param_end();
7455 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
7456 Type
*ExpectedTy
= nullptr;
7459 } else if (!Ty
->isVarArg()) {
7460 return error(ArgList
[i
].Loc
, "too many arguments specified");
7463 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
7464 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
7465 getTypeString(ExpectedTy
) + "'");
7466 Args
.push_back(ArgList
[i
].V
);
7467 Attrs
.push_back(ArgList
[i
].Attrs
);
7471 return error(CallLoc
, "not enough parameters specified for call");
7473 // Finish off the Attribute and check them
7475 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
7476 AttributeSet::get(Context
, RetAttrs
), Attrs
);
7478 CallInst
*CI
= CallInst::Create(Ty
, Callee
, Args
, BundleList
);
7479 CI
->setTailCallKind(TCK
);
7480 CI
->setCallingConv(CC
);
7482 if (!isa
<FPMathOperator
>(CI
)) {
7484 return error(CallLoc
, "fast-math-flags specified for call without "
7485 "floating-point scalar or vector return type");
7487 CI
->setFastMathFlags(FMF
);
7489 CI
->setAttributes(PAL
);
7490 ForwardRefAttrGroups
[CI
] = FwdRefAttrGrps
;
7495 //===----------------------------------------------------------------------===//
7496 // Memory Instructions.
7497 //===----------------------------------------------------------------------===//
7500 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7501 /// (',' 'align' i32)? (',', 'addrspace(n))?
7502 int LLParser::parseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7503 Value
*Size
= nullptr;
7504 LocTy SizeLoc
, TyLoc
, ASLoc
;
7505 MaybeAlign Alignment
;
7506 unsigned AddrSpace
= 0;
7509 bool IsInAlloca
= EatIfPresent(lltok::kw_inalloca
);
7510 bool IsSwiftError
= EatIfPresent(lltok::kw_swifterror
);
7512 if (parseType(Ty
, TyLoc
))
7515 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
7516 return error(TyLoc
, "invalid type for alloca");
7518 bool AteExtraComma
= false;
7519 if (EatIfPresent(lltok::comma
)) {
7520 if (Lex
.getKind() == lltok::kw_align
) {
7521 if (parseOptionalAlignment(Alignment
))
7523 if (parseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
7525 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
7526 ASLoc
= Lex
.getLoc();
7527 if (parseOptionalAddrSpace(AddrSpace
))
7529 } else if (Lex
.getKind() == lltok::MetadataVar
) {
7530 AteExtraComma
= true;
7532 if (parseTypeAndValue(Size
, SizeLoc
, PFS
))
7534 if (EatIfPresent(lltok::comma
)) {
7535 if (Lex
.getKind() == lltok::kw_align
) {
7536 if (parseOptionalAlignment(Alignment
))
7538 if (parseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
7540 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
7541 ASLoc
= Lex
.getLoc();
7542 if (parseOptionalAddrSpace(AddrSpace
))
7544 } else if (Lex
.getKind() == lltok::MetadataVar
) {
7545 AteExtraComma
= true;
7551 if (Size
&& !Size
->getType()->isIntegerTy())
7552 return error(SizeLoc
, "element count must have integer type");
7554 SmallPtrSet
<Type
*, 4> Visited
;
7555 if (!Alignment
&& !Ty
->isSized(&Visited
))
7556 return error(TyLoc
, "Cannot allocate unsized type");
7558 Alignment
= M
->getDataLayout().getPrefTypeAlign(Ty
);
7559 AllocaInst
*AI
= new AllocaInst(Ty
, AddrSpace
, Size
, *Alignment
);
7560 AI
->setUsedWithInAlloca(IsInAlloca
);
7561 AI
->setSwiftError(IsSwiftError
);
7563 return AteExtraComma
? InstExtraComma
: InstNormal
;
7567 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7568 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7569 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7570 int LLParser::parseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7571 Value
*Val
; LocTy Loc
;
7572 MaybeAlign Alignment
;
7573 bool AteExtraComma
= false;
7574 bool isAtomic
= false;
7575 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7576 SyncScope::ID SSID
= SyncScope::System
;
7578 if (Lex
.getKind() == lltok::kw_atomic
) {
7583 bool isVolatile
= false;
7584 if (Lex
.getKind() == lltok::kw_volatile
) {
7590 LocTy ExplicitTypeLoc
= Lex
.getLoc();
7591 if (parseType(Ty
) ||
7592 parseToken(lltok::comma
, "expected comma after load's type") ||
7593 parseTypeAndValue(Val
, Loc
, PFS
) ||
7594 parseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
7595 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7598 if (!Val
->getType()->isPointerTy() || !Ty
->isFirstClassType())
7599 return error(Loc
, "load operand must be a pointer to a first class type");
7600 if (isAtomic
&& !Alignment
)
7601 return error(Loc
, "atomic load must have explicit non-zero alignment");
7602 if (Ordering
== AtomicOrdering::Release
||
7603 Ordering
== AtomicOrdering::AcquireRelease
)
7604 return error(Loc
, "atomic load cannot use Release ordering");
7606 SmallPtrSet
<Type
*, 4> Visited
;
7607 if (!Alignment
&& !Ty
->isSized(&Visited
))
7608 return error(ExplicitTypeLoc
, "loading unsized types is not allowed");
7610 Alignment
= M
->getDataLayout().getABITypeAlign(Ty
);
7611 Inst
= new LoadInst(Ty
, Val
, "", isVolatile
, *Alignment
, Ordering
, SSID
);
7612 return AteExtraComma
? InstExtraComma
: InstNormal
;
7617 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7618 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7619 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7620 int LLParser::parseStore(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7621 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
7622 MaybeAlign Alignment
;
7623 bool AteExtraComma
= false;
7624 bool isAtomic
= false;
7625 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7626 SyncScope::ID SSID
= SyncScope::System
;
7628 if (Lex
.getKind() == lltok::kw_atomic
) {
7633 bool isVolatile
= false;
7634 if (Lex
.getKind() == lltok::kw_volatile
) {
7639 if (parseTypeAndValue(Val
, Loc
, PFS
) ||
7640 parseToken(lltok::comma
, "expected ',' after store operand") ||
7641 parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7642 parseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
7643 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7646 if (!Ptr
->getType()->isPointerTy())
7647 return error(PtrLoc
, "store operand must be a pointer");
7648 if (!Val
->getType()->isFirstClassType())
7649 return error(Loc
, "store operand must be a first class value");
7650 if (isAtomic
&& !Alignment
)
7651 return error(Loc
, "atomic store must have explicit non-zero alignment");
7652 if (Ordering
== AtomicOrdering::Acquire
||
7653 Ordering
== AtomicOrdering::AcquireRelease
)
7654 return error(Loc
, "atomic store cannot use Acquire ordering");
7655 SmallPtrSet
<Type
*, 4> Visited
;
7656 if (!Alignment
&& !Val
->getType()->isSized(&Visited
))
7657 return error(Loc
, "storing unsized types is not allowed");
7659 Alignment
= M
->getDataLayout().getABITypeAlign(Val
->getType());
7661 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, *Alignment
, Ordering
, SSID
);
7662 return AteExtraComma
? InstExtraComma
: InstNormal
;
7666 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7667 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7669 int LLParser::parseCmpXchg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7670 Value
*Ptr
, *Cmp
, *New
; LocTy PtrLoc
, CmpLoc
, NewLoc
;
7671 bool AteExtraComma
= false;
7672 AtomicOrdering SuccessOrdering
= AtomicOrdering::NotAtomic
;
7673 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
;
7674 SyncScope::ID SSID
= SyncScope::System
;
7675 bool isVolatile
= false;
7676 bool isWeak
= false;
7677 MaybeAlign Alignment
;
7679 if (EatIfPresent(lltok::kw_weak
))
7682 if (EatIfPresent(lltok::kw_volatile
))
7685 if (parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7686 parseToken(lltok::comma
, "expected ',' after cmpxchg address") ||
7687 parseTypeAndValue(Cmp
, CmpLoc
, PFS
) ||
7688 parseToken(lltok::comma
, "expected ',' after cmpxchg cmp operand") ||
7689 parseTypeAndValue(New
, NewLoc
, PFS
) ||
7690 parseScopeAndOrdering(true /*Always atomic*/, SSID
, SuccessOrdering
) ||
7691 parseOrdering(FailureOrdering
) ||
7692 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7695 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering
))
7696 return tokError("invalid cmpxchg success ordering");
7697 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering
))
7698 return tokError("invalid cmpxchg failure ordering");
7699 if (!Ptr
->getType()->isPointerTy())
7700 return error(PtrLoc
, "cmpxchg operand must be a pointer");
7701 if (Cmp
->getType() != New
->getType())
7702 return error(NewLoc
, "compare value and new value type do not match");
7703 if (!New
->getType()->isFirstClassType())
7704 return error(NewLoc
, "cmpxchg operand must be a first class value");
7706 const Align
DefaultAlignment(
7707 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7710 AtomicCmpXchgInst
*CXI
=
7711 new AtomicCmpXchgInst(Ptr
, Cmp
, New
, Alignment
.value_or(DefaultAlignment
),
7712 SuccessOrdering
, FailureOrdering
, SSID
);
7713 CXI
->setVolatile(isVolatile
);
7714 CXI
->setWeak(isWeak
);
7717 return AteExtraComma
? InstExtraComma
: InstNormal
;
7721 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7722 /// 'singlethread'? AtomicOrdering
7723 int LLParser::parseAtomicRMW(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7724 Value
*Ptr
, *Val
; LocTy PtrLoc
, ValLoc
;
7725 bool AteExtraComma
= false;
7726 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7727 SyncScope::ID SSID
= SyncScope::System
;
7728 bool isVolatile
= false;
7730 AtomicRMWInst::BinOp Operation
;
7731 MaybeAlign Alignment
;
7733 if (EatIfPresent(lltok::kw_volatile
))
7736 switch (Lex
.getKind()) {
7738 return tokError("expected binary operation in atomicrmw");
7739 case lltok::kw_xchg
: Operation
= AtomicRMWInst::Xchg
; break;
7740 case lltok::kw_add
: Operation
= AtomicRMWInst::Add
; break;
7741 case lltok::kw_sub
: Operation
= AtomicRMWInst::Sub
; break;
7742 case lltok::kw_and
: Operation
= AtomicRMWInst::And
; break;
7743 case lltok::kw_nand
: Operation
= AtomicRMWInst::Nand
; break;
7744 case lltok::kw_or
: Operation
= AtomicRMWInst::Or
; break;
7745 case lltok::kw_xor
: Operation
= AtomicRMWInst::Xor
; break;
7746 case lltok::kw_max
: Operation
= AtomicRMWInst::Max
; break;
7747 case lltok::kw_min
: Operation
= AtomicRMWInst::Min
; break;
7748 case lltok::kw_umax
: Operation
= AtomicRMWInst::UMax
; break;
7749 case lltok::kw_umin
: Operation
= AtomicRMWInst::UMin
; break;
7750 case lltok::kw_uinc_wrap
:
7751 Operation
= AtomicRMWInst::UIncWrap
;
7753 case lltok::kw_udec_wrap
:
7754 Operation
= AtomicRMWInst::UDecWrap
;
7756 case lltok::kw_fadd
:
7757 Operation
= AtomicRMWInst::FAdd
;
7760 case lltok::kw_fsub
:
7761 Operation
= AtomicRMWInst::FSub
;
7764 case lltok::kw_fmax
:
7765 Operation
= AtomicRMWInst::FMax
;
7768 case lltok::kw_fmin
:
7769 Operation
= AtomicRMWInst::FMin
;
7773 Lex
.Lex(); // Eat the operation.
7775 if (parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7776 parseToken(lltok::comma
, "expected ',' after atomicrmw address") ||
7777 parseTypeAndValue(Val
, ValLoc
, PFS
) ||
7778 parseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
) ||
7779 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7782 if (Ordering
== AtomicOrdering::Unordered
)
7783 return tokError("atomicrmw cannot be unordered");
7784 if (!Ptr
->getType()->isPointerTy())
7785 return error(PtrLoc
, "atomicrmw operand must be a pointer");
7787 if (Operation
== AtomicRMWInst::Xchg
) {
7788 if (!Val
->getType()->isIntegerTy() &&
7789 !Val
->getType()->isFloatingPointTy() &&
7790 !Val
->getType()->isPointerTy()) {
7793 "atomicrmw " + AtomicRMWInst::getOperationName(Operation
) +
7794 " operand must be an integer, floating point, or pointer type");
7797 if (!Val
->getType()->isFloatingPointTy()) {
7798 return error(ValLoc
, "atomicrmw " +
7799 AtomicRMWInst::getOperationName(Operation
) +
7800 " operand must be a floating point type");
7803 if (!Val
->getType()->isIntegerTy()) {
7804 return error(ValLoc
, "atomicrmw " +
7805 AtomicRMWInst::getOperationName(Operation
) +
7806 " operand must be an integer");
7811 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7813 if (Size
< 8 || (Size
& (Size
- 1)))
7814 return error(ValLoc
, "atomicrmw operand must be power-of-two byte-sized"
7816 const Align
DefaultAlignment(
7817 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7819 AtomicRMWInst
*RMWI
=
7820 new AtomicRMWInst(Operation
, Ptr
, Val
,
7821 Alignment
.value_or(DefaultAlignment
), Ordering
, SSID
);
7822 RMWI
->setVolatile(isVolatile
);
7824 return AteExtraComma
? InstExtraComma
: InstNormal
;
7828 /// ::= 'fence' 'singlethread'? AtomicOrdering
7829 int LLParser::parseFence(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7830 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7831 SyncScope::ID SSID
= SyncScope::System
;
7832 if (parseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7835 if (Ordering
== AtomicOrdering::Unordered
)
7836 return tokError("fence cannot be unordered");
7837 if (Ordering
== AtomicOrdering::Monotonic
)
7838 return tokError("fence cannot be monotonic");
7840 Inst
= new FenceInst(Context
, Ordering
, SSID
);
7844 /// parseGetElementPtr
7845 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7846 int LLParser::parseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7847 Value
*Ptr
= nullptr;
7848 Value
*Val
= nullptr;
7851 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
7854 if (parseType(Ty
) ||
7855 parseToken(lltok::comma
, "expected comma after getelementptr's type") ||
7856 parseTypeAndValue(Ptr
, Loc
, PFS
))
7859 Type
*BaseType
= Ptr
->getType();
7860 PointerType
*BasePointerType
= dyn_cast
<PointerType
>(BaseType
->getScalarType());
7861 if (!BasePointerType
)
7862 return error(Loc
, "base of getelementptr must be a pointer");
7864 SmallVector
<Value
*, 16> Indices
;
7865 bool AteExtraComma
= false;
7866 // GEP returns a vector of pointers if at least one of parameters is a vector.
7867 // All vector parameters should have the same vector width.
7868 ElementCount GEPWidth
= BaseType
->isVectorTy()
7869 ? cast
<VectorType
>(BaseType
)->getElementCount()
7870 : ElementCount::getFixed(0);
7872 while (EatIfPresent(lltok::comma
)) {
7873 if (Lex
.getKind() == lltok::MetadataVar
) {
7874 AteExtraComma
= true;
7877 if (parseTypeAndValue(Val
, EltLoc
, PFS
))
7879 if (!Val
->getType()->isIntOrIntVectorTy())
7880 return error(EltLoc
, "getelementptr index must be an integer");
7882 if (auto *ValVTy
= dyn_cast
<VectorType
>(Val
->getType())) {
7883 ElementCount ValNumEl
= ValVTy
->getElementCount();
7884 if (GEPWidth
!= ElementCount::getFixed(0) && GEPWidth
!= ValNumEl
)
7887 "getelementptr vector index has a wrong number of elements");
7888 GEPWidth
= ValNumEl
;
7890 Indices
.push_back(Val
);
7893 SmallPtrSet
<Type
*, 4> Visited
;
7894 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
7895 return error(Loc
, "base element of getelementptr must be sized");
7897 auto *STy
= dyn_cast
<StructType
>(Ty
);
7898 if (STy
&& STy
->containsScalableVectorType())
7899 return error(Loc
, "getelementptr cannot target structure that contains "
7900 "scalable vector type");
7902 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
7903 return error(Loc
, "invalid getelementptr indices");
7904 Inst
= GetElementPtrInst::Create(Ty
, Ptr
, Indices
);
7906 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
7907 return AteExtraComma
? InstExtraComma
: InstNormal
;
7910 /// parseExtractValue
7911 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7912 int LLParser::parseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7913 Value
*Val
; LocTy Loc
;
7914 SmallVector
<unsigned, 4> Indices
;
7916 if (parseTypeAndValue(Val
, Loc
, PFS
) ||
7917 parseIndexList(Indices
, AteExtraComma
))
7920 if (!Val
->getType()->isAggregateType())
7921 return error(Loc
, "extractvalue operand must be aggregate type");
7923 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
7924 return error(Loc
, "invalid indices for extractvalue");
7925 Inst
= ExtractValueInst::Create(Val
, Indices
);
7926 return AteExtraComma
? InstExtraComma
: InstNormal
;
7929 /// parseInsertValue
7930 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7931 int LLParser::parseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7932 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
7933 SmallVector
<unsigned, 4> Indices
;
7935 if (parseTypeAndValue(Val0
, Loc0
, PFS
) ||
7936 parseToken(lltok::comma
, "expected comma after insertvalue operand") ||
7937 parseTypeAndValue(Val1
, Loc1
, PFS
) ||
7938 parseIndexList(Indices
, AteExtraComma
))
7941 if (!Val0
->getType()->isAggregateType())
7942 return error(Loc0
, "insertvalue operand must be aggregate type");
7944 Type
*IndexedType
= ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
7946 return error(Loc0
, "invalid indices for insertvalue");
7947 if (IndexedType
!= Val1
->getType())
7948 return error(Loc1
, "insertvalue operand and field disagree in type: '" +
7949 getTypeString(Val1
->getType()) + "' instead of '" +
7950 getTypeString(IndexedType
) + "'");
7951 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
);
7952 return AteExtraComma
? InstExtraComma
: InstNormal
;
7955 //===----------------------------------------------------------------------===//
7956 // Embedded metadata.
7957 //===----------------------------------------------------------------------===//
7959 /// parseMDNodeVector
7960 /// ::= { Element (',' Element)* }
7962 /// ::= 'null' | TypeAndValue
7963 bool LLParser::parseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
7964 if (parseToken(lltok::lbrace
, "expected '{' here"))
7967 // Check for an empty list.
7968 if (EatIfPresent(lltok::rbrace
))
7972 // Null is a special case since it is typeless.
7973 if (EatIfPresent(lltok::kw_null
)) {
7974 Elts
.push_back(nullptr);
7979 if (parseMetadata(MD
, nullptr))
7982 } while (EatIfPresent(lltok::comma
));
7984 return parseToken(lltok::rbrace
, "expected end of metadata node");
7987 //===----------------------------------------------------------------------===//
7988 // Use-list order directives.
7989 //===----------------------------------------------------------------------===//
7990 bool LLParser::sortUseListOrder(Value
*V
, ArrayRef
<unsigned> Indexes
,
7993 return error(Loc
, "value has no uses");
7995 unsigned NumUses
= 0;
7996 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
7997 for (const Use
&U
: V
->uses()) {
7998 if (++NumUses
> Indexes
.size())
8000 Order
[&U
] = Indexes
[NumUses
- 1];
8003 return error(Loc
, "value only has one use");
8004 if (Order
.size() != Indexes
.size() || NumUses
> Indexes
.size())
8006 "wrong number of indexes, expected " + Twine(V
->getNumUses()));
8008 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
8009 return Order
.lookup(&L
) < Order
.lookup(&R
);
8014 /// parseUseListOrderIndexes
8015 /// ::= '{' uint32 (',' uint32)+ '}'
8016 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl
<unsigned> &Indexes
) {
8017 SMLoc Loc
= Lex
.getLoc();
8018 if (parseToken(lltok::lbrace
, "expected '{' here"))
8020 if (Lex
.getKind() == lltok::rbrace
)
8021 return Lex
.Error("expected non-empty list of uselistorder indexes");
8023 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8024 // indexes should be distinct numbers in the range [0, size-1], and should
8026 unsigned Offset
= 0;
8028 bool IsOrdered
= true;
8029 assert(Indexes
.empty() && "Expected empty order vector");
8032 if (parseUInt32(Index
))
8035 // Update consistency checks.
8036 Offset
+= Index
- Indexes
.size();
8037 Max
= std::max(Max
, Index
);
8038 IsOrdered
&= Index
== Indexes
.size();
8040 Indexes
.push_back(Index
);
8041 } while (EatIfPresent(lltok::comma
));
8043 if (parseToken(lltok::rbrace
, "expected '}' here"))
8046 if (Indexes
.size() < 2)
8047 return error(Loc
, "expected >= 2 uselistorder indexes");
8048 if (Offset
!= 0 || Max
>= Indexes
.size())
8050 "expected distinct uselistorder indexes in range [0, size)");
8052 return error(Loc
, "expected uselistorder indexes to change the order");
8057 /// parseUseListOrder
8058 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8059 bool LLParser::parseUseListOrder(PerFunctionState
*PFS
) {
8060 SMLoc Loc
= Lex
.getLoc();
8061 if (parseToken(lltok::kw_uselistorder
, "expected uselistorder directive"))
8065 SmallVector
<unsigned, 16> Indexes
;
8066 if (parseTypeAndValue(V
, PFS
) ||
8067 parseToken(lltok::comma
, "expected comma in uselistorder directive") ||
8068 parseUseListOrderIndexes(Indexes
))
8071 return sortUseListOrder(V
, Indexes
, Loc
);
8074 /// parseUseListOrderBB
8075 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8076 bool LLParser::parseUseListOrderBB() {
8077 assert(Lex
.getKind() == lltok::kw_uselistorder_bb
);
8078 SMLoc Loc
= Lex
.getLoc();
8082 SmallVector
<unsigned, 16> Indexes
;
8083 if (parseValID(Fn
, /*PFS=*/nullptr) ||
8084 parseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
8085 parseValID(Label
, /*PFS=*/nullptr) ||
8086 parseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
8087 parseUseListOrderIndexes(Indexes
))
8090 // Check the function.
8092 if (Fn
.Kind
== ValID::t_GlobalName
)
8093 GV
= M
->getNamedValue(Fn
.StrVal
);
8094 else if (Fn
.Kind
== ValID::t_GlobalID
)
8095 GV
= Fn
.UIntVal
< NumberedVals
.size() ? NumberedVals
[Fn
.UIntVal
] : nullptr;
8097 return error(Fn
.Loc
, "expected function name in uselistorder_bb");
8099 return error(Fn
.Loc
,
8100 "invalid function forward reference in uselistorder_bb");
8101 auto *F
= dyn_cast
<Function
>(GV
);
8103 return error(Fn
.Loc
, "expected function name in uselistorder_bb");
8104 if (F
->isDeclaration())
8105 return error(Fn
.Loc
, "invalid declaration in uselistorder_bb");
8107 // Check the basic block.
8108 if (Label
.Kind
== ValID::t_LocalID
)
8109 return error(Label
.Loc
, "invalid numeric label in uselistorder_bb");
8110 if (Label
.Kind
!= ValID::t_LocalName
)
8111 return error(Label
.Loc
, "expected basic block name in uselistorder_bb");
8112 Value
*V
= F
->getValueSymbolTable()->lookup(Label
.StrVal
);
8114 return error(Label
.Loc
, "invalid basic block in uselistorder_bb");
8115 if (!isa
<BasicBlock
>(V
))
8116 return error(Label
.Loc
, "expected basic block in uselistorder_bb");
8118 return sortUseListOrder(V
, Indexes
, Loc
);
8122 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8123 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8124 bool LLParser::parseModuleEntry(unsigned ID
) {
8125 assert(Lex
.getKind() == lltok::kw_module
);
8129 if (parseToken(lltok::colon
, "expected ':' here") ||
8130 parseToken(lltok::lparen
, "expected '(' here") ||
8131 parseToken(lltok::kw_path
, "expected 'path' here") ||
8132 parseToken(lltok::colon
, "expected ':' here") ||
8133 parseStringConstant(Path
) ||
8134 parseToken(lltok::comma
, "expected ',' here") ||
8135 parseToken(lltok::kw_hash
, "expected 'hash' here") ||
8136 parseToken(lltok::colon
, "expected ':' here") ||
8137 parseToken(lltok::lparen
, "expected '(' here"))
8141 if (parseUInt32(Hash
[0]) || parseToken(lltok::comma
, "expected ',' here") ||
8142 parseUInt32(Hash
[1]) || parseToken(lltok::comma
, "expected ',' here") ||
8143 parseUInt32(Hash
[2]) || parseToken(lltok::comma
, "expected ',' here") ||
8144 parseUInt32(Hash
[3]) || parseToken(lltok::comma
, "expected ',' here") ||
8145 parseUInt32(Hash
[4]))
8148 if (parseToken(lltok::rparen
, "expected ')' here") ||
8149 parseToken(lltok::rparen
, "expected ')' here"))
8152 auto ModuleEntry
= Index
->addModule(Path
, Hash
);
8153 ModuleIdMap
[ID
] = ModuleEntry
->first();
8159 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8160 bool LLParser::parseTypeIdEntry(unsigned ID
) {
8161 assert(Lex
.getKind() == lltok::kw_typeid
);
8165 if (parseToken(lltok::colon
, "expected ':' here") ||
8166 parseToken(lltok::lparen
, "expected '(' here") ||
8167 parseToken(lltok::kw_name
, "expected 'name' here") ||
8168 parseToken(lltok::colon
, "expected ':' here") ||
8169 parseStringConstant(Name
))
8172 TypeIdSummary
&TIS
= Index
->getOrInsertTypeIdSummary(Name
);
8173 if (parseToken(lltok::comma
, "expected ',' here") ||
8174 parseTypeIdSummary(TIS
) || parseToken(lltok::rparen
, "expected ')' here"))
8177 // Check if this ID was forward referenced, and if so, update the
8178 // corresponding GUIDs.
8179 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
8180 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
8181 for (auto TIDRef
: FwdRefTIDs
->second
) {
8182 assert(!*TIDRef
.first
&&
8183 "Forward referenced type id GUID expected to be 0");
8184 *TIDRef
.first
= GlobalValue::getGUID(Name
);
8186 ForwardRefTypeIds
.erase(FwdRefTIDs
);
8193 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8194 bool LLParser::parseTypeIdSummary(TypeIdSummary
&TIS
) {
8195 if (parseToken(lltok::kw_summary
, "expected 'summary' here") ||
8196 parseToken(lltok::colon
, "expected ':' here") ||
8197 parseToken(lltok::lparen
, "expected '(' here") ||
8198 parseTypeTestResolution(TIS
.TTRes
))
8201 if (EatIfPresent(lltok::comma
)) {
8202 // Expect optional wpdResolutions field
8203 if (parseOptionalWpdResolutions(TIS
.WPDRes
))
8207 if (parseToken(lltok::rparen
, "expected ')' here"))
8213 static ValueInfo EmptyVI
=
8214 ValueInfo(false, (GlobalValueSummaryMapTy::value_type
*)-8);
8216 /// TypeIdCompatibleVtableEntry
8217 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8218 /// TypeIdCompatibleVtableInfo
8220 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID
) {
8221 assert(Lex
.getKind() == lltok::kw_typeidCompatibleVTable
);
8225 if (parseToken(lltok::colon
, "expected ':' here") ||
8226 parseToken(lltok::lparen
, "expected '(' here") ||
8227 parseToken(lltok::kw_name
, "expected 'name' here") ||
8228 parseToken(lltok::colon
, "expected ':' here") ||
8229 parseStringConstant(Name
))
8232 TypeIdCompatibleVtableInfo
&TI
=
8233 Index
->getOrInsertTypeIdCompatibleVtableSummary(Name
);
8234 if (parseToken(lltok::comma
, "expected ',' here") ||
8235 parseToken(lltok::kw_summary
, "expected 'summary' here") ||
8236 parseToken(lltok::colon
, "expected ':' here") ||
8237 parseToken(lltok::lparen
, "expected '(' here"))
8240 IdToIndexMapType IdToIndexMap
;
8241 // parse each call edge
8244 if (parseToken(lltok::lparen
, "expected '(' here") ||
8245 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
8246 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(Offset
) ||
8247 parseToken(lltok::comma
, "expected ',' here"))
8250 LocTy Loc
= Lex
.getLoc();
8253 if (parseGVReference(VI
, GVId
))
8256 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8257 // forward reference. We will save the location of the ValueInfo needing an
8258 // update, but can only do so once the std::vector is finalized.
8260 IdToIndexMap
[GVId
].push_back(std::make_pair(TI
.size(), Loc
));
8261 TI
.push_back({Offset
, VI
});
8263 if (parseToken(lltok::rparen
, "expected ')' in call"))
8265 } while (EatIfPresent(lltok::comma
));
8267 // Now that the TI vector is finalized, it is safe to save the locations
8268 // of any forward GV references that need updating later.
8269 for (auto I
: IdToIndexMap
) {
8270 auto &Infos
= ForwardRefValueInfos
[I
.first
];
8271 for (auto P
: I
.second
) {
8272 assert(TI
[P
.first
].VTableVI
== EmptyVI
&&
8273 "Forward referenced ValueInfo expected to be empty");
8274 Infos
.emplace_back(&TI
[P
.first
].VTableVI
, P
.second
);
8278 if (parseToken(lltok::rparen
, "expected ')' here") ||
8279 parseToken(lltok::rparen
, "expected ')' here"))
8282 // Check if this ID was forward referenced, and if so, update the
8283 // corresponding GUIDs.
8284 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
8285 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
8286 for (auto TIDRef
: FwdRefTIDs
->second
) {
8287 assert(!*TIDRef
.first
&&
8288 "Forward referenced type id GUID expected to be 0");
8289 *TIDRef
.first
= GlobalValue::getGUID(Name
);
8291 ForwardRefTypeIds
.erase(FwdRefTIDs
);
8297 /// TypeTestResolution
8298 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
8299 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8300 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8301 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8302 /// [',' 'inlinesBits' ':' UInt64]? ')'
8303 bool LLParser::parseTypeTestResolution(TypeTestResolution
&TTRes
) {
8304 if (parseToken(lltok::kw_typeTestRes
, "expected 'typeTestRes' 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"))
8311 switch (Lex
.getKind()) {
8312 case lltok::kw_unknown
:
8313 TTRes
.TheKind
= TypeTestResolution::Unknown
;
8315 case lltok::kw_unsat
:
8316 TTRes
.TheKind
= TypeTestResolution::Unsat
;
8318 case lltok::kw_byteArray
:
8319 TTRes
.TheKind
= TypeTestResolution::ByteArray
;
8321 case lltok::kw_inline
:
8322 TTRes
.TheKind
= TypeTestResolution::Inline
;
8324 case lltok::kw_single
:
8325 TTRes
.TheKind
= TypeTestResolution::Single
;
8327 case lltok::kw_allOnes
:
8328 TTRes
.TheKind
= TypeTestResolution::AllOnes
;
8331 return error(Lex
.getLoc(), "unexpected TypeTestResolution kind");
8335 if (parseToken(lltok::comma
, "expected ',' here") ||
8336 parseToken(lltok::kw_sizeM1BitWidth
, "expected 'sizeM1BitWidth' here") ||
8337 parseToken(lltok::colon
, "expected ':' here") ||
8338 parseUInt32(TTRes
.SizeM1BitWidth
))
8341 // parse optional fields
8342 while (EatIfPresent(lltok::comma
)) {
8343 switch (Lex
.getKind()) {
8344 case lltok::kw_alignLog2
:
8346 if (parseToken(lltok::colon
, "expected ':'") ||
8347 parseUInt64(TTRes
.AlignLog2
))
8350 case lltok::kw_sizeM1
:
8352 if (parseToken(lltok::colon
, "expected ':'") || parseUInt64(TTRes
.SizeM1
))
8355 case lltok::kw_bitMask
: {
8358 if (parseToken(lltok::colon
, "expected ':'") || parseUInt32(Val
))
8360 assert(Val
<= 0xff);
8361 TTRes
.BitMask
= (uint8_t)Val
;
8364 case lltok::kw_inlineBits
:
8366 if (parseToken(lltok::colon
, "expected ':'") ||
8367 parseUInt64(TTRes
.InlineBits
))
8371 return error(Lex
.getLoc(), "expected optional TypeTestResolution field");
8375 if (parseToken(lltok::rparen
, "expected ')' here"))
8381 /// OptionalWpdResolutions
8382 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8383 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8384 bool LLParser::parseOptionalWpdResolutions(
8385 std::map
<uint64_t, WholeProgramDevirtResolution
> &WPDResMap
) {
8386 if (parseToken(lltok::kw_wpdResolutions
, "expected 'wpdResolutions' here") ||
8387 parseToken(lltok::colon
, "expected ':' here") ||
8388 parseToken(lltok::lparen
, "expected '(' here"))
8393 WholeProgramDevirtResolution WPDRes
;
8394 if (parseToken(lltok::lparen
, "expected '(' here") ||
8395 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
8396 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(Offset
) ||
8397 parseToken(lltok::comma
, "expected ',' here") || parseWpdRes(WPDRes
) ||
8398 parseToken(lltok::rparen
, "expected ')' here"))
8400 WPDResMap
[Offset
] = WPDRes
;
8401 } while (EatIfPresent(lltok::comma
));
8403 if (parseToken(lltok::rparen
, "expected ')' here"))
8410 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8411 /// [',' OptionalResByArg]? ')'
8412 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8413 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
8414 /// [',' OptionalResByArg]? ')'
8415 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8416 /// [',' OptionalResByArg]? ')'
8417 bool LLParser::parseWpdRes(WholeProgramDevirtResolution
&WPDRes
) {
8418 if (parseToken(lltok::kw_wpdRes
, "expected 'wpdRes' here") ||
8419 parseToken(lltok::colon
, "expected ':' here") ||
8420 parseToken(lltok::lparen
, "expected '(' here") ||
8421 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
8422 parseToken(lltok::colon
, "expected ':' here"))
8425 switch (Lex
.getKind()) {
8426 case lltok::kw_indir
:
8427 WPDRes
.TheKind
= WholeProgramDevirtResolution::Indir
;
8429 case lltok::kw_singleImpl
:
8430 WPDRes
.TheKind
= WholeProgramDevirtResolution::SingleImpl
;
8432 case lltok::kw_branchFunnel
:
8433 WPDRes
.TheKind
= WholeProgramDevirtResolution::BranchFunnel
;
8436 return error(Lex
.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8440 // parse optional fields
8441 while (EatIfPresent(lltok::comma
)) {
8442 switch (Lex
.getKind()) {
8443 case lltok::kw_singleImplName
:
8445 if (parseToken(lltok::colon
, "expected ':' here") ||
8446 parseStringConstant(WPDRes
.SingleImplName
))
8449 case lltok::kw_resByArg
:
8450 if (parseOptionalResByArg(WPDRes
.ResByArg
))
8454 return error(Lex
.getLoc(),
8455 "expected optional WholeProgramDevirtResolution field");
8459 if (parseToken(lltok::rparen
, "expected ')' here"))
8465 /// OptionalResByArg
8466 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8467 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8468 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8469 /// 'virtualConstProp' )
8470 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8471 /// [',' 'bit' ':' UInt32]? ')'
8472 bool LLParser::parseOptionalResByArg(
8473 std::map
<std::vector
<uint64_t>, WholeProgramDevirtResolution::ByArg
>
8475 if (parseToken(lltok::kw_resByArg
, "expected 'resByArg' here") ||
8476 parseToken(lltok::colon
, "expected ':' here") ||
8477 parseToken(lltok::lparen
, "expected '(' here"))
8481 std::vector
<uint64_t> Args
;
8482 if (parseArgs(Args
) || parseToken(lltok::comma
, "expected ',' here") ||
8483 parseToken(lltok::kw_byArg
, "expected 'byArg here") ||
8484 parseToken(lltok::colon
, "expected ':' here") ||
8485 parseToken(lltok::lparen
, "expected '(' here") ||
8486 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
8487 parseToken(lltok::colon
, "expected ':' here"))
8490 WholeProgramDevirtResolution::ByArg ByArg
;
8491 switch (Lex
.getKind()) {
8492 case lltok::kw_indir
:
8493 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::Indir
;
8495 case lltok::kw_uniformRetVal
:
8496 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniformRetVal
;
8498 case lltok::kw_uniqueRetVal
:
8499 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniqueRetVal
;
8501 case lltok::kw_virtualConstProp
:
8502 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::VirtualConstProp
;
8505 return error(Lex
.getLoc(),
8506 "unexpected WholeProgramDevirtResolution::ByArg kind");
8510 // parse optional fields
8511 while (EatIfPresent(lltok::comma
)) {
8512 switch (Lex
.getKind()) {
8513 case lltok::kw_info
:
8515 if (parseToken(lltok::colon
, "expected ':' here") ||
8516 parseUInt64(ByArg
.Info
))
8519 case lltok::kw_byte
:
8521 if (parseToken(lltok::colon
, "expected ':' here") ||
8522 parseUInt32(ByArg
.Byte
))
8527 if (parseToken(lltok::colon
, "expected ':' here") ||
8528 parseUInt32(ByArg
.Bit
))
8532 return error(Lex
.getLoc(),
8533 "expected optional whole program devirt field");
8537 if (parseToken(lltok::rparen
, "expected ')' here"))
8540 ResByArg
[Args
] = ByArg
;
8541 } while (EatIfPresent(lltok::comma
));
8543 if (parseToken(lltok::rparen
, "expected ')' here"))
8549 /// OptionalResByArg
8550 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8551 bool LLParser::parseArgs(std::vector
<uint64_t> &Args
) {
8552 if (parseToken(lltok::kw_args
, "expected 'args' here") ||
8553 parseToken(lltok::colon
, "expected ':' here") ||
8554 parseToken(lltok::lparen
, "expected '(' here"))
8559 if (parseUInt64(Val
))
8561 Args
.push_back(Val
);
8562 } while (EatIfPresent(lltok::comma
));
8564 if (parseToken(lltok::rparen
, "expected ')' here"))
8570 static const auto FwdVIRef
= (GlobalValueSummaryMapTy::value_type
*)-8;
8572 static void resolveFwdRef(ValueInfo
*Fwd
, ValueInfo
&Resolved
) {
8573 bool ReadOnly
= Fwd
->isReadOnly();
8574 bool WriteOnly
= Fwd
->isWriteOnly();
8575 assert(!(ReadOnly
&& WriteOnly
));
8580 Fwd
->setWriteOnly();
8583 /// Stores the given Name/GUID and associated summary into the Index.
8584 /// Also updates any forward references to the associated entry ID.
8585 void LLParser::addGlobalValueToIndex(
8586 std::string Name
, GlobalValue::GUID GUID
, GlobalValue::LinkageTypes Linkage
,
8587 unsigned ID
, std::unique_ptr
<GlobalValueSummary
> Summary
) {
8588 // First create the ValueInfo utilizing the Name or GUID.
8591 assert(Name
.empty());
8592 VI
= Index
->getOrInsertValueInfo(GUID
);
8594 assert(!Name
.empty());
8596 auto *GV
= M
->getNamedValue(Name
);
8598 VI
= Index
->getOrInsertValueInfo(GV
);
8601 (!GlobalValue::isLocalLinkage(Linkage
) || !SourceFileName
.empty()) &&
8602 "Need a source_filename to compute GUID for local");
8603 GUID
= GlobalValue::getGUID(
8604 GlobalValue::getGlobalIdentifier(Name
, Linkage
, SourceFileName
));
8605 VI
= Index
->getOrInsertValueInfo(GUID
, Index
->saveString(Name
));
8609 // Resolve forward references from calls/refs
8610 auto FwdRefVIs
= ForwardRefValueInfos
.find(ID
);
8611 if (FwdRefVIs
!= ForwardRefValueInfos
.end()) {
8612 for (auto VIRef
: FwdRefVIs
->second
) {
8613 assert(VIRef
.first
->getRef() == FwdVIRef
&&
8614 "Forward referenced ValueInfo expected to be empty");
8615 resolveFwdRef(VIRef
.first
, VI
);
8617 ForwardRefValueInfos
.erase(FwdRefVIs
);
8620 // Resolve forward references from aliases
8621 auto FwdRefAliasees
= ForwardRefAliasees
.find(ID
);
8622 if (FwdRefAliasees
!= ForwardRefAliasees
.end()) {
8623 for (auto AliaseeRef
: FwdRefAliasees
->second
) {
8624 assert(!AliaseeRef
.first
->hasAliasee() &&
8625 "Forward referencing alias already has aliasee");
8626 assert(Summary
&& "Aliasee must be a definition");
8627 AliaseeRef
.first
->setAliasee(VI
, Summary
.get());
8629 ForwardRefAliasees
.erase(FwdRefAliasees
);
8632 // Add the summary if one was provided.
8634 Index
->addGlobalValueSummary(VI
, std::move(Summary
));
8636 // Save the associated ValueInfo for use in later references by ID.
8637 if (ID
== NumberedValueInfos
.size())
8638 NumberedValueInfos
.push_back(VI
);
8640 // Handle non-continuous numbers (to make test simplification easier).
8641 if (ID
> NumberedValueInfos
.size())
8642 NumberedValueInfos
.resize(ID
+ 1);
8643 NumberedValueInfos
[ID
] = VI
;
8647 /// parseSummaryIndexFlags
8648 /// ::= 'flags' ':' UInt64
8649 bool LLParser::parseSummaryIndexFlags() {
8650 assert(Lex
.getKind() == lltok::kw_flags
);
8653 if (parseToken(lltok::colon
, "expected ':' here"))
8656 if (parseUInt64(Flags
))
8659 Index
->setFlags(Flags
);
8664 /// ::= 'blockcount' ':' UInt64
8665 bool LLParser::parseBlockCount() {
8666 assert(Lex
.getKind() == lltok::kw_blockcount
);
8669 if (parseToken(lltok::colon
, "expected ':' here"))
8671 uint64_t BlockCount
;
8672 if (parseUInt64(BlockCount
))
8675 Index
->setBlockCount(BlockCount
);
8680 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8681 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8682 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8683 bool LLParser::parseGVEntry(unsigned ID
) {
8684 assert(Lex
.getKind() == lltok::kw_gv
);
8687 if (parseToken(lltok::colon
, "expected ':' here") ||
8688 parseToken(lltok::lparen
, "expected '(' here"))
8692 GlobalValue::GUID GUID
= 0;
8693 switch (Lex
.getKind()) {
8694 case lltok::kw_name
:
8696 if (parseToken(lltok::colon
, "expected ':' here") ||
8697 parseStringConstant(Name
))
8699 // Can't create GUID/ValueInfo until we have the linkage.
8701 case lltok::kw_guid
:
8703 if (parseToken(lltok::colon
, "expected ':' here") || parseUInt64(GUID
))
8707 return error(Lex
.getLoc(), "expected name or guid tag");
8710 if (!EatIfPresent(lltok::comma
)) {
8711 // No summaries. Wrap up.
8712 if (parseToken(lltok::rparen
, "expected ')' here"))
8714 // This was created for a call to an external or indirect target.
8715 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8716 // created for indirect calls with VP. A Name with no GUID came from
8717 // an external definition. We pass ExternalLinkage since that is only
8718 // used when the GUID must be computed from Name, and in that case
8719 // the symbol must have external linkage.
8720 addGlobalValueToIndex(Name
, GUID
, GlobalValue::ExternalLinkage
, ID
,
8725 // Have a list of summaries
8726 if (parseToken(lltok::kw_summaries
, "expected 'summaries' here") ||
8727 parseToken(lltok::colon
, "expected ':' here") ||
8728 parseToken(lltok::lparen
, "expected '(' here"))
8731 switch (Lex
.getKind()) {
8732 case lltok::kw_function
:
8733 if (parseFunctionSummary(Name
, GUID
, ID
))
8736 case lltok::kw_variable
:
8737 if (parseVariableSummary(Name
, GUID
, ID
))
8740 case lltok::kw_alias
:
8741 if (parseAliasSummary(Name
, GUID
, ID
))
8745 return error(Lex
.getLoc(), "expected summary type");
8747 } while (EatIfPresent(lltok::comma
));
8749 if (parseToken(lltok::rparen
, "expected ')' here") ||
8750 parseToken(lltok::rparen
, "expected ')' here"))
8757 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8758 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8759 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8760 /// [',' OptionalRefs]? ')'
8761 bool LLParser::parseFunctionSummary(std::string Name
, GlobalValue::GUID GUID
,
8763 assert(Lex
.getKind() == lltok::kw_function
);
8766 StringRef ModulePath
;
8767 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8768 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8769 /*NotEligibleToImport=*/false,
8770 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8772 std::vector
<FunctionSummary::EdgeTy
> Calls
;
8773 FunctionSummary::TypeIdInfo TypeIdInfo
;
8774 std::vector
<FunctionSummary::ParamAccess
> ParamAccesses
;
8775 std::vector
<ValueInfo
> Refs
;
8776 std::vector
<CallsiteInfo
> Callsites
;
8777 std::vector
<AllocInfo
> Allocs
;
8778 // Default is all-zeros (conservative values).
8779 FunctionSummary::FFlags FFlags
= {};
8780 if (parseToken(lltok::colon
, "expected ':' here") ||
8781 parseToken(lltok::lparen
, "expected '(' here") ||
8782 parseModuleReference(ModulePath
) ||
8783 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8784 parseToken(lltok::comma
, "expected ',' here") ||
8785 parseToken(lltok::kw_insts
, "expected 'insts' here") ||
8786 parseToken(lltok::colon
, "expected ':' here") || parseUInt32(InstCount
))
8789 // parse optional fields
8790 while (EatIfPresent(lltok::comma
)) {
8791 switch (Lex
.getKind()) {
8792 case lltok::kw_funcFlags
:
8793 if (parseOptionalFFlags(FFlags
))
8796 case lltok::kw_calls
:
8797 if (parseOptionalCalls(Calls
))
8800 case lltok::kw_typeIdInfo
:
8801 if (parseOptionalTypeIdInfo(TypeIdInfo
))
8804 case lltok::kw_refs
:
8805 if (parseOptionalRefs(Refs
))
8808 case lltok::kw_params
:
8809 if (parseOptionalParamAccesses(ParamAccesses
))
8812 case lltok::kw_allocs
:
8813 if (parseOptionalAllocs(Allocs
))
8816 case lltok::kw_callsites
:
8817 if (parseOptionalCallsites(Callsites
))
8821 return error(Lex
.getLoc(), "expected optional function summary field");
8825 if (parseToken(lltok::rparen
, "expected ')' here"))
8828 auto FS
= std::make_unique
<FunctionSummary
>(
8829 GVFlags
, InstCount
, FFlags
, /*EntryCount=*/0, std::move(Refs
),
8830 std::move(Calls
), std::move(TypeIdInfo
.TypeTests
),
8831 std::move(TypeIdInfo
.TypeTestAssumeVCalls
),
8832 std::move(TypeIdInfo
.TypeCheckedLoadVCalls
),
8833 std::move(TypeIdInfo
.TypeTestAssumeConstVCalls
),
8834 std::move(TypeIdInfo
.TypeCheckedLoadConstVCalls
),
8835 std::move(ParamAccesses
), std::move(Callsites
), std::move(Allocs
));
8837 FS
->setModulePath(ModulePath
);
8839 addGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8846 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8847 /// [',' OptionalRefs]? ')'
8848 bool LLParser::parseVariableSummary(std::string Name
, GlobalValue::GUID GUID
,
8850 assert(Lex
.getKind() == lltok::kw_variable
);
8853 StringRef ModulePath
;
8854 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8855 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8856 /*NotEligibleToImport=*/false,
8857 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8858 GlobalVarSummary::GVarFlags
GVarFlags(/*ReadOnly*/ false,
8859 /* WriteOnly */ false,
8860 /* Constant */ false,
8861 GlobalObject::VCallVisibilityPublic
);
8862 std::vector
<ValueInfo
> Refs
;
8863 VTableFuncList VTableFuncs
;
8864 if (parseToken(lltok::colon
, "expected ':' here") ||
8865 parseToken(lltok::lparen
, "expected '(' here") ||
8866 parseModuleReference(ModulePath
) ||
8867 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8868 parseToken(lltok::comma
, "expected ',' here") ||
8869 parseGVarFlags(GVarFlags
))
8872 // parse optional fields
8873 while (EatIfPresent(lltok::comma
)) {
8874 switch (Lex
.getKind()) {
8875 case lltok::kw_vTableFuncs
:
8876 if (parseOptionalVTableFuncs(VTableFuncs
))
8879 case lltok::kw_refs
:
8880 if (parseOptionalRefs(Refs
))
8884 return error(Lex
.getLoc(), "expected optional variable summary field");
8888 if (parseToken(lltok::rparen
, "expected ')' here"))
8892 std::make_unique
<GlobalVarSummary
>(GVFlags
, GVarFlags
, std::move(Refs
));
8894 GS
->setModulePath(ModulePath
);
8895 GS
->setVTableFuncs(std::move(VTableFuncs
));
8897 addGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8904 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8905 /// 'aliasee' ':' GVReference ')'
8906 bool LLParser::parseAliasSummary(std::string Name
, GlobalValue::GUID GUID
,
8908 assert(Lex
.getKind() == lltok::kw_alias
);
8909 LocTy Loc
= Lex
.getLoc();
8912 StringRef ModulePath
;
8913 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8914 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8915 /*NotEligibleToImport=*/false,
8916 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8917 if (parseToken(lltok::colon
, "expected ':' here") ||
8918 parseToken(lltok::lparen
, "expected '(' here") ||
8919 parseModuleReference(ModulePath
) ||
8920 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8921 parseToken(lltok::comma
, "expected ',' here") ||
8922 parseToken(lltok::kw_aliasee
, "expected 'aliasee' here") ||
8923 parseToken(lltok::colon
, "expected ':' here"))
8926 ValueInfo AliaseeVI
;
8928 if (parseGVReference(AliaseeVI
, GVId
))
8931 if (parseToken(lltok::rparen
, "expected ')' here"))
8934 auto AS
= std::make_unique
<AliasSummary
>(GVFlags
);
8936 AS
->setModulePath(ModulePath
);
8938 // Record forward reference if the aliasee is not parsed yet.
8939 if (AliaseeVI
.getRef() == FwdVIRef
) {
8940 ForwardRefAliasees
[GVId
].emplace_back(AS
.get(), Loc
);
8942 auto Summary
= Index
->findSummaryInModule(AliaseeVI
, ModulePath
);
8943 assert(Summary
&& "Aliasee must be a definition");
8944 AS
->setAliasee(AliaseeVI
, Summary
);
8947 addGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8955 bool LLParser::parseFlag(unsigned &Val
) {
8956 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
8957 return tokError("expected integer");
8958 Val
= (unsigned)Lex
.getAPSIntVal().getBoolValue();
8964 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8965 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8966 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8967 /// [',' 'noInline' ':' Flag]? ')'
8968 /// [',' 'alwaysInline' ':' Flag]? ')'
8969 /// [',' 'noUnwind' ':' Flag]? ')'
8970 /// [',' 'mayThrow' ':' Flag]? ')'
8971 /// [',' 'hasUnknownCall' ':' Flag]? ')'
8972 /// [',' 'mustBeUnreachable' ':' Flag]? ')'
8974 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags
&FFlags
) {
8975 assert(Lex
.getKind() == lltok::kw_funcFlags
);
8978 if (parseToken(lltok::colon
, "expected ':' in funcFlags") ||
8979 parseToken(lltok::lparen
, "expected '(' in funcFlags"))
8984 switch (Lex
.getKind()) {
8985 case lltok::kw_readNone
:
8987 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8989 FFlags
.ReadNone
= Val
;
8991 case lltok::kw_readOnly
:
8993 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8995 FFlags
.ReadOnly
= Val
;
8997 case lltok::kw_noRecurse
:
8999 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9001 FFlags
.NoRecurse
= Val
;
9003 case lltok::kw_returnDoesNotAlias
:
9005 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9007 FFlags
.ReturnDoesNotAlias
= Val
;
9009 case lltok::kw_noInline
:
9011 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9013 FFlags
.NoInline
= Val
;
9015 case lltok::kw_alwaysInline
:
9017 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9019 FFlags
.AlwaysInline
= Val
;
9021 case lltok::kw_noUnwind
:
9023 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9025 FFlags
.NoUnwind
= Val
;
9027 case lltok::kw_mayThrow
:
9029 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9031 FFlags
.MayThrow
= Val
;
9033 case lltok::kw_hasUnknownCall
:
9035 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9037 FFlags
.HasUnknownCall
= Val
;
9039 case lltok::kw_mustBeUnreachable
:
9041 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9043 FFlags
.MustBeUnreachable
= Val
;
9046 return error(Lex
.getLoc(), "expected function flag type");
9048 } while (EatIfPresent(lltok::comma
));
9050 if (parseToken(lltok::rparen
, "expected ')' in funcFlags"))
9057 /// := 'calls' ':' '(' Call [',' Call]* ')'
9058 /// Call ::= '(' 'callee' ':' GVReference
9059 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
9060 bool LLParser::parseOptionalCalls(std::vector
<FunctionSummary::EdgeTy
> &Calls
) {
9061 assert(Lex
.getKind() == lltok::kw_calls
);
9064 if (parseToken(lltok::colon
, "expected ':' in calls") ||
9065 parseToken(lltok::lparen
, "expected '(' in calls"))
9068 IdToIndexMapType IdToIndexMap
;
9069 // parse each call edge
9072 if (parseToken(lltok::lparen
, "expected '(' in call") ||
9073 parseToken(lltok::kw_callee
, "expected 'callee' in call") ||
9074 parseToken(lltok::colon
, "expected ':'"))
9077 LocTy Loc
= Lex
.getLoc();
9079 if (parseGVReference(VI
, GVId
))
9082 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
9084 if (EatIfPresent(lltok::comma
)) {
9085 // Expect either hotness or relbf
9086 if (EatIfPresent(lltok::kw_hotness
)) {
9087 if (parseToken(lltok::colon
, "expected ':'") || parseHotness(Hotness
))
9090 if (parseToken(lltok::kw_relbf
, "expected relbf") ||
9091 parseToken(lltok::colon
, "expected ':'") || parseUInt32(RelBF
))
9095 // Keep track of the Call array index needing a forward reference.
9096 // We will save the location of the ValueInfo needing an update, but
9097 // can only do so once the std::vector is finalized.
9098 if (VI
.getRef() == FwdVIRef
)
9099 IdToIndexMap
[GVId
].push_back(std::make_pair(Calls
.size(), Loc
));
9100 Calls
.push_back(FunctionSummary::EdgeTy
{VI
, CalleeInfo(Hotness
, RelBF
)});
9102 if (parseToken(lltok::rparen
, "expected ')' in call"))
9104 } while (EatIfPresent(lltok::comma
));
9106 // Now that the Calls vector is finalized, it is safe to save the locations
9107 // of any forward GV references that need updating later.
9108 for (auto I
: IdToIndexMap
) {
9109 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9110 for (auto P
: I
.second
) {
9111 assert(Calls
[P
.first
].first
.getRef() == FwdVIRef
&&
9112 "Forward referenced ValueInfo expected to be empty");
9113 Infos
.emplace_back(&Calls
[P
.first
].first
, P
.second
);
9117 if (parseToken(lltok::rparen
, "expected ')' in calls"))
9124 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
9125 bool LLParser::parseHotness(CalleeInfo::HotnessType
&Hotness
) {
9126 switch (Lex
.getKind()) {
9127 case lltok::kw_unknown
:
9128 Hotness
= CalleeInfo::HotnessType::Unknown
;
9130 case lltok::kw_cold
:
9131 Hotness
= CalleeInfo::HotnessType::Cold
;
9133 case lltok::kw_none
:
9134 Hotness
= CalleeInfo::HotnessType::None
;
9137 Hotness
= CalleeInfo::HotnessType::Hot
;
9139 case lltok::kw_critical
:
9140 Hotness
= CalleeInfo::HotnessType::Critical
;
9143 return error(Lex
.getLoc(), "invalid call edge hotness");
9149 /// OptionalVTableFuncs
9150 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9151 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9152 bool LLParser::parseOptionalVTableFuncs(VTableFuncList
&VTableFuncs
) {
9153 assert(Lex
.getKind() == lltok::kw_vTableFuncs
);
9156 if (parseToken(lltok::colon
, "expected ':' in vTableFuncs") ||
9157 parseToken(lltok::lparen
, "expected '(' in vTableFuncs"))
9160 IdToIndexMapType IdToIndexMap
;
9161 // parse each virtual function pair
9164 if (parseToken(lltok::lparen
, "expected '(' in vTableFunc") ||
9165 parseToken(lltok::kw_virtFunc
, "expected 'callee' in vTableFunc") ||
9166 parseToken(lltok::colon
, "expected ':'"))
9169 LocTy Loc
= Lex
.getLoc();
9171 if (parseGVReference(VI
, GVId
))
9175 if (parseToken(lltok::comma
, "expected comma") ||
9176 parseToken(lltok::kw_offset
, "expected offset") ||
9177 parseToken(lltok::colon
, "expected ':'") || parseUInt64(Offset
))
9180 // Keep track of the VTableFuncs array index needing a forward reference.
9181 // We will save the location of the ValueInfo needing an update, but
9182 // can only do so once the std::vector is finalized.
9184 IdToIndexMap
[GVId
].push_back(std::make_pair(VTableFuncs
.size(), Loc
));
9185 VTableFuncs
.push_back({VI
, Offset
});
9187 if (parseToken(lltok::rparen
, "expected ')' in vTableFunc"))
9189 } while (EatIfPresent(lltok::comma
));
9191 // Now that the VTableFuncs vector is finalized, it is safe to save the
9192 // locations of any forward GV references that need updating later.
9193 for (auto I
: IdToIndexMap
) {
9194 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9195 for (auto P
: I
.second
) {
9196 assert(VTableFuncs
[P
.first
].FuncVI
== EmptyVI
&&
9197 "Forward referenced ValueInfo expected to be empty");
9198 Infos
.emplace_back(&VTableFuncs
[P
.first
].FuncVI
, P
.second
);
9202 if (parseToken(lltok::rparen
, "expected ')' in vTableFuncs"))
9208 /// ParamNo := 'param' ':' UInt64
9209 bool LLParser::parseParamNo(uint64_t &ParamNo
) {
9210 if (parseToken(lltok::kw_param
, "expected 'param' here") ||
9211 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(ParamNo
))
9216 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9217 bool LLParser::parseParamAccessOffset(ConstantRange
&Range
) {
9220 auto ParseAPSInt
= [&](APSInt
&Val
) {
9221 if (Lex
.getKind() != lltok::APSInt
)
9222 return tokError("expected integer");
9223 Val
= Lex
.getAPSIntVal();
9224 Val
= Val
.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth
);
9225 Val
.setIsSigned(true);
9229 if (parseToken(lltok::kw_offset
, "expected 'offset' here") ||
9230 parseToken(lltok::colon
, "expected ':' here") ||
9231 parseToken(lltok::lsquare
, "expected '[' here") || ParseAPSInt(Lower
) ||
9232 parseToken(lltok::comma
, "expected ',' here") || ParseAPSInt(Upper
) ||
9233 parseToken(lltok::rsquare
, "expected ']' here"))
9238 (Lower
== Upper
&& !Lower
.isMaxValue())
9239 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth
)
9240 : ConstantRange(Lower
, Upper
);
9246 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9247 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call
&Call
,
9248 IdLocListType
&IdLocList
) {
9249 if (parseToken(lltok::lparen
, "expected '(' here") ||
9250 parseToken(lltok::kw_callee
, "expected 'callee' here") ||
9251 parseToken(lltok::colon
, "expected ':' here"))
9256 LocTy Loc
= Lex
.getLoc();
9257 if (parseGVReference(VI
, GVId
))
9261 IdLocList
.emplace_back(GVId
, Loc
);
9263 if (parseToken(lltok::comma
, "expected ',' here") ||
9264 parseParamNo(Call
.ParamNo
) ||
9265 parseToken(lltok::comma
, "expected ',' here") ||
9266 parseParamAccessOffset(Call
.Offsets
))
9269 if (parseToken(lltok::rparen
, "expected ')' here"))
9276 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9277 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9278 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess
&Param
,
9279 IdLocListType
&IdLocList
) {
9280 if (parseToken(lltok::lparen
, "expected '(' here") ||
9281 parseParamNo(Param
.ParamNo
) ||
9282 parseToken(lltok::comma
, "expected ',' here") ||
9283 parseParamAccessOffset(Param
.Use
))
9286 if (EatIfPresent(lltok::comma
)) {
9287 if (parseToken(lltok::kw_calls
, "expected 'calls' here") ||
9288 parseToken(lltok::colon
, "expected ':' here") ||
9289 parseToken(lltok::lparen
, "expected '(' here"))
9292 FunctionSummary::ParamAccess::Call Call
;
9293 if (parseParamAccessCall(Call
, IdLocList
))
9295 Param
.Calls
.push_back(Call
);
9296 } while (EatIfPresent(lltok::comma
));
9298 if (parseToken(lltok::rparen
, "expected ')' here"))
9302 if (parseToken(lltok::rparen
, "expected ')' here"))
9308 /// OptionalParamAccesses
9309 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9310 bool LLParser::parseOptionalParamAccesses(
9311 std::vector
<FunctionSummary::ParamAccess
> &Params
) {
9312 assert(Lex
.getKind() == lltok::kw_params
);
9315 if (parseToken(lltok::colon
, "expected ':' here") ||
9316 parseToken(lltok::lparen
, "expected '(' here"))
9319 IdLocListType VContexts
;
9320 size_t CallsNum
= 0;
9322 FunctionSummary::ParamAccess ParamAccess
;
9323 if (parseParamAccess(ParamAccess
, VContexts
))
9325 CallsNum
+= ParamAccess
.Calls
.size();
9326 assert(VContexts
.size() == CallsNum
);
9328 Params
.emplace_back(std::move(ParamAccess
));
9329 } while (EatIfPresent(lltok::comma
));
9331 if (parseToken(lltok::rparen
, "expected ')' here"))
9334 // Now that the Params is finalized, it is safe to save the locations
9335 // of any forward GV references that need updating later.
9336 IdLocListType::const_iterator ItContext
= VContexts
.begin();
9337 for (auto &PA
: Params
) {
9338 for (auto &C
: PA
.Calls
) {
9339 if (C
.Callee
.getRef() == FwdVIRef
)
9340 ForwardRefValueInfos
[ItContext
->first
].emplace_back(&C
.Callee
,
9345 assert(ItContext
== VContexts
.end());
9351 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9352 bool LLParser::parseOptionalRefs(std::vector
<ValueInfo
> &Refs
) {
9353 assert(Lex
.getKind() == lltok::kw_refs
);
9356 if (parseToken(lltok::colon
, "expected ':' in refs") ||
9357 parseToken(lltok::lparen
, "expected '(' in refs"))
9360 struct ValueContext
{
9365 std::vector
<ValueContext
> VContexts
;
9366 // parse each ref edge
9369 VC
.Loc
= Lex
.getLoc();
9370 if (parseGVReference(VC
.VI
, VC
.GVId
))
9372 VContexts
.push_back(VC
);
9373 } while (EatIfPresent(lltok::comma
));
9375 // Sort value contexts so that ones with writeonly
9376 // and readonly ValueInfo are at the end of VContexts vector.
9377 // See FunctionSummary::specialRefCounts()
9378 llvm::sort(VContexts
, [](const ValueContext
&VC1
, const ValueContext
&VC2
) {
9379 return VC1
.VI
.getAccessSpecifier() < VC2
.VI
.getAccessSpecifier();
9382 IdToIndexMapType IdToIndexMap
;
9383 for (auto &VC
: VContexts
) {
9384 // Keep track of the Refs array index needing a forward reference.
9385 // We will save the location of the ValueInfo needing an update, but
9386 // can only do so once the std::vector is finalized.
9387 if (VC
.VI
.getRef() == FwdVIRef
)
9388 IdToIndexMap
[VC
.GVId
].push_back(std::make_pair(Refs
.size(), VC
.Loc
));
9389 Refs
.push_back(VC
.VI
);
9392 // Now that the Refs vector is finalized, it is safe to save the locations
9393 // of any forward GV references that need updating later.
9394 for (auto I
: IdToIndexMap
) {
9395 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9396 for (auto P
: I
.second
) {
9397 assert(Refs
[P
.first
].getRef() == FwdVIRef
&&
9398 "Forward referenced ValueInfo expected to be empty");
9399 Infos
.emplace_back(&Refs
[P
.first
], P
.second
);
9403 if (parseToken(lltok::rparen
, "expected ')' in refs"))
9409 /// OptionalTypeIdInfo
9410 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9411 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9412 /// [',' TypeCheckedLoadConstVCalls]? ')'
9413 bool LLParser::parseOptionalTypeIdInfo(
9414 FunctionSummary::TypeIdInfo
&TypeIdInfo
) {
9415 assert(Lex
.getKind() == lltok::kw_typeIdInfo
);
9418 if (parseToken(lltok::colon
, "expected ':' here") ||
9419 parseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
9423 switch (Lex
.getKind()) {
9424 case lltok::kw_typeTests
:
9425 if (parseTypeTests(TypeIdInfo
.TypeTests
))
9428 case lltok::kw_typeTestAssumeVCalls
:
9429 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls
,
9430 TypeIdInfo
.TypeTestAssumeVCalls
))
9433 case lltok::kw_typeCheckedLoadVCalls
:
9434 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls
,
9435 TypeIdInfo
.TypeCheckedLoadVCalls
))
9438 case lltok::kw_typeTestAssumeConstVCalls
:
9439 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls
,
9440 TypeIdInfo
.TypeTestAssumeConstVCalls
))
9443 case lltok::kw_typeCheckedLoadConstVCalls
:
9444 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls
,
9445 TypeIdInfo
.TypeCheckedLoadConstVCalls
))
9449 return error(Lex
.getLoc(), "invalid typeIdInfo list type");
9451 } while (EatIfPresent(lltok::comma
));
9453 if (parseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
9460 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9461 /// [',' (SummaryID | UInt64)]* ')'
9462 bool LLParser::parseTypeTests(std::vector
<GlobalValue::GUID
> &TypeTests
) {
9463 assert(Lex
.getKind() == lltok::kw_typeTests
);
9466 if (parseToken(lltok::colon
, "expected ':' here") ||
9467 parseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
9470 IdToIndexMapType IdToIndexMap
;
9472 GlobalValue::GUID GUID
= 0;
9473 if (Lex
.getKind() == lltok::SummaryID
) {
9474 unsigned ID
= Lex
.getUIntVal();
9475 LocTy Loc
= Lex
.getLoc();
9476 // Keep track of the TypeTests array index needing a forward reference.
9477 // We will save the location of the GUID needing an update, but
9478 // can only do so once the std::vector is finalized.
9479 IdToIndexMap
[ID
].push_back(std::make_pair(TypeTests
.size(), Loc
));
9481 } else if (parseUInt64(GUID
))
9483 TypeTests
.push_back(GUID
);
9484 } while (EatIfPresent(lltok::comma
));
9486 // Now that the TypeTests vector is finalized, it is safe to save the
9487 // locations of any forward GV references that need updating later.
9488 for (auto I
: IdToIndexMap
) {
9489 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9490 for (auto P
: I
.second
) {
9491 assert(TypeTests
[P
.first
] == 0 &&
9492 "Forward referenced type id GUID expected to be 0");
9493 Ids
.emplace_back(&TypeTests
[P
.first
], P
.second
);
9497 if (parseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
9504 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9505 bool LLParser::parseVFuncIdList(
9506 lltok::Kind Kind
, std::vector
<FunctionSummary::VFuncId
> &VFuncIdList
) {
9507 assert(Lex
.getKind() == Kind
);
9510 if (parseToken(lltok::colon
, "expected ':' here") ||
9511 parseToken(lltok::lparen
, "expected '(' here"))
9514 IdToIndexMapType IdToIndexMap
;
9516 FunctionSummary::VFuncId VFuncId
;
9517 if (parseVFuncId(VFuncId
, IdToIndexMap
, VFuncIdList
.size()))
9519 VFuncIdList
.push_back(VFuncId
);
9520 } while (EatIfPresent(lltok::comma
));
9522 if (parseToken(lltok::rparen
, "expected ')' here"))
9525 // Now that the VFuncIdList vector is finalized, it is safe to save the
9526 // locations of any forward GV references that need updating later.
9527 for (auto I
: IdToIndexMap
) {
9528 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9529 for (auto P
: I
.second
) {
9530 assert(VFuncIdList
[P
.first
].GUID
== 0 &&
9531 "Forward referenced type id GUID expected to be 0");
9532 Ids
.emplace_back(&VFuncIdList
[P
.first
].GUID
, P
.second
);
9540 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9541 bool LLParser::parseConstVCallList(
9543 std::vector
<FunctionSummary::ConstVCall
> &ConstVCallList
) {
9544 assert(Lex
.getKind() == Kind
);
9547 if (parseToken(lltok::colon
, "expected ':' here") ||
9548 parseToken(lltok::lparen
, "expected '(' here"))
9551 IdToIndexMapType IdToIndexMap
;
9553 FunctionSummary::ConstVCall ConstVCall
;
9554 if (parseConstVCall(ConstVCall
, IdToIndexMap
, ConstVCallList
.size()))
9556 ConstVCallList
.push_back(ConstVCall
);
9557 } while (EatIfPresent(lltok::comma
));
9559 if (parseToken(lltok::rparen
, "expected ')' here"))
9562 // Now that the ConstVCallList vector is finalized, it is safe to save the
9563 // locations of any forward GV references that need updating later.
9564 for (auto I
: IdToIndexMap
) {
9565 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9566 for (auto P
: I
.second
) {
9567 assert(ConstVCallList
[P
.first
].VFunc
.GUID
== 0 &&
9568 "Forward referenced type id GUID expected to be 0");
9569 Ids
.emplace_back(&ConstVCallList
[P
.first
].VFunc
.GUID
, P
.second
);
9577 /// ::= '(' VFuncId ',' Args ')'
9578 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall
&ConstVCall
,
9579 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
9580 if (parseToken(lltok::lparen
, "expected '(' here") ||
9581 parseVFuncId(ConstVCall
.VFunc
, IdToIndexMap
, Index
))
9584 if (EatIfPresent(lltok::comma
))
9585 if (parseArgs(ConstVCall
.Args
))
9588 if (parseToken(lltok::rparen
, "expected ')' here"))
9595 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9596 /// 'offset' ':' UInt64 ')'
9597 bool LLParser::parseVFuncId(FunctionSummary::VFuncId
&VFuncId
,
9598 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
9599 assert(Lex
.getKind() == lltok::kw_vFuncId
);
9602 if (parseToken(lltok::colon
, "expected ':' here") ||
9603 parseToken(lltok::lparen
, "expected '(' here"))
9606 if (Lex
.getKind() == lltok::SummaryID
) {
9608 unsigned ID
= Lex
.getUIntVal();
9609 LocTy Loc
= Lex
.getLoc();
9610 // Keep track of the array index needing a forward reference.
9611 // We will save the location of the GUID needing an update, but
9612 // can only do so once the caller's std::vector is finalized.
9613 IdToIndexMap
[ID
].push_back(std::make_pair(Index
, Loc
));
9615 } else if (parseToken(lltok::kw_guid
, "expected 'guid' here") ||
9616 parseToken(lltok::colon
, "expected ':' here") ||
9617 parseUInt64(VFuncId
.GUID
))
9620 if (parseToken(lltok::comma
, "expected ',' here") ||
9621 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
9622 parseToken(lltok::colon
, "expected ':' here") ||
9623 parseUInt64(VFuncId
.Offset
) ||
9624 parseToken(lltok::rparen
, "expected ')' here"))
9631 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9632 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9633 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9634 /// 'canAutoHide' ':' Flag ',' ')'
9635 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags
&GVFlags
) {
9636 assert(Lex
.getKind() == lltok::kw_flags
);
9639 if (parseToken(lltok::colon
, "expected ':' here") ||
9640 parseToken(lltok::lparen
, "expected '(' here"))
9645 switch (Lex
.getKind()) {
9646 case lltok::kw_linkage
:
9648 if (parseToken(lltok::colon
, "expected ':'"))
9651 GVFlags
.Linkage
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
9652 assert(HasLinkage
&& "Linkage not optional in summary entry");
9655 case lltok::kw_visibility
:
9657 if (parseToken(lltok::colon
, "expected ':'"))
9659 parseOptionalVisibility(Flag
);
9660 GVFlags
.Visibility
= Flag
;
9662 case lltok::kw_notEligibleToImport
:
9664 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9666 GVFlags
.NotEligibleToImport
= Flag
;
9668 case lltok::kw_live
:
9670 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9672 GVFlags
.Live
= Flag
;
9674 case lltok::kw_dsoLocal
:
9676 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9678 GVFlags
.DSOLocal
= Flag
;
9680 case lltok::kw_canAutoHide
:
9682 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9684 GVFlags
.CanAutoHide
= Flag
;
9687 return error(Lex
.getLoc(), "expected gv flag type");
9689 } while (EatIfPresent(lltok::comma
));
9691 if (parseToken(lltok::rparen
, "expected ')' here"))
9698 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9699 /// ',' 'writeonly' ':' Flag
9700 /// ',' 'constant' ':' Flag ')'
9701 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags
&GVarFlags
) {
9702 assert(Lex
.getKind() == lltok::kw_varFlags
);
9705 if (parseToken(lltok::colon
, "expected ':' here") ||
9706 parseToken(lltok::lparen
, "expected '(' here"))
9709 auto ParseRest
= [this](unsigned int &Val
) {
9711 if (parseToken(lltok::colon
, "expected ':'"))
9713 return parseFlag(Val
);
9718 switch (Lex
.getKind()) {
9719 case lltok::kw_readonly
:
9720 if (ParseRest(Flag
))
9722 GVarFlags
.MaybeReadOnly
= Flag
;
9724 case lltok::kw_writeonly
:
9725 if (ParseRest(Flag
))
9727 GVarFlags
.MaybeWriteOnly
= Flag
;
9729 case lltok::kw_constant
:
9730 if (ParseRest(Flag
))
9732 GVarFlags
.Constant
= Flag
;
9734 case lltok::kw_vcall_visibility
:
9735 if (ParseRest(Flag
))
9737 GVarFlags
.VCallVisibility
= Flag
;
9740 return error(Lex
.getLoc(), "expected gvar flag type");
9742 } while (EatIfPresent(lltok::comma
));
9743 return parseToken(lltok::rparen
, "expected ')' here");
9747 /// ::= 'module' ':' UInt
9748 bool LLParser::parseModuleReference(StringRef
&ModulePath
) {
9750 if (parseToken(lltok::kw_module
, "expected 'module' here") ||
9751 parseToken(lltok::colon
, "expected ':' here") ||
9752 parseToken(lltok::SummaryID
, "expected module ID"))
9755 unsigned ModuleID
= Lex
.getUIntVal();
9756 auto I
= ModuleIdMap
.find(ModuleID
);
9757 // We should have already parsed all module IDs
9758 assert(I
!= ModuleIdMap
.end());
9759 ModulePath
= I
->second
;
9765 bool LLParser::parseGVReference(ValueInfo
&VI
, unsigned &GVId
) {
9766 bool WriteOnly
= false, ReadOnly
= EatIfPresent(lltok::kw_readonly
);
9768 WriteOnly
= EatIfPresent(lltok::kw_writeonly
);
9769 if (parseToken(lltok::SummaryID
, "expected GV ID"))
9772 GVId
= Lex
.getUIntVal();
9773 // Check if we already have a VI for this GV
9774 if (GVId
< NumberedValueInfos
.size()) {
9775 assert(NumberedValueInfos
[GVId
].getRef() != FwdVIRef
);
9776 VI
= NumberedValueInfos
[GVId
];
9778 // We will create a forward reference to the stored location.
9779 VI
= ValueInfo(false, FwdVIRef
);
9789 /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
9790 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
9791 /// ',' MemProfs ')'
9792 /// Version ::= UInt32
9793 bool LLParser::parseOptionalAllocs(std::vector
<AllocInfo
> &Allocs
) {
9794 assert(Lex
.getKind() == lltok::kw_allocs
);
9797 if (parseToken(lltok::colon
, "expected ':' in allocs") ||
9798 parseToken(lltok::lparen
, "expected '(' in allocs"))
9803 if (parseToken(lltok::lparen
, "expected '(' in alloc") ||
9804 parseToken(lltok::kw_versions
, "expected 'versions' in alloc") ||
9805 parseToken(lltok::colon
, "expected ':'") ||
9806 parseToken(lltok::lparen
, "expected '(' in versions"))
9809 SmallVector
<uint8_t> Versions
;
9812 if (parseAllocType(V
))
9814 Versions
.push_back(V
);
9815 } while (EatIfPresent(lltok::comma
));
9817 if (parseToken(lltok::rparen
, "expected ')' in versions") ||
9818 parseToken(lltok::comma
, "expected ',' in alloc"))
9821 std::vector
<MIBInfo
> MIBs
;
9822 if (parseMemProfs(MIBs
))
9825 Allocs
.push_back({Versions
, MIBs
});
9827 if (parseToken(lltok::rparen
, "expected ')' in alloc"))
9829 } while (EatIfPresent(lltok::comma
));
9831 if (parseToken(lltok::rparen
, "expected ')' in allocs"))
9838 /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
9839 /// MemProf ::= '(' 'type' ':' AllocType
9840 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
9841 /// StackId ::= UInt64
9842 bool LLParser::parseMemProfs(std::vector
<MIBInfo
> &MIBs
) {
9843 assert(Lex
.getKind() == lltok::kw_memProf
);
9846 if (parseToken(lltok::colon
, "expected ':' in memprof") ||
9847 parseToken(lltok::lparen
, "expected '(' in memprof"))
9852 if (parseToken(lltok::lparen
, "expected '(' in memprof") ||
9853 parseToken(lltok::kw_type
, "expected 'type' in memprof") ||
9854 parseToken(lltok::colon
, "expected ':'"))
9858 if (parseAllocType(AllocType
))
9861 if (parseToken(lltok::comma
, "expected ',' in memprof") ||
9862 parseToken(lltok::kw_stackIds
, "expected 'stackIds' in memprof") ||
9863 parseToken(lltok::colon
, "expected ':'") ||
9864 parseToken(lltok::lparen
, "expected '(' in stackIds"))
9867 SmallVector
<unsigned> StackIdIndices
;
9869 uint64_t StackId
= 0;
9870 if (parseUInt64(StackId
))
9872 StackIdIndices
.push_back(Index
->addOrGetStackIdIndex(StackId
));
9873 } while (EatIfPresent(lltok::comma
));
9875 if (parseToken(lltok::rparen
, "expected ')' in stackIds"))
9878 MIBs
.push_back({(AllocationType
)AllocType
, StackIdIndices
});
9880 if (parseToken(lltok::rparen
, "expected ')' in memprof"))
9882 } while (EatIfPresent(lltok::comma
));
9884 if (parseToken(lltok::rparen
, "expected ')' in memprof"))
9891 /// := ('none'|'notcold'|'cold'|'hot')
9892 bool LLParser::parseAllocType(uint8_t &AllocType
) {
9893 switch (Lex
.getKind()) {
9894 case lltok::kw_none
:
9895 AllocType
= (uint8_t)AllocationType::None
;
9897 case lltok::kw_notcold
:
9898 AllocType
= (uint8_t)AllocationType::NotCold
;
9900 case lltok::kw_cold
:
9901 AllocType
= (uint8_t)AllocationType::Cold
;
9904 AllocType
= (uint8_t)AllocationType::Hot
;
9907 return error(Lex
.getLoc(), "invalid alloc type");
9913 /// OptionalCallsites
9914 /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
9915 /// Callsite ::= '(' 'callee' ':' GVReference
9916 /// ',' 'clones' ':' '(' Version [',' Version]* ')'
9917 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
9918 /// Version ::= UInt32
9919 /// StackId ::= UInt64
9920 bool LLParser::parseOptionalCallsites(std::vector
<CallsiteInfo
> &Callsites
) {
9921 assert(Lex
.getKind() == lltok::kw_callsites
);
9924 if (parseToken(lltok::colon
, "expected ':' in callsites") ||
9925 parseToken(lltok::lparen
, "expected '(' in callsites"))
9928 IdToIndexMapType IdToIndexMap
;
9929 // parse each callsite
9931 if (parseToken(lltok::lparen
, "expected '(' in callsite") ||
9932 parseToken(lltok::kw_callee
, "expected 'callee' in callsite") ||
9933 parseToken(lltok::colon
, "expected ':'"))
9938 LocTy Loc
= Lex
.getLoc();
9939 if (!EatIfPresent(lltok::kw_null
)) {
9940 if (parseGVReference(VI
, GVId
))
9944 if (parseToken(lltok::comma
, "expected ',' in callsite") ||
9945 parseToken(lltok::kw_clones
, "expected 'clones' in callsite") ||
9946 parseToken(lltok::colon
, "expected ':'") ||
9947 parseToken(lltok::lparen
, "expected '(' in clones"))
9950 SmallVector
<unsigned> Clones
;
9955 Clones
.push_back(V
);
9956 } while (EatIfPresent(lltok::comma
));
9958 if (parseToken(lltok::rparen
, "expected ')' in clones") ||
9959 parseToken(lltok::comma
, "expected ',' in callsite") ||
9960 parseToken(lltok::kw_stackIds
, "expected 'stackIds' in callsite") ||
9961 parseToken(lltok::colon
, "expected ':'") ||
9962 parseToken(lltok::lparen
, "expected '(' in stackIds"))
9965 SmallVector
<unsigned> StackIdIndices
;
9967 uint64_t StackId
= 0;
9968 if (parseUInt64(StackId
))
9970 StackIdIndices
.push_back(Index
->addOrGetStackIdIndex(StackId
));
9971 } while (EatIfPresent(lltok::comma
));
9973 if (parseToken(lltok::rparen
, "expected ')' in stackIds"))
9976 // Keep track of the Callsites array index needing a forward reference.
9977 // We will save the location of the ValueInfo needing an update, but
9978 // can only do so once the SmallVector is finalized.
9979 if (VI
.getRef() == FwdVIRef
)
9980 IdToIndexMap
[GVId
].push_back(std::make_pair(Callsites
.size(), Loc
));
9981 Callsites
.push_back({VI
, Clones
, StackIdIndices
});
9983 if (parseToken(lltok::rparen
, "expected ')' in callsite"))
9985 } while (EatIfPresent(lltok::comma
));
9987 // Now that the Callsites vector is finalized, it is safe to save the
9988 // locations of any forward GV references that need updating later.
9989 for (auto I
: IdToIndexMap
) {
9990 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9991 for (auto P
: I
.second
) {
9992 assert(Callsites
[P
.first
].Callee
.getRef() == FwdVIRef
&&
9993 "Forward referenced ValueInfo expected to be empty");
9994 Infos
.emplace_back(&Callsites
[P
.first
].Callee
, P
.second
);
9998 if (parseToken(lltok::rparen
, "expected ')' in callsites"))