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/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/ValueSymbolTable.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/SaveAndRestore.h"
46 #include "llvm/Support/raw_ostream.h"
55 static std::string
getTypeString(Type
*T
) {
57 raw_string_ostream
Tmp(Result
);
62 /// Run: module ::= toplevelentity*
63 bool LLParser::Run(bool UpgradeDebugInfo
,
64 DataLayoutCallbackTy DataLayoutCallback
) {
68 if (Context
.shouldDiscardValueNames())
71 "Can't read textual IR with a Context that discards named Values");
74 if (parseTargetDefinitions())
77 if (auto LayoutOverride
= DataLayoutCallback(M
->getTargetTriple()))
78 M
->setDataLayout(*LayoutOverride
);
81 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo
) ||
85 bool LLParser::parseStandaloneConstantValue(Constant
*&C
,
86 const SlotMapping
*Slots
) {
87 restoreParsingState(Slots
);
91 if (parseType(Ty
) || parseConstantValue(Ty
, C
))
93 if (Lex
.getKind() != lltok::Eof
)
94 return error(Lex
.getLoc(), "expected end of string");
98 bool LLParser::parseTypeAtBeginning(Type
*&Ty
, unsigned &Read
,
99 const SlotMapping
*Slots
) {
100 restoreParsingState(Slots
);
104 SMLoc Start
= Lex
.getLoc();
108 SMLoc End
= Lex
.getLoc();
109 Read
= End
.getPointer() - Start
.getPointer();
114 void LLParser::restoreParsingState(const SlotMapping
*Slots
) {
117 NumberedVals
= Slots
->GlobalValues
;
118 NumberedMetadata
= Slots
->MetadataNodes
;
119 for (const auto &I
: Slots
->NamedTypes
)
121 std::make_pair(I
.getKey(), std::make_pair(I
.second
, LocTy())));
122 for (const auto &I
: Slots
->Types
)
123 NumberedTypes
.insert(
124 std::make_pair(I
.first
, std::make_pair(I
.second
, LocTy())));
127 /// validateEndOfModule - Do final validity and sanity checks at the end of the
129 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo
) {
132 // Handle any function attribute group forward references.
133 for (const auto &RAG
: ForwardRefAttrGroups
) {
134 Value
*V
= RAG
.first
;
135 const std::vector
<unsigned> &Attrs
= RAG
.second
;
138 for (const auto &Attr
: Attrs
)
139 B
.merge(NumberedAttrBuilders
[Attr
]);
141 if (Function
*Fn
= dyn_cast
<Function
>(V
)) {
142 AttributeList AS
= Fn
->getAttributes();
143 AttrBuilder
FnAttrs(AS
.getFnAttrs());
144 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
148 // If the alignment was parsed as an attribute, move to the alignment
150 if (FnAttrs
.hasAlignmentAttr()) {
151 Fn
->setAlignment(FnAttrs
.getAlignment());
152 FnAttrs
.removeAttribute(Attribute::Alignment
);
155 AS
= AS
.addFnAttributes(Context
, AttributeSet::get(Context
, FnAttrs
));
156 Fn
->setAttributes(AS
);
157 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(V
)) {
158 AttributeList AS
= CI
->getAttributes();
159 AttrBuilder
FnAttrs(AS
.getFnAttrs());
160 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
162 AS
= AS
.addFnAttributes(Context
, AttributeSet::get(Context
, FnAttrs
));
163 CI
->setAttributes(AS
);
164 } else if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(V
)) {
165 AttributeList AS
= II
->getAttributes();
166 AttrBuilder
FnAttrs(AS
.getFnAttrs());
167 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
169 AS
= AS
.addFnAttributes(Context
, AttributeSet::get(Context
, FnAttrs
));
170 II
->setAttributes(AS
);
171 } else if (CallBrInst
*CBI
= dyn_cast
<CallBrInst
>(V
)) {
172 AttributeList AS
= CBI
->getAttributes();
173 AttrBuilder
FnAttrs(AS
.getFnAttrs());
174 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
176 AS
= AS
.addFnAttributes(Context
, AttributeSet::get(Context
, FnAttrs
));
177 CBI
->setAttributes(AS
);
178 } else if (auto *GV
= dyn_cast
<GlobalVariable
>(V
)) {
179 AttrBuilder
Attrs(GV
->getAttributes());
181 GV
->setAttributes(AttributeSet::get(Context
,Attrs
));
183 llvm_unreachable("invalid object with forward attribute group reference");
187 // If there are entries in ForwardRefBlockAddresses at this point, the
188 // function was never defined.
189 if (!ForwardRefBlockAddresses
.empty())
190 return error(ForwardRefBlockAddresses
.begin()->first
.Loc
,
191 "expected function name in blockaddress");
193 for (const auto &NT
: NumberedTypes
)
194 if (NT
.second
.second
.isValid())
195 return error(NT
.second
.second
,
196 "use of undefined type '%" + Twine(NT
.first
) + "'");
198 for (StringMap
<std::pair
<Type
*, LocTy
> >::iterator I
=
199 NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
)
200 if (I
->second
.second
.isValid())
201 return error(I
->second
.second
,
202 "use of undefined type named '" + I
->getKey() + "'");
204 if (!ForwardRefComdats
.empty())
205 return error(ForwardRefComdats
.begin()->second
,
206 "use of undefined comdat '$" +
207 ForwardRefComdats
.begin()->first
+ "'");
209 if (!ForwardRefVals
.empty())
210 return error(ForwardRefVals
.begin()->second
.second
,
211 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
214 if (!ForwardRefValIDs
.empty())
215 return error(ForwardRefValIDs
.begin()->second
.second
,
216 "use of undefined value '@" +
217 Twine(ForwardRefValIDs
.begin()->first
) + "'");
219 if (!ForwardRefMDNodes
.empty())
220 return error(ForwardRefMDNodes
.begin()->second
.second
,
221 "use of undefined metadata '!" +
222 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
224 // Resolve metadata cycles.
225 for (auto &N
: NumberedMetadata
) {
226 if (N
.second
&& !N
.second
->isResolved())
227 N
.second
->resolveCycles();
230 for (auto *Inst
: InstsWithTBAATag
) {
231 MDNode
*MD
= Inst
->getMetadata(LLVMContext::MD_tbaa
);
232 assert(MD
&& "UpgradeInstWithTBAATag should have a TBAA tag");
233 auto *UpgradedMD
= UpgradeTBAANode(*MD
);
234 if (MD
!= UpgradedMD
)
235 Inst
->setMetadata(LLVMContext::MD_tbaa
, UpgradedMD
);
238 // Look for intrinsic functions and CallInst that need to be upgraded
239 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
240 UpgradeCallsToIntrinsic(&*FI
++); // must be post-increment, as we remove
242 // Some types could be renamed during loading if several modules are
243 // loaded in the same LLVMContext (LTO scenario). In this case we should
244 // remangle intrinsics names as well.
245 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; ) {
246 Function
*F
= &*FI
++;
247 if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(F
)) {
248 F
->replaceAllUsesWith(Remangled
.getValue());
249 F
->eraseFromParent();
253 if (UpgradeDebugInfo
)
254 llvm::UpgradeDebugInfo(*M
);
256 UpgradeModuleFlags(*M
);
257 UpgradeSectionAttributes(*M
);
261 // Initialize the slot mapping.
262 // Because by this point we've parsed and validated everything, we can "steal"
263 // the mapping from LLParser as it doesn't need it anymore.
264 Slots
->GlobalValues
= std::move(NumberedVals
);
265 Slots
->MetadataNodes
= std::move(NumberedMetadata
);
266 for (const auto &I
: NamedTypes
)
267 Slots
->NamedTypes
.insert(std::make_pair(I
.getKey(), I
.second
.first
));
268 for (const auto &I
: NumberedTypes
)
269 Slots
->Types
.insert(std::make_pair(I
.first
, I
.second
.first
));
274 /// Do final validity and sanity checks at the end of the index.
275 bool LLParser::validateEndOfIndex() {
279 if (!ForwardRefValueInfos
.empty())
280 return error(ForwardRefValueInfos
.begin()->second
.front().second
,
281 "use of undefined summary '^" +
282 Twine(ForwardRefValueInfos
.begin()->first
) + "'");
284 if (!ForwardRefAliasees
.empty())
285 return error(ForwardRefAliasees
.begin()->second
.front().second
,
286 "use of undefined summary '^" +
287 Twine(ForwardRefAliasees
.begin()->first
) + "'");
289 if (!ForwardRefTypeIds
.empty())
290 return error(ForwardRefTypeIds
.begin()->second
.front().second
,
291 "use of undefined type id summary '^" +
292 Twine(ForwardRefTypeIds
.begin()->first
) + "'");
297 //===----------------------------------------------------------------------===//
298 // Top-Level Entities
299 //===----------------------------------------------------------------------===//
301 bool LLParser::parseTargetDefinitions() {
303 switch (Lex
.getKind()) {
304 case lltok::kw_target
:
305 if (parseTargetDefinition())
308 case lltok::kw_source_filename
:
309 if (parseSourceFileName())
318 bool LLParser::parseTopLevelEntities() {
319 // If there is no Module, then parse just the summary index entries.
322 switch (Lex
.getKind()) {
325 case lltok::SummaryID
:
326 if (parseSummaryEntry())
329 case lltok::kw_source_filename
:
330 if (parseSourceFileName())
334 // Skip everything else
340 switch (Lex
.getKind()) {
342 return tokError("expected top-level entity");
343 case lltok::Eof
: return false;
344 case lltok::kw_declare
:
348 case lltok::kw_define
:
352 case lltok::kw_module
:
353 if (parseModuleAsm())
356 case lltok::LocalVarID
:
357 if (parseUnnamedType())
360 case lltok::LocalVar
:
361 if (parseNamedType())
364 case lltok::GlobalID
:
365 if (parseUnnamedGlobal())
368 case lltok::GlobalVar
:
369 if (parseNamedGlobal())
372 case lltok::ComdatVar
: if (parseComdat()) return true; break;
374 if (parseStandaloneMetadata())
377 case lltok::SummaryID
:
378 if (parseSummaryEntry())
381 case lltok::MetadataVar
:
382 if (parseNamedMetadata())
385 case lltok::kw_attributes
:
386 if (parseUnnamedAttrGrp())
389 case lltok::kw_uselistorder
:
390 if (parseUseListOrder())
393 case lltok::kw_uselistorder_bb
:
394 if (parseUseListOrderBB())
402 /// ::= 'module' 'asm' STRINGCONSTANT
403 bool LLParser::parseModuleAsm() {
404 assert(Lex
.getKind() == lltok::kw_module
);
408 if (parseToken(lltok::kw_asm
, "expected 'module asm'") ||
409 parseStringConstant(AsmStr
))
412 M
->appendModuleInlineAsm(AsmStr
);
417 /// ::= 'target' 'triple' '=' STRINGCONSTANT
418 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
419 bool LLParser::parseTargetDefinition() {
420 assert(Lex
.getKind() == lltok::kw_target
);
424 return tokError("unknown target property");
425 case lltok::kw_triple
:
427 if (parseToken(lltok::equal
, "expected '=' after target triple") ||
428 parseStringConstant(Str
))
430 M
->setTargetTriple(Str
);
432 case lltok::kw_datalayout
:
434 if (parseToken(lltok::equal
, "expected '=' after target datalayout") ||
435 parseStringConstant(Str
))
437 M
->setDataLayout(Str
);
443 /// ::= 'source_filename' '=' STRINGCONSTANT
444 bool LLParser::parseSourceFileName() {
445 assert(Lex
.getKind() == lltok::kw_source_filename
);
447 if (parseToken(lltok::equal
, "expected '=' after source_filename") ||
448 parseStringConstant(SourceFileName
))
451 M
->setSourceFileName(SourceFileName
);
455 /// parseUnnamedType:
456 /// ::= LocalVarID '=' 'type' type
457 bool LLParser::parseUnnamedType() {
458 LocTy TypeLoc
= Lex
.getLoc();
459 unsigned TypeID
= Lex
.getUIntVal();
460 Lex
.Lex(); // eat LocalVarID;
462 if (parseToken(lltok::equal
, "expected '=' after name") ||
463 parseToken(lltok::kw_type
, "expected 'type' after '='"))
466 Type
*Result
= nullptr;
467 if (parseStructDefinition(TypeLoc
, "", NumberedTypes
[TypeID
], Result
))
470 if (!isa
<StructType
>(Result
)) {
471 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[TypeID
];
473 return error(TypeLoc
, "non-struct types may not be recursive");
474 Entry
.first
= Result
;
475 Entry
.second
= SMLoc();
482 /// ::= LocalVar '=' 'type' type
483 bool LLParser::parseNamedType() {
484 std::string Name
= Lex
.getStrVal();
485 LocTy NameLoc
= Lex
.getLoc();
486 Lex
.Lex(); // eat LocalVar.
488 if (parseToken(lltok::equal
, "expected '=' after name") ||
489 parseToken(lltok::kw_type
, "expected 'type' after name"))
492 Type
*Result
= nullptr;
493 if (parseStructDefinition(NameLoc
, Name
, NamedTypes
[Name
], Result
))
496 if (!isa
<StructType
>(Result
)) {
497 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Name
];
499 return error(NameLoc
, "non-struct types may not be recursive");
500 Entry
.first
= Result
;
501 Entry
.second
= SMLoc();
508 /// ::= 'declare' FunctionHeader
509 bool LLParser::parseDeclare() {
510 assert(Lex
.getKind() == lltok::kw_declare
);
513 std::vector
<std::pair
<unsigned, MDNode
*>> MDs
;
514 while (Lex
.getKind() == lltok::MetadataVar
) {
517 if (parseMetadataAttachment(MDK
, N
))
519 MDs
.push_back({MDK
, N
});
523 if (parseFunctionHeader(F
, false))
526 F
->addMetadata(MD
.first
, *MD
.second
);
531 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
532 bool LLParser::parseDefine() {
533 assert(Lex
.getKind() == lltok::kw_define
);
537 return parseFunctionHeader(F
, true) || parseOptionalFunctionMetadata(*F
) ||
538 parseFunctionBody(*F
);
544 bool LLParser::parseGlobalType(bool &IsConstant
) {
545 if (Lex
.getKind() == lltok::kw_constant
)
547 else if (Lex
.getKind() == lltok::kw_global
)
551 return tokError("expected 'global' or 'constant'");
557 bool LLParser::parseOptionalUnnamedAddr(
558 GlobalVariable::UnnamedAddr
&UnnamedAddr
) {
559 if (EatIfPresent(lltok::kw_unnamed_addr
))
560 UnnamedAddr
= GlobalValue::UnnamedAddr::Global
;
561 else if (EatIfPresent(lltok::kw_local_unnamed_addr
))
562 UnnamedAddr
= GlobalValue::UnnamedAddr::Local
;
564 UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
568 /// parseUnnamedGlobal:
569 /// OptionalVisibility (ALIAS | IFUNC) ...
570 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
571 /// OptionalDLLStorageClass
572 /// ... -> global variable
573 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
574 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
575 /// OptionalVisibility
576 /// OptionalDLLStorageClass
577 /// ... -> global variable
578 bool LLParser::parseUnnamedGlobal() {
579 unsigned VarID
= NumberedVals
.size();
581 LocTy NameLoc
= Lex
.getLoc();
583 // Handle the GlobalID form.
584 if (Lex
.getKind() == lltok::GlobalID
) {
585 if (Lex
.getUIntVal() != VarID
)
586 return error(Lex
.getLoc(),
587 "variable expected to be numbered '%" + Twine(VarID
) + "'");
588 Lex
.Lex(); // eat GlobalID;
590 if (parseToken(lltok::equal
, "expected '=' after name"))
595 unsigned Linkage
, Visibility
, DLLStorageClass
;
597 GlobalVariable::ThreadLocalMode TLM
;
598 GlobalVariable::UnnamedAddr UnnamedAddr
;
599 if (parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
601 parseOptionalThreadLocal(TLM
) || parseOptionalUnnamedAddr(UnnamedAddr
))
604 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
605 return parseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
606 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
608 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
609 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
612 /// parseNamedGlobal:
613 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
614 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
615 /// OptionalVisibility OptionalDLLStorageClass
616 /// ... -> global variable
617 bool LLParser::parseNamedGlobal() {
618 assert(Lex
.getKind() == lltok::GlobalVar
);
619 LocTy NameLoc
= Lex
.getLoc();
620 std::string Name
= Lex
.getStrVal();
624 unsigned Linkage
, Visibility
, DLLStorageClass
;
626 GlobalVariable::ThreadLocalMode TLM
;
627 GlobalVariable::UnnamedAddr UnnamedAddr
;
628 if (parseToken(lltok::equal
, "expected '=' in global variable") ||
629 parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
631 parseOptionalThreadLocal(TLM
) || parseOptionalUnnamedAddr(UnnamedAddr
))
634 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
635 return parseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
636 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
638 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
639 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
642 bool LLParser::parseComdat() {
643 assert(Lex
.getKind() == lltok::ComdatVar
);
644 std::string Name
= Lex
.getStrVal();
645 LocTy NameLoc
= Lex
.getLoc();
648 if (parseToken(lltok::equal
, "expected '=' here"))
651 if (parseToken(lltok::kw_comdat
, "expected comdat keyword"))
652 return tokError("expected comdat type");
654 Comdat::SelectionKind SK
;
655 switch (Lex
.getKind()) {
657 return tokError("unknown selection kind");
661 case lltok::kw_exactmatch
:
662 SK
= Comdat::ExactMatch
;
664 case lltok::kw_largest
:
665 SK
= Comdat::Largest
;
667 case lltok::kw_nodeduplicate
:
668 SK
= Comdat::NoDeduplicate
;
670 case lltok::kw_samesize
:
671 SK
= Comdat::SameSize
;
676 // See if the comdat was forward referenced, if so, use the comdat.
677 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
678 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
679 if (I
!= ComdatSymTab
.end() && !ForwardRefComdats
.erase(Name
))
680 return error(NameLoc
, "redefinition of comdat '$" + Name
+ "'");
683 if (I
!= ComdatSymTab
.end())
686 C
= M
->getOrInsertComdat(Name
);
687 C
->setSelectionKind(SK
);
693 // ::= '!' STRINGCONSTANT
694 bool LLParser::parseMDString(MDString
*&Result
) {
696 if (parseStringConstant(Str
))
698 Result
= MDString::get(Context
, Str
);
703 // ::= '!' MDNodeNumber
704 bool LLParser::parseMDNodeID(MDNode
*&Result
) {
705 // !{ ..., !42, ... }
706 LocTy IDLoc
= Lex
.getLoc();
708 if (parseUInt32(MID
))
711 // If not a forward reference, just return it now.
712 if (NumberedMetadata
.count(MID
)) {
713 Result
= NumberedMetadata
[MID
];
717 // Otherwise, create MDNode forward reference.
718 auto &FwdRef
= ForwardRefMDNodes
[MID
];
719 FwdRef
= std::make_pair(MDTuple::getTemporary(Context
, None
), IDLoc
);
721 Result
= FwdRef
.first
.get();
722 NumberedMetadata
[MID
].reset(Result
);
726 /// parseNamedMetadata:
727 /// !foo = !{ !1, !2 }
728 bool LLParser::parseNamedMetadata() {
729 assert(Lex
.getKind() == lltok::MetadataVar
);
730 std::string Name
= Lex
.getStrVal();
733 if (parseToken(lltok::equal
, "expected '=' here") ||
734 parseToken(lltok::exclaim
, "Expected '!' here") ||
735 parseToken(lltok::lbrace
, "Expected '{' here"))
738 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
739 if (Lex
.getKind() != lltok::rbrace
)
742 // parse DIExpressions inline as a special case. They are still MDNodes,
743 // so they can still appear in named metadata. Remove this logic if they
744 // become plain Metadata.
745 if (Lex
.getKind() == lltok::MetadataVar
&&
746 Lex
.getStrVal() == "DIExpression") {
747 if (parseDIExpression(N
, /*IsDistinct=*/false))
749 // DIArgLists should only appear inline in a function, as they may
750 // contain LocalAsMetadata arguments which require a function context.
751 } else if (Lex
.getKind() == lltok::MetadataVar
&&
752 Lex
.getStrVal() == "DIArgList") {
753 return tokError("found DIArgList outside of function");
754 } else if (parseToken(lltok::exclaim
, "Expected '!' here") ||
759 } while (EatIfPresent(lltok::comma
));
761 return parseToken(lltok::rbrace
, "expected end of metadata node");
764 /// parseStandaloneMetadata:
766 bool LLParser::parseStandaloneMetadata() {
767 assert(Lex
.getKind() == lltok::exclaim
);
769 unsigned MetadataID
= 0;
772 if (parseUInt32(MetadataID
) || parseToken(lltok::equal
, "expected '=' here"))
775 // Detect common error, from old metadata syntax.
776 if (Lex
.getKind() == lltok::Type
)
777 return tokError("unexpected type in metadata definition");
779 bool IsDistinct
= EatIfPresent(lltok::kw_distinct
);
780 if (Lex
.getKind() == lltok::MetadataVar
) {
781 if (parseSpecializedMDNode(Init
, IsDistinct
))
783 } else if (parseToken(lltok::exclaim
, "Expected '!' here") ||
784 parseMDTuple(Init
, IsDistinct
))
787 // See if this was forward referenced, if so, handle it.
788 auto FI
= ForwardRefMDNodes
.find(MetadataID
);
789 if (FI
!= ForwardRefMDNodes
.end()) {
790 FI
->second
.first
->replaceAllUsesWith(Init
);
791 ForwardRefMDNodes
.erase(FI
);
793 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
795 if (NumberedMetadata
.count(MetadataID
))
796 return tokError("Metadata id is already used");
797 NumberedMetadata
[MetadataID
].reset(Init
);
803 // Skips a single module summary entry.
804 bool LLParser::skipModuleSummaryEntry() {
805 // Each module summary entry consists of a tag for the entry
806 // type, followed by a colon, then the fields which may be surrounded by
807 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
808 // support is in place we will look for the tokens corresponding to the
810 if (Lex
.getKind() != lltok::kw_gv
&& Lex
.getKind() != lltok::kw_module
&&
811 Lex
.getKind() != lltok::kw_typeid
&& Lex
.getKind() != lltok::kw_flags
&&
812 Lex
.getKind() != lltok::kw_blockcount
)
814 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
815 "start of summary entry");
816 if (Lex
.getKind() == lltok::kw_flags
)
817 return parseSummaryIndexFlags();
818 if (Lex
.getKind() == lltok::kw_blockcount
)
819 return parseBlockCount();
821 if (parseToken(lltok::colon
, "expected ':' at start of summary entry") ||
822 parseToken(lltok::lparen
, "expected '(' at start of summary entry"))
824 // Now walk through the parenthesized entry, until the number of open
825 // parentheses goes back down to 0 (the first '(' was parsed above).
826 unsigned NumOpenParen
= 1;
828 switch (Lex
.getKind()) {
836 return tokError("found end of file while parsing summary entry");
838 // Skip everything in between parentheses.
842 } while (NumOpenParen
> 0);
847 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
848 bool LLParser::parseSummaryEntry() {
849 assert(Lex
.getKind() == lltok::SummaryID
);
850 unsigned SummaryID
= Lex
.getUIntVal();
852 // For summary entries, colons should be treated as distinct tokens,
853 // not an indication of the end of a label token.
854 Lex
.setIgnoreColonInIdentifiers(true);
857 if (parseToken(lltok::equal
, "expected '=' here"))
860 // If we don't have an index object, skip the summary entry.
862 return skipModuleSummaryEntry();
865 switch (Lex
.getKind()) {
867 result
= parseGVEntry(SummaryID
);
869 case lltok::kw_module
:
870 result
= parseModuleEntry(SummaryID
);
872 case lltok::kw_typeid
:
873 result
= parseTypeIdEntry(SummaryID
);
875 case lltok::kw_typeidCompatibleVTable
:
876 result
= parseTypeIdCompatibleVtableEntry(SummaryID
);
878 case lltok::kw_flags
:
879 result
= parseSummaryIndexFlags();
881 case lltok::kw_blockcount
:
882 result
= parseBlockCount();
885 result
= error(Lex
.getLoc(), "unexpected summary kind");
888 Lex
.setIgnoreColonInIdentifiers(false);
892 static bool isValidVisibilityForLinkage(unsigned V
, unsigned L
) {
893 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
894 (GlobalValue::VisibilityTypes
)V
== GlobalValue::DefaultVisibility
;
897 // If there was an explicit dso_local, update GV. In the absence of an explicit
898 // dso_local we keep the default value.
899 static void maybeSetDSOLocal(bool DSOLocal
, GlobalValue
&GV
) {
901 GV
.setDSOLocal(true);
904 static std::string
typeComparisonErrorMessage(StringRef Message
, Type
*Ty1
,
906 std::string ErrString
;
907 raw_string_ostream
ErrOS(ErrString
);
908 ErrOS
<< Message
<< " (" << *Ty1
<< " vs " << *Ty2
<< ")";
912 /// parseIndirectSymbol:
913 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
914 /// OptionalVisibility OptionalDLLStorageClass
915 /// OptionalThreadLocal OptionalUnnamedAddr
916 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
921 /// IndirectSymbolAttr
922 /// ::= ',' 'partition' StringConstant
924 /// Everything through OptionalUnnamedAddr has already been parsed.
926 bool LLParser::parseIndirectSymbol(const std::string
&Name
, LocTy NameLoc
,
927 unsigned L
, unsigned Visibility
,
928 unsigned DLLStorageClass
, bool DSOLocal
,
929 GlobalVariable::ThreadLocalMode TLM
,
930 GlobalVariable::UnnamedAddr UnnamedAddr
) {
932 if (Lex
.getKind() == lltok::kw_alias
)
934 else if (Lex
.getKind() == lltok::kw_ifunc
)
937 llvm_unreachable("Not an alias or ifunc!");
940 GlobalValue::LinkageTypes Linkage
= (GlobalValue::LinkageTypes
) L
;
942 if(IsAlias
&& !GlobalAlias::isValidLinkage(Linkage
))
943 return error(NameLoc
, "invalid linkage type for alias");
945 if (!isValidVisibilityForLinkage(Visibility
, L
))
946 return error(NameLoc
,
947 "symbol with local linkage must have default visibility");
950 LocTy ExplicitTypeLoc
= Lex
.getLoc();
952 parseToken(lltok::comma
, "expected comma after alias or ifunc's type"))
956 LocTy AliaseeLoc
= Lex
.getLoc();
957 if (Lex
.getKind() != lltok::kw_bitcast
&&
958 Lex
.getKind() != lltok::kw_getelementptr
&&
959 Lex
.getKind() != lltok::kw_addrspacecast
&&
960 Lex
.getKind() != lltok::kw_inttoptr
) {
961 if (parseGlobalTypeAndValue(Aliasee
))
964 // The bitcast dest type is not present, it is implied by the dest type.
966 if (parseValID(ID
, /*PFS=*/nullptr))
968 if (ID
.Kind
!= ValID::t_Constant
)
969 return error(AliaseeLoc
, "invalid aliasee");
970 Aliasee
= ID
.ConstantVal
;
973 Type
*AliaseeType
= Aliasee
->getType();
974 auto *PTy
= dyn_cast
<PointerType
>(AliaseeType
);
976 return error(AliaseeLoc
, "An alias or ifunc must have pointer type");
977 unsigned AddrSpace
= PTy
->getAddressSpace();
979 if (IsAlias
&& !PTy
->isOpaqueOrPointeeTypeMatches(Ty
)) {
982 typeComparisonErrorMessage(
983 "explicit pointee type doesn't match operand's pointee type", Ty
,
984 PTy
->getElementType()));
987 if (!IsAlias
&& !PTy
->getElementType()->isFunctionTy()) {
988 return error(ExplicitTypeLoc
,
989 "explicit pointee type should be a function type");
992 GlobalValue
*GVal
= nullptr;
994 // See if the alias was forward referenced, if so, prepare to replace the
995 // forward reference.
997 auto I
= ForwardRefVals
.find(Name
);
998 if (I
!= ForwardRefVals
.end()) {
999 GVal
= I
->second
.first
;
1000 ForwardRefVals
.erase(Name
);
1001 } else if (M
->getNamedValue(Name
)) {
1002 return error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1005 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1006 if (I
!= ForwardRefValIDs
.end()) {
1007 GVal
= I
->second
.first
;
1008 ForwardRefValIDs
.erase(I
);
1012 // Okay, create the alias but do not insert it into the module yet.
1013 std::unique_ptr
<GlobalIndirectSymbol
> GA
;
1015 GA
.reset(GlobalAlias::create(Ty
, AddrSpace
,
1016 (GlobalValue::LinkageTypes
)Linkage
, Name
,
1017 Aliasee
, /*Parent*/ nullptr));
1019 GA
.reset(GlobalIFunc::create(Ty
, AddrSpace
,
1020 (GlobalValue::LinkageTypes
)Linkage
, Name
,
1021 Aliasee
, /*Parent*/ nullptr));
1022 GA
->setThreadLocalMode(TLM
);
1023 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1024 GA
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1025 GA
->setUnnamedAddr(UnnamedAddr
);
1026 maybeSetDSOLocal(DSOLocal
, *GA
);
1028 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1029 // Now parse them if there are any.
1030 while (Lex
.getKind() == lltok::comma
) {
1033 if (Lex
.getKind() == lltok::kw_partition
) {
1035 GA
->setPartition(Lex
.getStrVal());
1036 if (parseToken(lltok::StringConstant
, "expected partition string"))
1039 return tokError("unknown alias or ifunc property!");
1044 NumberedVals
.push_back(GA
.get());
1047 // Verify that types agree.
1048 if (GVal
->getType() != GA
->getType())
1051 "forward reference and definition of alias have different types");
1053 // If they agree, just RAUW the old value with the alias and remove the
1054 // forward ref info.
1055 GVal
->replaceAllUsesWith(GA
.get());
1056 GVal
->eraseFromParent();
1059 // Insert into the module, we know its name won't collide now.
1061 M
->getAliasList().push_back(cast
<GlobalAlias
>(GA
.get()));
1063 M
->getIFuncList().push_back(cast
<GlobalIFunc
>(GA
.get()));
1064 assert(GA
->getName() == Name
&& "Should not be a name conflict!");
1066 // The module owns this now
1073 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1074 /// OptionalVisibility OptionalDLLStorageClass
1075 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1076 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1077 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1078 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1079 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1080 /// Const OptionalAttrs
1082 /// Everything up to and including OptionalUnnamedAddr has been parsed
1085 bool LLParser::parseGlobal(const std::string
&Name
, LocTy NameLoc
,
1086 unsigned Linkage
, bool HasLinkage
,
1087 unsigned Visibility
, unsigned DLLStorageClass
,
1088 bool DSOLocal
, GlobalVariable::ThreadLocalMode TLM
,
1089 GlobalVariable::UnnamedAddr UnnamedAddr
) {
1090 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
1091 return error(NameLoc
,
1092 "symbol with local linkage must have default visibility");
1095 bool IsConstant
, IsExternallyInitialized
;
1096 LocTy IsExternallyInitializedLoc
;
1100 if (parseOptionalAddrSpace(AddrSpace
) ||
1101 parseOptionalToken(lltok::kw_externally_initialized
,
1102 IsExternallyInitialized
,
1103 &IsExternallyInitializedLoc
) ||
1104 parseGlobalType(IsConstant
) || parseType(Ty
, TyLoc
))
1107 // If the linkage is specified and is external, then no initializer is
1109 Constant
*Init
= nullptr;
1111 !GlobalValue::isValidDeclarationLinkage(
1112 (GlobalValue::LinkageTypes
)Linkage
)) {
1113 if (parseGlobalValue(Ty
, Init
))
1117 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
1118 return error(TyLoc
, "invalid type for global variable");
1120 GlobalValue
*GVal
= nullptr;
1122 // See if the global was forward referenced, if so, use the global.
1123 if (!Name
.empty()) {
1124 auto I
= ForwardRefVals
.find(Name
);
1125 if (I
!= ForwardRefVals
.end()) {
1126 GVal
= I
->second
.first
;
1127 ForwardRefVals
.erase(I
);
1128 } else if (M
->getNamedValue(Name
)) {
1129 return error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1132 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1133 if (I
!= ForwardRefValIDs
.end()) {
1134 GVal
= I
->second
.first
;
1135 ForwardRefValIDs
.erase(I
);
1139 GlobalVariable
*GV
= new GlobalVariable(
1140 *M
, Ty
, false, GlobalValue::ExternalLinkage
, nullptr, Name
, nullptr,
1141 GlobalVariable::NotThreadLocal
, AddrSpace
);
1144 NumberedVals
.push_back(GV
);
1146 // Set the parsed properties on the global.
1148 GV
->setInitializer(Init
);
1149 GV
->setConstant(IsConstant
);
1150 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
1151 maybeSetDSOLocal(DSOLocal
, *GV
);
1152 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1153 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1154 GV
->setExternallyInitialized(IsExternallyInitialized
);
1155 GV
->setThreadLocalMode(TLM
);
1156 GV
->setUnnamedAddr(UnnamedAddr
);
1159 if (!GVal
->getType()->isOpaque() && GVal
->getValueType() != Ty
)
1162 "forward reference and definition of global have different types");
1164 GVal
->replaceAllUsesWith(GV
);
1165 GVal
->eraseFromParent();
1168 // parse attributes on the global.
1169 while (Lex
.getKind() == lltok::comma
) {
1172 if (Lex
.getKind() == lltok::kw_section
) {
1174 GV
->setSection(Lex
.getStrVal());
1175 if (parseToken(lltok::StringConstant
, "expected global section string"))
1177 } else if (Lex
.getKind() == lltok::kw_partition
) {
1179 GV
->setPartition(Lex
.getStrVal());
1180 if (parseToken(lltok::StringConstant
, "expected partition string"))
1182 } else if (Lex
.getKind() == lltok::kw_align
) {
1183 MaybeAlign Alignment
;
1184 if (parseOptionalAlignment(Alignment
))
1186 GV
->setAlignment(Alignment
);
1187 } else if (Lex
.getKind() == lltok::MetadataVar
) {
1188 if (parseGlobalObjectMetadataAttachment(*GV
))
1192 if (parseOptionalComdat(Name
, C
))
1197 return tokError("unknown global variable property!");
1203 std::vector
<unsigned> FwdRefAttrGrps
;
1204 if (parseFnAttributeValuePairs(Attrs
, FwdRefAttrGrps
, false, BuiltinLoc
))
1206 if (Attrs
.hasAttributes() || !FwdRefAttrGrps
.empty()) {
1207 GV
->setAttributes(AttributeSet::get(Context
, Attrs
));
1208 ForwardRefAttrGroups
[GV
] = FwdRefAttrGrps
;
1214 /// parseUnnamedAttrGrp
1215 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1216 bool LLParser::parseUnnamedAttrGrp() {
1217 assert(Lex
.getKind() == lltok::kw_attributes
);
1218 LocTy AttrGrpLoc
= Lex
.getLoc();
1221 if (Lex
.getKind() != lltok::AttrGrpID
)
1222 return tokError("expected attribute group id");
1224 unsigned VarID
= Lex
.getUIntVal();
1225 std::vector
<unsigned> unused
;
1229 if (parseToken(lltok::equal
, "expected '=' here") ||
1230 parseToken(lltok::lbrace
, "expected '{' here") ||
1231 parseFnAttributeValuePairs(NumberedAttrBuilders
[VarID
], unused
, true,
1233 parseToken(lltok::rbrace
, "expected end of attribute group"))
1236 if (!NumberedAttrBuilders
[VarID
].hasAttributes())
1237 return error(AttrGrpLoc
, "attribute group has no attributes");
1242 static Attribute::AttrKind
tokenToAttribute(lltok::Kind Kind
) {
1244 #define GET_ATTR_NAMES
1245 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1246 case lltok::kw_##DISPLAY_NAME: \
1247 return Attribute::ENUM_NAME;
1248 #include "llvm/IR/Attributes.inc"
1250 return Attribute::None
;
1254 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr
, AttrBuilder
&B
,
1256 if (Attribute::isTypeAttrKind(Attr
))
1257 return parseRequiredTypeAttr(B
, Lex
.getKind(), Attr
);
1260 case Attribute::Alignment
: {
1261 MaybeAlign Alignment
;
1265 if (parseToken(lltok::equal
, "expected '=' here") || parseUInt32(Value
))
1267 Alignment
= Align(Value
);
1269 if (parseOptionalAlignment(Alignment
, true))
1272 B
.addAlignmentAttr(Alignment
);
1275 case Attribute::StackAlignment
: {
1279 if (parseToken(lltok::equal
, "expected '=' here") ||
1280 parseUInt32(Alignment
))
1283 if (parseOptionalStackAlignment(Alignment
))
1286 B
.addStackAlignmentAttr(Alignment
);
1289 case Attribute::AllocSize
: {
1290 unsigned ElemSizeArg
;
1291 Optional
<unsigned> NumElemsArg
;
1292 if (parseAllocSizeArguments(ElemSizeArg
, NumElemsArg
))
1294 B
.addAllocSizeAttr(ElemSizeArg
, NumElemsArg
);
1297 case Attribute::VScaleRange
: {
1298 unsigned MinValue
, MaxValue
;
1299 if (parseVScaleRangeArguments(MinValue
, MaxValue
))
1301 B
.addVScaleRangeAttr(MinValue
, MaxValue
);
1304 case Attribute::Dereferenceable
: {
1306 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1308 B
.addDereferenceableAttr(Bytes
);
1311 case Attribute::DereferenceableOrNull
: {
1313 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1315 B
.addDereferenceableOrNullAttr(Bytes
);
1319 B
.addAttribute(Attr
);
1325 /// parseFnAttributeValuePairs
1326 /// ::= <attr> | <attr> '=' <value>
1327 bool LLParser::parseFnAttributeValuePairs(AttrBuilder
&B
,
1328 std::vector
<unsigned> &FwdRefAttrGrps
,
1329 bool InAttrGrp
, LocTy
&BuiltinLoc
) {
1330 bool HaveError
= false;
1335 lltok::Kind Token
= Lex
.getKind();
1336 if (Token
== lltok::rbrace
)
1337 return HaveError
; // Finished.
1339 if (Token
== lltok::StringConstant
) {
1340 if (parseStringAttribute(B
))
1345 if (Token
== lltok::AttrGrpID
) {
1346 // Allow a function to reference an attribute group:
1348 // define void @foo() #1 { ... }
1352 "cannot have an attribute group reference in an attribute group");
1354 // Save the reference to the attribute group. We'll fill it in later.
1355 FwdRefAttrGrps
.push_back(Lex
.getUIntVal());
1361 SMLoc Loc
= Lex
.getLoc();
1362 if (Token
== lltok::kw_builtin
)
1365 Attribute::AttrKind Attr
= tokenToAttribute(Token
);
1366 if (Attr
== Attribute::None
) {
1369 return error(Lex
.getLoc(), "unterminated attribute group");
1372 if (parseEnumAttribute(Attr
, B
, InAttrGrp
))
1375 // As a hack, we allow function alignment to be initially parsed as an
1376 // attribute on a function declaration/definition or added to an attribute
1377 // group and later moved to the alignment field.
1378 if (!Attribute::canUseAsFnAttr(Attr
) && Attr
!= Attribute::Alignment
)
1379 HaveError
|= error(Loc
, "this attribute does not apply to functions");
1383 //===----------------------------------------------------------------------===//
1384 // GlobalValue Reference/Resolution Routines.
1385 //===----------------------------------------------------------------------===//
1387 static inline GlobalValue
*createGlobalFwdRef(Module
*M
, PointerType
*PTy
) {
1388 // For opaque pointers, the used global type does not matter. We will later
1389 // RAUW it with a global/function of the correct type.
1390 if (PTy
->isOpaque())
1391 return new GlobalVariable(*M
, Type::getInt8Ty(M
->getContext()), false,
1392 GlobalValue::ExternalWeakLinkage
, nullptr, "",
1393 nullptr, GlobalVariable::NotThreadLocal
,
1394 PTy
->getAddressSpace());
1396 if (auto *FT
= dyn_cast
<FunctionType
>(PTy
->getPointerElementType()))
1397 return Function::Create(FT
, GlobalValue::ExternalWeakLinkage
,
1398 PTy
->getAddressSpace(), "", M
);
1400 return new GlobalVariable(*M
, PTy
->getPointerElementType(), false,
1401 GlobalValue::ExternalWeakLinkage
, nullptr, "",
1402 nullptr, GlobalVariable::NotThreadLocal
,
1403 PTy
->getAddressSpace());
1406 Value
*LLParser::checkValidVariableType(LocTy Loc
, const Twine
&Name
, Type
*Ty
,
1407 Value
*Val
, bool IsCall
) {
1408 Type
*ValTy
= Val
->getType();
1411 // For calls, we also allow opaque pointers.
1412 if (IsCall
&& ValTy
== PointerType::get(Ty
->getContext(),
1413 Ty
->getPointerAddressSpace()))
1415 if (Ty
->isLabelTy())
1416 error(Loc
, "'" + Name
+ "' is not a basic block");
1418 error(Loc
, "'" + Name
+ "' defined with type '" +
1419 getTypeString(Val
->getType()) + "' but expected '" +
1420 getTypeString(Ty
) + "'");
1424 /// getGlobalVal - Get a value with the specified name or ID, creating a
1425 /// forward reference record if needed. This can return null if the value
1426 /// exists but does not have the right type.
1427 GlobalValue
*LLParser::getGlobalVal(const std::string
&Name
, Type
*Ty
,
1428 LocTy Loc
, bool IsCall
) {
1429 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1431 error(Loc
, "global variable reference must have pointer type");
1435 // Look this name up in the normal function symbol table.
1437 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
1439 // If this is a forward reference for the value, see if we already created a
1440 // forward ref record.
1442 auto I
= ForwardRefVals
.find(Name
);
1443 if (I
!= ForwardRefVals
.end())
1444 Val
= I
->second
.first
;
1447 // If we have the value in the symbol table or fwd-ref table, return it.
1449 return cast_or_null
<GlobalValue
>(
1450 checkValidVariableType(Loc
, "@" + Name
, Ty
, Val
, IsCall
));
1452 // Otherwise, create a new forward reference for this value and remember it.
1453 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
);
1454 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1458 GlobalValue
*LLParser::getGlobalVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
1460 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1462 error(Loc
, "global variable reference must have pointer type");
1466 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
1468 // If this is a forward reference for the value, see if we already created a
1469 // forward ref record.
1471 auto I
= ForwardRefValIDs
.find(ID
);
1472 if (I
!= ForwardRefValIDs
.end())
1473 Val
= I
->second
.first
;
1476 // If we have the value in the symbol table or fwd-ref table, return it.
1478 return cast_or_null
<GlobalValue
>(
1479 checkValidVariableType(Loc
, "@" + Twine(ID
), Ty
, Val
, IsCall
));
1481 // Otherwise, create a new forward reference for this value and remember it.
1482 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
);
1483 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1487 //===----------------------------------------------------------------------===//
1488 // Comdat Reference/Resolution Routines.
1489 //===----------------------------------------------------------------------===//
1491 Comdat
*LLParser::getComdat(const std::string
&Name
, LocTy Loc
) {
1492 // Look this name up in the comdat symbol table.
1493 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
1494 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
1495 if (I
!= ComdatSymTab
.end())
1498 // Otherwise, create a new forward reference for this value and remember it.
1499 Comdat
*C
= M
->getOrInsertComdat(Name
);
1500 ForwardRefComdats
[Name
] = Loc
;
1504 //===----------------------------------------------------------------------===//
1506 //===----------------------------------------------------------------------===//
1508 /// parseToken - If the current token has the specified kind, eat it and return
1509 /// success. Otherwise, emit the specified error and return failure.
1510 bool LLParser::parseToken(lltok::Kind T
, const char *ErrMsg
) {
1511 if (Lex
.getKind() != T
)
1512 return tokError(ErrMsg
);
1517 /// parseStringConstant
1518 /// ::= StringConstant
1519 bool LLParser::parseStringConstant(std::string
&Result
) {
1520 if (Lex
.getKind() != lltok::StringConstant
)
1521 return tokError("expected string constant");
1522 Result
= Lex
.getStrVal();
1529 bool LLParser::parseUInt32(uint32_t &Val
) {
1530 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1531 return tokError("expected integer");
1532 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
1533 if (Val64
!= unsigned(Val64
))
1534 return tokError("expected 32-bit integer (too large)");
1542 bool LLParser::parseUInt64(uint64_t &Val
) {
1543 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1544 return tokError("expected integer");
1545 Val
= Lex
.getAPSIntVal().getLimitedValue();
1551 /// := 'localdynamic'
1552 /// := 'initialexec'
1554 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode
&TLM
) {
1555 switch (Lex
.getKind()) {
1557 return tokError("expected localdynamic, initialexec or localexec");
1558 case lltok::kw_localdynamic
:
1559 TLM
= GlobalVariable::LocalDynamicTLSModel
;
1561 case lltok::kw_initialexec
:
1562 TLM
= GlobalVariable::InitialExecTLSModel
;
1564 case lltok::kw_localexec
:
1565 TLM
= GlobalVariable::LocalExecTLSModel
;
1573 /// parseOptionalThreadLocal
1575 /// := 'thread_local'
1576 /// := 'thread_local' '(' tlsmodel ')'
1577 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode
&TLM
) {
1578 TLM
= GlobalVariable::NotThreadLocal
;
1579 if (!EatIfPresent(lltok::kw_thread_local
))
1582 TLM
= GlobalVariable::GeneralDynamicTLSModel
;
1583 if (Lex
.getKind() == lltok::lparen
) {
1585 return parseTLSModel(TLM
) ||
1586 parseToken(lltok::rparen
, "expected ')' after thread local model");
1591 /// parseOptionalAddrSpace
1593 /// := 'addrspace' '(' uint32 ')'
1594 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace
, unsigned DefaultAS
) {
1595 AddrSpace
= DefaultAS
;
1596 if (!EatIfPresent(lltok::kw_addrspace
))
1598 return parseToken(lltok::lparen
, "expected '(' in address space") ||
1599 parseUInt32(AddrSpace
) ||
1600 parseToken(lltok::rparen
, "expected ')' in address space");
1603 /// parseStringAttribute
1604 /// := StringConstant
1605 /// := StringConstant '=' StringConstant
1606 bool LLParser::parseStringAttribute(AttrBuilder
&B
) {
1607 std::string Attr
= Lex
.getStrVal();
1610 if (EatIfPresent(lltok::equal
) && parseStringConstant(Val
))
1612 B
.addAttribute(Attr
, Val
);
1616 /// Parse a potentially empty list of parameter or return attributes.
1617 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder
&B
, bool IsParam
) {
1618 bool HaveError
= false;
1623 lltok::Kind Token
= Lex
.getKind();
1624 if (Token
== lltok::StringConstant
) {
1625 if (parseStringAttribute(B
))
1630 SMLoc Loc
= Lex
.getLoc();
1631 Attribute::AttrKind Attr
= tokenToAttribute(Token
);
1632 if (Attr
== Attribute::None
)
1635 if (parseEnumAttribute(Attr
, B
, /* InAttrGroup */ false))
1638 if (IsParam
&& !Attribute::canUseAsParamAttr(Attr
))
1639 HaveError
|= error(Loc
, "this attribute does not apply to parameters");
1640 if (!IsParam
&& !Attribute::canUseAsRetAttr(Attr
))
1641 HaveError
|= error(Loc
, "this attribute does not apply to return values");
1645 static unsigned parseOptionalLinkageAux(lltok::Kind Kind
, bool &HasLinkage
) {
1650 return GlobalValue::ExternalLinkage
;
1651 case lltok::kw_private
:
1652 return GlobalValue::PrivateLinkage
;
1653 case lltok::kw_internal
:
1654 return GlobalValue::InternalLinkage
;
1655 case lltok::kw_weak
:
1656 return GlobalValue::WeakAnyLinkage
;
1657 case lltok::kw_weak_odr
:
1658 return GlobalValue::WeakODRLinkage
;
1659 case lltok::kw_linkonce
:
1660 return GlobalValue::LinkOnceAnyLinkage
;
1661 case lltok::kw_linkonce_odr
:
1662 return GlobalValue::LinkOnceODRLinkage
;
1663 case lltok::kw_available_externally
:
1664 return GlobalValue::AvailableExternallyLinkage
;
1665 case lltok::kw_appending
:
1666 return GlobalValue::AppendingLinkage
;
1667 case lltok::kw_common
:
1668 return GlobalValue::CommonLinkage
;
1669 case lltok::kw_extern_weak
:
1670 return GlobalValue::ExternalWeakLinkage
;
1671 case lltok::kw_external
:
1672 return GlobalValue::ExternalLinkage
;
1676 /// parseOptionalLinkage
1683 /// ::= 'linkonce_odr'
1684 /// ::= 'available_externally'
1687 /// ::= 'extern_weak'
1689 bool LLParser::parseOptionalLinkage(unsigned &Res
, bool &HasLinkage
,
1690 unsigned &Visibility
,
1691 unsigned &DLLStorageClass
, bool &DSOLocal
) {
1692 Res
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
1695 parseOptionalDSOLocal(DSOLocal
);
1696 parseOptionalVisibility(Visibility
);
1697 parseOptionalDLLStorageClass(DLLStorageClass
);
1699 if (DSOLocal
&& DLLStorageClass
== GlobalValue::DLLImportStorageClass
) {
1700 return error(Lex
.getLoc(), "dso_location and DLL-StorageClass mismatch");
1706 void LLParser::parseOptionalDSOLocal(bool &DSOLocal
) {
1707 switch (Lex
.getKind()) {
1711 case lltok::kw_dso_local
:
1715 case lltok::kw_dso_preemptable
:
1722 /// parseOptionalVisibility
1728 void LLParser::parseOptionalVisibility(unsigned &Res
) {
1729 switch (Lex
.getKind()) {
1731 Res
= GlobalValue::DefaultVisibility
;
1733 case lltok::kw_default
:
1734 Res
= GlobalValue::DefaultVisibility
;
1736 case lltok::kw_hidden
:
1737 Res
= GlobalValue::HiddenVisibility
;
1739 case lltok::kw_protected
:
1740 Res
= GlobalValue::ProtectedVisibility
;
1746 /// parseOptionalDLLStorageClass
1751 void LLParser::parseOptionalDLLStorageClass(unsigned &Res
) {
1752 switch (Lex
.getKind()) {
1754 Res
= GlobalValue::DefaultStorageClass
;
1756 case lltok::kw_dllimport
:
1757 Res
= GlobalValue::DLLImportStorageClass
;
1759 case lltok::kw_dllexport
:
1760 Res
= GlobalValue::DLLExportStorageClass
;
1766 /// parseOptionalCallingConv
1770 /// ::= 'intel_ocl_bicc'
1772 /// ::= 'cfguard_checkcc'
1773 /// ::= 'x86_stdcallcc'
1774 /// ::= 'x86_fastcallcc'
1775 /// ::= 'x86_thiscallcc'
1776 /// ::= 'x86_vectorcallcc'
1777 /// ::= 'arm_apcscc'
1778 /// ::= 'arm_aapcscc'
1779 /// ::= 'arm_aapcs_vfpcc'
1780 /// ::= 'aarch64_vector_pcs'
1781 /// ::= 'aarch64_sve_vector_pcs'
1782 /// ::= 'msp430_intrcc'
1783 /// ::= 'avr_intrcc'
1784 /// ::= 'avr_signalcc'
1785 /// ::= 'ptx_kernel'
1786 /// ::= 'ptx_device'
1788 /// ::= 'spir_kernel'
1789 /// ::= 'x86_64_sysvcc'
1791 /// ::= 'webkit_jscc'
1793 /// ::= 'preserve_mostcc'
1794 /// ::= 'preserve_allcc'
1797 /// ::= 'swifttailcc'
1798 /// ::= 'x86_intrcc'
1801 /// ::= 'cxx_fast_tlscc'
1809 /// ::= 'amdgpu_kernel'
1813 bool LLParser::parseOptionalCallingConv(unsigned &CC
) {
1814 switch (Lex
.getKind()) {
1815 default: CC
= CallingConv::C
; return false;
1816 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
1817 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
1818 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
1819 case lltok::kw_cfguard_checkcc
: CC
= CallingConv::CFGuard_Check
; break;
1820 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
1821 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
1822 case lltok::kw_x86_regcallcc
: CC
= CallingConv::X86_RegCall
; break;
1823 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
1824 case lltok::kw_x86_vectorcallcc
:CC
= CallingConv::X86_VectorCall
; break;
1825 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
1826 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
1827 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
1828 case lltok::kw_aarch64_vector_pcs
:CC
= CallingConv::AArch64_VectorCall
; break;
1829 case lltok::kw_aarch64_sve_vector_pcs
:
1830 CC
= CallingConv::AArch64_SVE_VectorCall
;
1832 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
1833 case lltok::kw_avr_intrcc
: CC
= CallingConv::AVR_INTR
; break;
1834 case lltok::kw_avr_signalcc
: CC
= CallingConv::AVR_SIGNAL
; break;
1835 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
1836 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
1837 case lltok::kw_spir_kernel
: CC
= CallingConv::SPIR_KERNEL
; break;
1838 case lltok::kw_spir_func
: CC
= CallingConv::SPIR_FUNC
; break;
1839 case lltok::kw_intel_ocl_bicc
: CC
= CallingConv::Intel_OCL_BI
; break;
1840 case lltok::kw_x86_64_sysvcc
: CC
= CallingConv::X86_64_SysV
; break;
1841 case lltok::kw_win64cc
: CC
= CallingConv::Win64
; break;
1842 case lltok::kw_webkit_jscc
: CC
= CallingConv::WebKit_JS
; break;
1843 case lltok::kw_anyregcc
: CC
= CallingConv::AnyReg
; break;
1844 case lltok::kw_preserve_mostcc
:CC
= CallingConv::PreserveMost
; break;
1845 case lltok::kw_preserve_allcc
: CC
= CallingConv::PreserveAll
; break;
1846 case lltok::kw_ghccc
: CC
= CallingConv::GHC
; break;
1847 case lltok::kw_swiftcc
: CC
= CallingConv::Swift
; break;
1848 case lltok::kw_swifttailcc
: CC
= CallingConv::SwiftTail
; break;
1849 case lltok::kw_x86_intrcc
: CC
= CallingConv::X86_INTR
; break;
1850 case lltok::kw_hhvmcc
: CC
= CallingConv::HHVM
; break;
1851 case lltok::kw_hhvm_ccc
: CC
= CallingConv::HHVM_C
; break;
1852 case lltok::kw_cxx_fast_tlscc
: CC
= CallingConv::CXX_FAST_TLS
; break;
1853 case lltok::kw_amdgpu_vs
: CC
= CallingConv::AMDGPU_VS
; break;
1854 case lltok::kw_amdgpu_gfx
: CC
= CallingConv::AMDGPU_Gfx
; break;
1855 case lltok::kw_amdgpu_ls
: CC
= CallingConv::AMDGPU_LS
; break;
1856 case lltok::kw_amdgpu_hs
: CC
= CallingConv::AMDGPU_HS
; break;
1857 case lltok::kw_amdgpu_es
: CC
= CallingConv::AMDGPU_ES
; break;
1858 case lltok::kw_amdgpu_gs
: CC
= CallingConv::AMDGPU_GS
; break;
1859 case lltok::kw_amdgpu_ps
: CC
= CallingConv::AMDGPU_PS
; break;
1860 case lltok::kw_amdgpu_cs
: CC
= CallingConv::AMDGPU_CS
; break;
1861 case lltok::kw_amdgpu_kernel
: CC
= CallingConv::AMDGPU_KERNEL
; break;
1862 case lltok::kw_tailcc
: CC
= CallingConv::Tail
; break;
1863 case lltok::kw_cc
: {
1865 return parseUInt32(CC
);
1873 /// parseMetadataAttachment
1875 bool LLParser::parseMetadataAttachment(unsigned &Kind
, MDNode
*&MD
) {
1876 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata attachment");
1878 std::string Name
= Lex
.getStrVal();
1879 Kind
= M
->getMDKindID(Name
);
1882 return parseMDNode(MD
);
1885 /// parseInstructionMetadata
1886 /// ::= !dbg !42 (',' !dbg !57)*
1887 bool LLParser::parseInstructionMetadata(Instruction
&Inst
) {
1889 if (Lex
.getKind() != lltok::MetadataVar
)
1890 return tokError("expected metadata after comma");
1894 if (parseMetadataAttachment(MDK
, N
))
1897 Inst
.setMetadata(MDK
, N
);
1898 if (MDK
== LLVMContext::MD_tbaa
)
1899 InstsWithTBAATag
.push_back(&Inst
);
1901 // If this is the end of the list, we're done.
1902 } while (EatIfPresent(lltok::comma
));
1906 /// parseGlobalObjectMetadataAttachment
1908 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject
&GO
) {
1911 if (parseMetadataAttachment(MDK
, N
))
1914 GO
.addMetadata(MDK
, *N
);
1918 /// parseOptionalFunctionMetadata
1920 bool LLParser::parseOptionalFunctionMetadata(Function
&F
) {
1921 while (Lex
.getKind() == lltok::MetadataVar
)
1922 if (parseGlobalObjectMetadataAttachment(F
))
1927 /// parseOptionalAlignment
1930 bool LLParser::parseOptionalAlignment(MaybeAlign
&Alignment
, bool AllowParens
) {
1932 if (!EatIfPresent(lltok::kw_align
))
1934 LocTy AlignLoc
= Lex
.getLoc();
1937 LocTy ParenLoc
= Lex
.getLoc();
1938 bool HaveParens
= false;
1940 if (EatIfPresent(lltok::lparen
))
1944 if (parseUInt32(Value
))
1947 if (HaveParens
&& !EatIfPresent(lltok::rparen
))
1948 return error(ParenLoc
, "expected ')'");
1950 if (!isPowerOf2_32(Value
))
1951 return error(AlignLoc
, "alignment is not a power of two");
1952 if (Value
> Value::MaximumAlignment
)
1953 return error(AlignLoc
, "huge alignments are not supported yet");
1954 Alignment
= Align(Value
);
1958 /// parseOptionalDerefAttrBytes
1960 /// ::= AttrKind '(' 4 ')'
1962 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1963 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind
,
1965 assert((AttrKind
== lltok::kw_dereferenceable
||
1966 AttrKind
== lltok::kw_dereferenceable_or_null
) &&
1970 if (!EatIfPresent(AttrKind
))
1972 LocTy ParenLoc
= Lex
.getLoc();
1973 if (!EatIfPresent(lltok::lparen
))
1974 return error(ParenLoc
, "expected '('");
1975 LocTy DerefLoc
= Lex
.getLoc();
1976 if (parseUInt64(Bytes
))
1978 ParenLoc
= Lex
.getLoc();
1979 if (!EatIfPresent(lltok::rparen
))
1980 return error(ParenLoc
, "expected ')'");
1982 return error(DerefLoc
, "dereferenceable bytes must be non-zero");
1986 /// parseOptionalCommaAlign
1990 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1992 bool LLParser::parseOptionalCommaAlign(MaybeAlign
&Alignment
,
1993 bool &AteExtraComma
) {
1994 AteExtraComma
= false;
1995 while (EatIfPresent(lltok::comma
)) {
1996 // Metadata at the end is an early exit.
1997 if (Lex
.getKind() == lltok::MetadataVar
) {
1998 AteExtraComma
= true;
2002 if (Lex
.getKind() != lltok::kw_align
)
2003 return error(Lex
.getLoc(), "expected metadata or 'align'");
2005 if (parseOptionalAlignment(Alignment
))
2012 /// parseOptionalCommaAddrSpace
2014 /// ::= ',' addrspace(1)
2016 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2018 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace
, LocTy
&Loc
,
2019 bool &AteExtraComma
) {
2020 AteExtraComma
= false;
2021 while (EatIfPresent(lltok::comma
)) {
2022 // Metadata at the end is an early exit.
2023 if (Lex
.getKind() == lltok::MetadataVar
) {
2024 AteExtraComma
= true;
2029 if (Lex
.getKind() != lltok::kw_addrspace
)
2030 return error(Lex
.getLoc(), "expected metadata or 'addrspace'");
2032 if (parseOptionalAddrSpace(AddrSpace
))
2039 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg
,
2040 Optional
<unsigned> &HowManyArg
) {
2043 auto StartParen
= Lex
.getLoc();
2044 if (!EatIfPresent(lltok::lparen
))
2045 return error(StartParen
, "expected '('");
2047 if (parseUInt32(BaseSizeArg
))
2050 if (EatIfPresent(lltok::comma
)) {
2051 auto HowManyAt
= Lex
.getLoc();
2053 if (parseUInt32(HowMany
))
2055 if (HowMany
== BaseSizeArg
)
2056 return error(HowManyAt
,
2057 "'allocsize' indices can't refer to the same parameter");
2058 HowManyArg
= HowMany
;
2062 auto EndParen
= Lex
.getLoc();
2063 if (!EatIfPresent(lltok::rparen
))
2064 return error(EndParen
, "expected ')'");
2068 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue
,
2069 unsigned &MaxValue
) {
2072 auto StartParen
= Lex
.getLoc();
2073 if (!EatIfPresent(lltok::lparen
))
2074 return error(StartParen
, "expected '('");
2076 if (parseUInt32(MinValue
))
2079 if (EatIfPresent(lltok::comma
)) {
2080 if (parseUInt32(MaxValue
))
2083 MaxValue
= MinValue
;
2085 auto EndParen
= Lex
.getLoc();
2086 if (!EatIfPresent(lltok::rparen
))
2087 return error(EndParen
, "expected ')'");
2091 /// parseScopeAndOrdering
2092 /// if isAtomic: ::= SyncScope? AtomicOrdering
2095 /// This sets Scope and Ordering to the parsed values.
2096 bool LLParser::parseScopeAndOrdering(bool IsAtomic
, SyncScope::ID
&SSID
,
2097 AtomicOrdering
&Ordering
) {
2101 return parseScope(SSID
) || parseOrdering(Ordering
);
2105 /// ::= syncscope("singlethread" | "<target scope>")?
2107 /// This sets synchronization scope ID to the ID of the parsed value.
2108 bool LLParser::parseScope(SyncScope::ID
&SSID
) {
2109 SSID
= SyncScope::System
;
2110 if (EatIfPresent(lltok::kw_syncscope
)) {
2111 auto StartParenAt
= Lex
.getLoc();
2112 if (!EatIfPresent(lltok::lparen
))
2113 return error(StartParenAt
, "Expected '(' in syncscope");
2116 auto SSNAt
= Lex
.getLoc();
2117 if (parseStringConstant(SSN
))
2118 return error(SSNAt
, "Expected synchronization scope name");
2120 auto EndParenAt
= Lex
.getLoc();
2121 if (!EatIfPresent(lltok::rparen
))
2122 return error(EndParenAt
, "Expected ')' in syncscope");
2124 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2131 /// ::= AtomicOrdering
2133 /// This sets Ordering to the parsed value.
2134 bool LLParser::parseOrdering(AtomicOrdering
&Ordering
) {
2135 switch (Lex
.getKind()) {
2137 return tokError("Expected ordering on atomic instruction");
2138 case lltok::kw_unordered
: Ordering
= AtomicOrdering::Unordered
; break;
2139 case lltok::kw_monotonic
: Ordering
= AtomicOrdering::Monotonic
; break;
2140 // Not specified yet:
2141 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2142 case lltok::kw_acquire
: Ordering
= AtomicOrdering::Acquire
; break;
2143 case lltok::kw_release
: Ordering
= AtomicOrdering::Release
; break;
2144 case lltok::kw_acq_rel
: Ordering
= AtomicOrdering::AcquireRelease
; break;
2145 case lltok::kw_seq_cst
:
2146 Ordering
= AtomicOrdering::SequentiallyConsistent
;
2153 /// parseOptionalStackAlignment
2155 /// ::= 'alignstack' '(' 4 ')'
2156 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment
) {
2158 if (!EatIfPresent(lltok::kw_alignstack
))
2160 LocTy ParenLoc
= Lex
.getLoc();
2161 if (!EatIfPresent(lltok::lparen
))
2162 return error(ParenLoc
, "expected '('");
2163 LocTy AlignLoc
= Lex
.getLoc();
2164 if (parseUInt32(Alignment
))
2166 ParenLoc
= Lex
.getLoc();
2167 if (!EatIfPresent(lltok::rparen
))
2168 return error(ParenLoc
, "expected ')'");
2169 if (!isPowerOf2_32(Alignment
))
2170 return error(AlignLoc
, "stack alignment is not a power of two");
2174 /// parseIndexList - This parses the index list for an insert/extractvalue
2175 /// instruction. This sets AteExtraComma in the case where we eat an extra
2176 /// comma at the end of the line and find that it is followed by metadata.
2177 /// Clients that don't allow metadata can call the version of this function that
2178 /// only takes one argument.
2181 /// ::= (',' uint32)+
2183 bool LLParser::parseIndexList(SmallVectorImpl
<unsigned> &Indices
,
2184 bool &AteExtraComma
) {
2185 AteExtraComma
= false;
2187 if (Lex
.getKind() != lltok::comma
)
2188 return tokError("expected ',' as start of index list");
2190 while (EatIfPresent(lltok::comma
)) {
2191 if (Lex
.getKind() == lltok::MetadataVar
) {
2192 if (Indices
.empty())
2193 return tokError("expected index");
2194 AteExtraComma
= true;
2198 if (parseUInt32(Idx
))
2200 Indices
.push_back(Idx
);
2206 //===----------------------------------------------------------------------===//
2208 //===----------------------------------------------------------------------===//
2210 /// parseType - parse a type.
2211 bool LLParser::parseType(Type
*&Result
, const Twine
&Msg
, bool AllowVoid
) {
2212 SMLoc TypeLoc
= Lex
.getLoc();
2213 switch (Lex
.getKind()) {
2215 return tokError(Msg
);
2217 // Type ::= 'float' | 'void' (etc)
2218 Result
= Lex
.getTyVal();
2222 // Type ::= StructType
2223 if (parseAnonStructType(Result
, false))
2226 case lltok::lsquare
:
2227 // Type ::= '[' ... ']'
2228 Lex
.Lex(); // eat the lsquare.
2229 if (parseArrayVectorType(Result
, false))
2232 case lltok::less
: // Either vector or packed struct.
2233 // Type ::= '<' ... '>'
2235 if (Lex
.getKind() == lltok::lbrace
) {
2236 if (parseAnonStructType(Result
, true) ||
2237 parseToken(lltok::greater
, "expected '>' at end of packed struct"))
2239 } else if (parseArrayVectorType(Result
, true))
2242 case lltok::LocalVar
: {
2244 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Lex
.getStrVal()];
2246 // If the type hasn't been defined yet, create a forward definition and
2247 // remember where that forward def'n was seen (in case it never is defined).
2249 Entry
.first
= StructType::create(Context
, Lex
.getStrVal());
2250 Entry
.second
= Lex
.getLoc();
2252 Result
= Entry
.first
;
2257 case lltok::LocalVarID
: {
2259 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[Lex
.getUIntVal()];
2261 // If the type hasn't been defined yet, create a forward definition and
2262 // remember where that forward def'n was seen (in case it never is defined).
2264 Entry
.first
= StructType::create(Context
);
2265 Entry
.second
= Lex
.getLoc();
2267 Result
= Entry
.first
;
2273 // Handle (explicit) opaque pointer types (not --force-opaque-pointers).
2275 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2276 if (Result
->isOpaquePointerTy()) {
2278 if (parseOptionalAddrSpace(AddrSpace
))
2280 Result
= PointerType::get(getContext(), AddrSpace
);
2282 // Give a nice error for 'ptr*'.
2283 if (Lex
.getKind() == lltok::star
)
2284 return tokError("ptr* is invalid - use ptr instead");
2286 // Fall through to parsing the type suffixes only if this 'ptr' is a
2287 // function return. Otherwise, return success, implicitly rejecting other
2289 if (Lex
.getKind() != lltok::lparen
)
2293 // parse the type suffixes.
2295 switch (Lex
.getKind()) {
2298 if (!AllowVoid
&& Result
->isVoidTy())
2299 return error(TypeLoc
, "void type only allowed for function results");
2302 // Type ::= Type '*'
2304 if (Result
->isLabelTy())
2305 return tokError("basic block pointers are invalid");
2306 if (Result
->isVoidTy())
2307 return tokError("pointers to void are invalid - use i8* instead");
2308 if (!PointerType::isValidElementType(Result
))
2309 return tokError("pointer to this type is invalid");
2310 Result
= PointerType::getUnqual(Result
);
2314 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2315 case lltok::kw_addrspace
: {
2316 if (Result
->isLabelTy())
2317 return tokError("basic block pointers are invalid");
2318 if (Result
->isVoidTy())
2319 return tokError("pointers to void are invalid; use i8* instead");
2320 if (!PointerType::isValidElementType(Result
))
2321 return tokError("pointer to this type is invalid");
2323 if (parseOptionalAddrSpace(AddrSpace
) ||
2324 parseToken(lltok::star
, "expected '*' in address space"))
2327 Result
= PointerType::get(Result
, AddrSpace
);
2331 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2333 if (parseFunctionType(Result
))
2340 /// parseParameterList
2342 /// ::= '(' Arg (',' Arg)* ')'
2344 /// ::= Type OptionalAttributes Value OptionalAttributes
2345 bool LLParser::parseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
2346 PerFunctionState
&PFS
, bool IsMustTailCall
,
2347 bool InVarArgsFunc
) {
2348 if (parseToken(lltok::lparen
, "expected '(' in call"))
2351 while (Lex
.getKind() != lltok::rparen
) {
2352 // If this isn't the first argument, we need a comma.
2353 if (!ArgList
.empty() &&
2354 parseToken(lltok::comma
, "expected ',' in argument list"))
2357 // parse an ellipsis if this is a musttail call in a variadic function.
2358 if (Lex
.getKind() == lltok::dotdotdot
) {
2359 const char *Msg
= "unexpected ellipsis in argument list for ";
2360 if (!IsMustTailCall
)
2361 return tokError(Twine(Msg
) + "non-musttail call");
2363 return tokError(Twine(Msg
) + "musttail call in non-varargs function");
2364 Lex
.Lex(); // Lex the '...', it is purely for readability.
2365 return parseToken(lltok::rparen
, "expected ')' at end of argument list");
2368 // parse the argument.
2370 Type
*ArgTy
= nullptr;
2371 AttrBuilder ArgAttrs
;
2373 if (parseType(ArgTy
, ArgLoc
))
2376 if (ArgTy
->isMetadataTy()) {
2377 if (parseMetadataAsValue(V
, PFS
))
2380 // Otherwise, handle normal operands.
2381 if (parseOptionalParamAttrs(ArgAttrs
) || parseValue(ArgTy
, V
, PFS
))
2384 ArgList
.push_back(ParamInfo(
2385 ArgLoc
, V
, AttributeSet::get(V
->getContext(), ArgAttrs
)));
2388 if (IsMustTailCall
&& InVarArgsFunc
)
2389 return tokError("expected '...' at end of argument list for musttail call "
2390 "in varargs function");
2392 Lex
.Lex(); // Lex the ')'.
2396 /// parseRequiredTypeAttr
2397 /// ::= attrname(<ty>)
2398 bool LLParser::parseRequiredTypeAttr(AttrBuilder
&B
, lltok::Kind AttrToken
,
2399 Attribute::AttrKind AttrKind
) {
2401 if (!EatIfPresent(AttrToken
))
2403 if (!EatIfPresent(lltok::lparen
))
2404 return error(Lex
.getLoc(), "expected '('");
2407 if (!EatIfPresent(lltok::rparen
))
2408 return error(Lex
.getLoc(), "expected ')'");
2410 B
.addTypeAttr(AttrKind
, Ty
);
2414 /// parseOptionalOperandBundles
2416 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2419 /// ::= bundle-tag '(' ')'
2420 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2422 /// bundle-tag ::= String Constant
2423 bool LLParser::parseOptionalOperandBundles(
2424 SmallVectorImpl
<OperandBundleDef
> &BundleList
, PerFunctionState
&PFS
) {
2425 LocTy BeginLoc
= Lex
.getLoc();
2426 if (!EatIfPresent(lltok::lsquare
))
2429 while (Lex
.getKind() != lltok::rsquare
) {
2430 // If this isn't the first operand bundle, we need a comma.
2431 if (!BundleList
.empty() &&
2432 parseToken(lltok::comma
, "expected ',' in input list"))
2436 if (parseStringConstant(Tag
))
2439 if (parseToken(lltok::lparen
, "expected '(' in operand bundle"))
2442 std::vector
<Value
*> Inputs
;
2443 while (Lex
.getKind() != lltok::rparen
) {
2444 // If this isn't the first input, we need a comma.
2445 if (!Inputs
.empty() &&
2446 parseToken(lltok::comma
, "expected ',' in input list"))
2450 Value
*Input
= nullptr;
2451 if (parseType(Ty
) || parseValue(Ty
, Input
, PFS
))
2453 Inputs
.push_back(Input
);
2456 BundleList
.emplace_back(std::move(Tag
), std::move(Inputs
));
2458 Lex
.Lex(); // Lex the ')'.
2461 if (BundleList
.empty())
2462 return error(BeginLoc
, "operand bundle set must not be empty");
2464 Lex
.Lex(); // Lex the ']'.
2468 /// parseArgumentList - parse the argument list for a function type or function
2470 /// ::= '(' ArgTypeListI ')'
2474 /// ::= ArgTypeList ',' '...'
2475 /// ::= ArgType (',' ArgType)*
2477 bool LLParser::parseArgumentList(SmallVectorImpl
<ArgInfo
> &ArgList
,
2479 unsigned CurValID
= 0;
2481 assert(Lex
.getKind() == lltok::lparen
);
2482 Lex
.Lex(); // eat the (.
2484 if (Lex
.getKind() == lltok::rparen
) {
2486 } else if (Lex
.getKind() == lltok::dotdotdot
) {
2490 LocTy TypeLoc
= Lex
.getLoc();
2491 Type
*ArgTy
= nullptr;
2495 if (parseType(ArgTy
) || parseOptionalParamAttrs(Attrs
))
2498 if (ArgTy
->isVoidTy())
2499 return error(TypeLoc
, "argument can not have void type");
2501 if (Lex
.getKind() == lltok::LocalVar
) {
2502 Name
= Lex
.getStrVal();
2504 } else if (Lex
.getKind() == lltok::LocalVarID
) {
2505 if (Lex
.getUIntVal() != CurValID
)
2506 return error(TypeLoc
, "argument expected to be numbered '%" +
2507 Twine(CurValID
) + "'");
2512 if (!FunctionType::isValidArgumentType(ArgTy
))
2513 return error(TypeLoc
, "invalid type for function argument");
2515 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2516 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2519 while (EatIfPresent(lltok::comma
)) {
2520 // Handle ... at end of arg list.
2521 if (EatIfPresent(lltok::dotdotdot
)) {
2526 // Otherwise must be an argument type.
2527 TypeLoc
= Lex
.getLoc();
2528 if (parseType(ArgTy
) || parseOptionalParamAttrs(Attrs
))
2531 if (ArgTy
->isVoidTy())
2532 return error(TypeLoc
, "argument can not have void type");
2534 if (Lex
.getKind() == lltok::LocalVar
) {
2535 Name
= Lex
.getStrVal();
2538 if (Lex
.getKind() == lltok::LocalVarID
) {
2539 if (Lex
.getUIntVal() != CurValID
)
2540 return error(TypeLoc
, "argument expected to be numbered '%" +
2541 Twine(CurValID
) + "'");
2548 if (!ArgTy
->isFirstClassType())
2549 return error(TypeLoc
, "invalid type for function argument");
2551 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2552 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2557 return parseToken(lltok::rparen
, "expected ')' at end of argument list");
2560 /// parseFunctionType
2561 /// ::= Type ArgumentList OptionalAttrs
2562 bool LLParser::parseFunctionType(Type
*&Result
) {
2563 assert(Lex
.getKind() == lltok::lparen
);
2565 if (!FunctionType::isValidReturnType(Result
))
2566 return tokError("invalid function return type");
2568 SmallVector
<ArgInfo
, 8> ArgList
;
2570 if (parseArgumentList(ArgList
, IsVarArg
))
2573 // Reject names on the arguments lists.
2574 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2575 if (!ArgList
[i
].Name
.empty())
2576 return error(ArgList
[i
].Loc
, "argument name invalid in function type");
2577 if (ArgList
[i
].Attrs
.hasAttributes())
2578 return error(ArgList
[i
].Loc
,
2579 "argument attributes invalid in function type");
2582 SmallVector
<Type
*, 16> ArgListTy
;
2583 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2584 ArgListTy
.push_back(ArgList
[i
].Ty
);
2586 Result
= FunctionType::get(Result
, ArgListTy
, IsVarArg
);
2590 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2592 bool LLParser::parseAnonStructType(Type
*&Result
, bool Packed
) {
2593 SmallVector
<Type
*, 8> Elts
;
2594 if (parseStructBody(Elts
))
2597 Result
= StructType::get(Context
, Elts
, Packed
);
2601 /// parseStructDefinition - parse a struct in a 'type' definition.
2602 bool LLParser::parseStructDefinition(SMLoc TypeLoc
, StringRef Name
,
2603 std::pair
<Type
*, LocTy
> &Entry
,
2605 // If the type was already defined, diagnose the redefinition.
2606 if (Entry
.first
&& !Entry
.second
.isValid())
2607 return error(TypeLoc
, "redefinition of type");
2609 // If we have opaque, just return without filling in the definition for the
2610 // struct. This counts as a definition as far as the .ll file goes.
2611 if (EatIfPresent(lltok::kw_opaque
)) {
2612 // This type is being defined, so clear the location to indicate this.
2613 Entry
.second
= SMLoc();
2615 // If this type number has never been uttered, create it.
2617 Entry
.first
= StructType::create(Context
, Name
);
2618 ResultTy
= Entry
.first
;
2622 // If the type starts with '<', then it is either a packed struct or a vector.
2623 bool isPacked
= EatIfPresent(lltok::less
);
2625 // If we don't have a struct, then we have a random type alias, which we
2626 // accept for compatibility with old files. These types are not allowed to be
2627 // forward referenced and not allowed to be recursive.
2628 if (Lex
.getKind() != lltok::lbrace
) {
2630 return error(TypeLoc
, "forward references to non-struct type");
2634 return parseArrayVectorType(ResultTy
, true);
2635 return parseType(ResultTy
);
2638 // This type is being defined, so clear the location to indicate this.
2639 Entry
.second
= SMLoc();
2641 // If this type number has never been uttered, create it.
2643 Entry
.first
= StructType::create(Context
, Name
);
2645 StructType
*STy
= cast
<StructType
>(Entry
.first
);
2647 SmallVector
<Type
*, 8> Body
;
2648 if (parseStructBody(Body
) ||
2649 (isPacked
&& parseToken(lltok::greater
, "expected '>' in packed struct")))
2652 STy
->setBody(Body
, isPacked
);
2657 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2660 /// ::= '{' Type (',' Type)* '}'
2661 /// ::= '<' '{' '}' '>'
2662 /// ::= '<' '{' Type (',' Type)* '}' '>'
2663 bool LLParser::parseStructBody(SmallVectorImpl
<Type
*> &Body
) {
2664 assert(Lex
.getKind() == lltok::lbrace
);
2665 Lex
.Lex(); // Consume the '{'
2667 // Handle the empty struct.
2668 if (EatIfPresent(lltok::rbrace
))
2671 LocTy EltTyLoc
= Lex
.getLoc();
2677 if (!StructType::isValidElementType(Ty
))
2678 return error(EltTyLoc
, "invalid element type for struct");
2680 while (EatIfPresent(lltok::comma
)) {
2681 EltTyLoc
= Lex
.getLoc();
2685 if (!StructType::isValidElementType(Ty
))
2686 return error(EltTyLoc
, "invalid element type for struct");
2691 return parseToken(lltok::rbrace
, "expected '}' at end of struct");
2694 /// parseArrayVectorType - parse an array or vector type, assuming the first
2695 /// token has already been consumed.
2697 /// ::= '[' APSINTVAL 'x' Types ']'
2698 /// ::= '<' APSINTVAL 'x' Types '>'
2699 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2700 bool LLParser::parseArrayVectorType(Type
*&Result
, bool IsVector
) {
2701 bool Scalable
= false;
2703 if (IsVector
&& Lex
.getKind() == lltok::kw_vscale
) {
2704 Lex
.Lex(); // consume the 'vscale'
2705 if (parseToken(lltok::kw_x
, "expected 'x' after vscale"))
2711 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
2712 Lex
.getAPSIntVal().getBitWidth() > 64)
2713 return tokError("expected number in address space");
2715 LocTy SizeLoc
= Lex
.getLoc();
2716 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
2719 if (parseToken(lltok::kw_x
, "expected 'x' after element count"))
2722 LocTy TypeLoc
= Lex
.getLoc();
2723 Type
*EltTy
= nullptr;
2724 if (parseType(EltTy
))
2727 if (parseToken(IsVector
? lltok::greater
: lltok::rsquare
,
2728 "expected end of sequential type"))
2733 return error(SizeLoc
, "zero element vector is illegal");
2734 if ((unsigned)Size
!= Size
)
2735 return error(SizeLoc
, "size too large for vector");
2736 if (!VectorType::isValidElementType(EltTy
))
2737 return error(TypeLoc
, "invalid vector element type");
2738 Result
= VectorType::get(EltTy
, unsigned(Size
), Scalable
);
2740 if (!ArrayType::isValidElementType(EltTy
))
2741 return error(TypeLoc
, "invalid array element type");
2742 Result
= ArrayType::get(EltTy
, Size
);
2747 //===----------------------------------------------------------------------===//
2748 // Function Semantic Analysis.
2749 //===----------------------------------------------------------------------===//
2751 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
2753 : P(p
), F(f
), FunctionNumber(functionNumber
) {
2755 // Insert unnamed arguments into the NumberedVals list.
2756 for (Argument
&A
: F
.args())
2758 NumberedVals
.push_back(&A
);
2761 LLParser::PerFunctionState::~PerFunctionState() {
2762 // If there were any forward referenced non-basicblock values, delete them.
2764 for (const auto &P
: ForwardRefVals
) {
2765 if (isa
<BasicBlock
>(P
.second
.first
))
2767 P
.second
.first
->replaceAllUsesWith(
2768 UndefValue::get(P
.second
.first
->getType()));
2769 P
.second
.first
->deleteValue();
2772 for (const auto &P
: ForwardRefValIDs
) {
2773 if (isa
<BasicBlock
>(P
.second
.first
))
2775 P
.second
.first
->replaceAllUsesWith(
2776 UndefValue::get(P
.second
.first
->getType()));
2777 P
.second
.first
->deleteValue();
2781 bool LLParser::PerFunctionState::finishFunction() {
2782 if (!ForwardRefVals
.empty())
2783 return P
.error(ForwardRefVals
.begin()->second
.second
,
2784 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
2786 if (!ForwardRefValIDs
.empty())
2787 return P
.error(ForwardRefValIDs
.begin()->second
.second
,
2788 "use of undefined value '%" +
2789 Twine(ForwardRefValIDs
.begin()->first
) + "'");
2793 /// getVal - Get a value with the specified name or ID, creating a
2794 /// forward reference record if needed. This can return null if the value
2795 /// exists but does not have the right type.
2796 Value
*LLParser::PerFunctionState::getVal(const std::string
&Name
, Type
*Ty
,
2797 LocTy Loc
, bool IsCall
) {
2798 // Look this name up in the normal function symbol table.
2799 Value
*Val
= F
.getValueSymbolTable()->lookup(Name
);
2801 // If this is a forward reference for the value, see if we already created a
2802 // forward ref record.
2804 auto I
= ForwardRefVals
.find(Name
);
2805 if (I
!= ForwardRefVals
.end())
2806 Val
= I
->second
.first
;
2809 // If we have the value in the symbol table or fwd-ref table, return it.
2811 return P
.checkValidVariableType(Loc
, "%" + Name
, Ty
, Val
, IsCall
);
2813 // Don't make placeholders with invalid type.
2814 if (!Ty
->isFirstClassType()) {
2815 P
.error(Loc
, "invalid use of a non-first-class type");
2819 // Otherwise, create a new forward reference for this value and remember it.
2821 if (Ty
->isLabelTy()) {
2822 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
2824 FwdVal
= new Argument(Ty
, Name
);
2827 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
2831 Value
*LLParser::PerFunctionState::getVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
2833 // Look this name up in the normal function symbol table.
2834 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
2836 // If this is a forward reference for the value, see if we already created a
2837 // forward ref record.
2839 auto I
= ForwardRefValIDs
.find(ID
);
2840 if (I
!= ForwardRefValIDs
.end())
2841 Val
= I
->second
.first
;
2844 // If we have the value in the symbol table or fwd-ref table, return it.
2846 return P
.checkValidVariableType(Loc
, "%" + Twine(ID
), Ty
, Val
, IsCall
);
2848 if (!Ty
->isFirstClassType()) {
2849 P
.error(Loc
, "invalid use of a non-first-class type");
2853 // Otherwise, create a new forward reference for this value and remember it.
2855 if (Ty
->isLabelTy()) {
2856 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
2858 FwdVal
= new Argument(Ty
);
2861 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
2865 /// setInstName - After an instruction is parsed and inserted into its
2866 /// basic block, this installs its name.
2867 bool LLParser::PerFunctionState::setInstName(int NameID
,
2868 const std::string
&NameStr
,
2869 LocTy NameLoc
, Instruction
*Inst
) {
2870 // If this instruction has void type, it cannot have a name or ID specified.
2871 if (Inst
->getType()->isVoidTy()) {
2872 if (NameID
!= -1 || !NameStr
.empty())
2873 return P
.error(NameLoc
, "instructions returning void cannot have a name");
2877 // If this was a numbered instruction, verify that the instruction is the
2878 // expected value and resolve any forward references.
2879 if (NameStr
.empty()) {
2880 // If neither a name nor an ID was specified, just use the next ID.
2882 NameID
= NumberedVals
.size();
2884 if (unsigned(NameID
) != NumberedVals
.size())
2885 return P
.error(NameLoc
, "instruction expected to be numbered '%" +
2886 Twine(NumberedVals
.size()) + "'");
2888 auto FI
= ForwardRefValIDs
.find(NameID
);
2889 if (FI
!= ForwardRefValIDs
.end()) {
2890 Value
*Sentinel
= FI
->second
.first
;
2891 if (Sentinel
->getType() != Inst
->getType())
2892 return P
.error(NameLoc
, "instruction forward referenced with type '" +
2893 getTypeString(FI
->second
.first
->getType()) +
2896 Sentinel
->replaceAllUsesWith(Inst
);
2897 Sentinel
->deleteValue();
2898 ForwardRefValIDs
.erase(FI
);
2901 NumberedVals
.push_back(Inst
);
2905 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2906 auto FI
= ForwardRefVals
.find(NameStr
);
2907 if (FI
!= ForwardRefVals
.end()) {
2908 Value
*Sentinel
= FI
->second
.first
;
2909 if (Sentinel
->getType() != Inst
->getType())
2910 return P
.error(NameLoc
, "instruction forward referenced with type '" +
2911 getTypeString(FI
->second
.first
->getType()) +
2914 Sentinel
->replaceAllUsesWith(Inst
);
2915 Sentinel
->deleteValue();
2916 ForwardRefVals
.erase(FI
);
2919 // Set the name on the instruction.
2920 Inst
->setName(NameStr
);
2922 if (Inst
->getName() != NameStr
)
2923 return P
.error(NameLoc
, "multiple definition of local value named '" +
2928 /// getBB - Get a basic block with the specified name or ID, creating a
2929 /// forward reference record if needed.
2930 BasicBlock
*LLParser::PerFunctionState::getBB(const std::string
&Name
,
2932 return dyn_cast_or_null
<BasicBlock
>(
2933 getVal(Name
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
2936 BasicBlock
*LLParser::PerFunctionState::getBB(unsigned ID
, LocTy Loc
) {
2937 return dyn_cast_or_null
<BasicBlock
>(
2938 getVal(ID
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
2941 /// defineBB - Define the specified basic block, which is either named or
2942 /// unnamed. If there is an error, this returns null otherwise it returns
2943 /// the block being defined.
2944 BasicBlock
*LLParser::PerFunctionState::defineBB(const std::string
&Name
,
2945 int NameID
, LocTy Loc
) {
2948 if (NameID
!= -1 && unsigned(NameID
) != NumberedVals
.size()) {
2949 P
.error(Loc
, "label expected to be numbered '" +
2950 Twine(NumberedVals
.size()) + "'");
2953 BB
= getBB(NumberedVals
.size(), Loc
);
2955 P
.error(Loc
, "unable to create block numbered '" +
2956 Twine(NumberedVals
.size()) + "'");
2960 BB
= getBB(Name
, Loc
);
2962 P
.error(Loc
, "unable to create block named '" + Name
+ "'");
2967 // Move the block to the end of the function. Forward ref'd blocks are
2968 // inserted wherever they happen to be referenced.
2969 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
2971 // Remove the block from forward ref sets.
2973 ForwardRefValIDs
.erase(NumberedVals
.size());
2974 NumberedVals
.push_back(BB
);
2976 // BB forward references are already in the function symbol table.
2977 ForwardRefVals
.erase(Name
);
2983 //===----------------------------------------------------------------------===//
2985 //===----------------------------------------------------------------------===//
2987 /// parseValID - parse an abstract value that doesn't necessarily have a
2988 /// type implied. For example, if we parse "4" we don't know what integer type
2989 /// it has. The value will later be combined with its type and checked for
2990 /// sanity. PFS is used to convert function-local operands of metadata (since
2991 /// metadata operands are not just parsed here but also converted to values).
2992 /// PFS can be null when we are not parsing metadata values inside a function.
2993 bool LLParser::parseValID(ValID
&ID
, PerFunctionState
*PFS
, Type
*ExpectedTy
) {
2994 ID
.Loc
= Lex
.getLoc();
2995 switch (Lex
.getKind()) {
2997 return tokError("expected value token");
2998 case lltok::GlobalID
: // @42
2999 ID
.UIntVal
= Lex
.getUIntVal();
3000 ID
.Kind
= ValID::t_GlobalID
;
3002 case lltok::GlobalVar
: // @foo
3003 ID
.StrVal
= Lex
.getStrVal();
3004 ID
.Kind
= ValID::t_GlobalName
;
3006 case lltok::LocalVarID
: // %42
3007 ID
.UIntVal
= Lex
.getUIntVal();
3008 ID
.Kind
= ValID::t_LocalID
;
3010 case lltok::LocalVar
: // %foo
3011 ID
.StrVal
= Lex
.getStrVal();
3012 ID
.Kind
= ValID::t_LocalName
;
3015 ID
.APSIntVal
= Lex
.getAPSIntVal();
3016 ID
.Kind
= ValID::t_APSInt
;
3018 case lltok::APFloat
:
3019 ID
.APFloatVal
= Lex
.getAPFloatVal();
3020 ID
.Kind
= ValID::t_APFloat
;
3022 case lltok::kw_true
:
3023 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
3024 ID
.Kind
= ValID::t_Constant
;
3026 case lltok::kw_false
:
3027 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
3028 ID
.Kind
= ValID::t_Constant
;
3030 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
3031 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
3032 case lltok::kw_poison
: ID
.Kind
= ValID::t_Poison
; break;
3033 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
3034 case lltok::kw_none
: ID
.Kind
= ValID::t_None
; break;
3036 case lltok::lbrace
: {
3037 // ValID ::= '{' ConstVector '}'
3039 SmallVector
<Constant
*, 16> Elts
;
3040 if (parseGlobalValueVector(Elts
) ||
3041 parseToken(lltok::rbrace
, "expected end of struct constant"))
3044 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3045 ID
.UIntVal
= Elts
.size();
3046 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3047 Elts
.size() * sizeof(Elts
[0]));
3048 ID
.Kind
= ValID::t_ConstantStruct
;
3052 // ValID ::= '<' ConstVector '>' --> Vector.
3053 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3055 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
3057 SmallVector
<Constant
*, 16> Elts
;
3058 LocTy FirstEltLoc
= Lex
.getLoc();
3059 if (parseGlobalValueVector(Elts
) ||
3061 parseToken(lltok::rbrace
, "expected end of packed struct")) ||
3062 parseToken(lltok::greater
, "expected end of constant"))
3065 if (isPackedStruct
) {
3066 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3067 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3068 Elts
.size() * sizeof(Elts
[0]));
3069 ID
.UIntVal
= Elts
.size();
3070 ID
.Kind
= ValID::t_PackedConstantStruct
;
3075 return error(ID
.Loc
, "constant vector must not be empty");
3077 if (!Elts
[0]->getType()->isIntegerTy() &&
3078 !Elts
[0]->getType()->isFloatingPointTy() &&
3079 !Elts
[0]->getType()->isPointerTy())
3082 "vector elements must have integer, pointer or floating point type");
3084 // Verify that all the vector elements have the same type.
3085 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
3086 if (Elts
[i
]->getType() != Elts
[0]->getType())
3087 return error(FirstEltLoc
, "vector element #" + Twine(i
) +
3088 " is not of type '" +
3089 getTypeString(Elts
[0]->getType()));
3091 ID
.ConstantVal
= ConstantVector::get(Elts
);
3092 ID
.Kind
= ValID::t_Constant
;
3095 case lltok::lsquare
: { // Array Constant
3097 SmallVector
<Constant
*, 16> Elts
;
3098 LocTy FirstEltLoc
= Lex
.getLoc();
3099 if (parseGlobalValueVector(Elts
) ||
3100 parseToken(lltok::rsquare
, "expected end of array constant"))
3103 // Handle empty element.
3105 // Use undef instead of an array because it's inconvenient to determine
3106 // the element type at this point, there being no elements to examine.
3107 ID
.Kind
= ValID::t_EmptyArray
;
3111 if (!Elts
[0]->getType()->isFirstClassType())
3112 return error(FirstEltLoc
, "invalid array element type: " +
3113 getTypeString(Elts
[0]->getType()));
3115 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
3117 // Verify all elements are correct type!
3118 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
3119 if (Elts
[i
]->getType() != Elts
[0]->getType())
3120 return error(FirstEltLoc
, "array element #" + Twine(i
) +
3121 " is not of type '" +
3122 getTypeString(Elts
[0]->getType()));
3125 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
);
3126 ID
.Kind
= ValID::t_Constant
;
3129 case lltok::kw_c
: // c "foo"
3131 ID
.ConstantVal
= ConstantDataArray::getString(Context
, Lex
.getStrVal(),
3133 if (parseToken(lltok::StringConstant
, "expected string"))
3135 ID
.Kind
= ValID::t_Constant
;
3138 case lltok::kw_asm
: {
3139 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3141 bool HasSideEffect
, AlignStack
, AsmDialect
, CanThrow
;
3143 if (parseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
3144 parseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
3145 parseOptionalToken(lltok::kw_inteldialect
, AsmDialect
) ||
3146 parseOptionalToken(lltok::kw_unwind
, CanThrow
) ||
3147 parseStringConstant(ID
.StrVal
) ||
3148 parseToken(lltok::comma
, "expected comma in inline asm expression") ||
3149 parseToken(lltok::StringConstant
, "expected constraint string"))
3151 ID
.StrVal2
= Lex
.getStrVal();
3152 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
) << 1) |
3153 (unsigned(AsmDialect
) << 2) | (unsigned(CanThrow
) << 3);
3154 ID
.Kind
= ValID::t_InlineAsm
;
3158 case lltok::kw_blockaddress
: {
3159 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3164 if (parseToken(lltok::lparen
, "expected '(' in block address expression") ||
3165 parseValID(Fn
, PFS
) ||
3166 parseToken(lltok::comma
,
3167 "expected comma in block address expression") ||
3168 parseValID(Label
, PFS
) ||
3169 parseToken(lltok::rparen
, "expected ')' in block address expression"))
3172 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3173 return error(Fn
.Loc
, "expected function name in blockaddress");
3174 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
3175 return error(Label
.Loc
, "expected basic block name in blockaddress");
3177 // Try to find the function (but skip it if it's forward-referenced).
3178 GlobalValue
*GV
= nullptr;
3179 if (Fn
.Kind
== ValID::t_GlobalID
) {
3180 if (Fn
.UIntVal
< NumberedVals
.size())
3181 GV
= NumberedVals
[Fn
.UIntVal
];
3182 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3183 GV
= M
->getNamedValue(Fn
.StrVal
);
3185 Function
*F
= nullptr;
3187 // Confirm that it's actually a function with a definition.
3188 if (!isa
<Function
>(GV
))
3189 return error(Fn
.Loc
, "expected function name in blockaddress");
3190 F
= cast
<Function
>(GV
);
3191 if (F
->isDeclaration())
3192 return error(Fn
.Loc
, "cannot take blockaddress inside a declaration");
3196 // Make a global variable as a placeholder for this reference.
3197 GlobalValue
*&FwdRef
=
3198 ForwardRefBlockAddresses
.insert(std::make_pair(
3200 std::map
<ValID
, GlobalValue
*>()))
3201 .first
->second
.insert(std::make_pair(std::move(Label
), nullptr))
3206 // If we know the type that the blockaddress is being assigned to,
3207 // we can use the address space of that type.
3208 if (!ExpectedTy
->isPointerTy())
3209 return error(ID
.Loc
,
3210 "type of blockaddress must be a pointer and not '" +
3211 getTypeString(ExpectedTy
) + "'");
3212 FwdDeclAS
= ExpectedTy
->getPointerAddressSpace();
3214 // Otherwise, we default the address space of the current function.
3215 FwdDeclAS
= PFS
->getFunction().getAddressSpace();
3217 llvm_unreachable("Unknown address space for blockaddress");
3219 FwdRef
= new GlobalVariable(
3220 *M
, Type::getInt8Ty(Context
), false, GlobalValue::InternalLinkage
,
3221 nullptr, "", nullptr, GlobalValue::NotThreadLocal
, FwdDeclAS
);
3224 ID
.ConstantVal
= FwdRef
;
3225 ID
.Kind
= ValID::t_Constant
;
3229 // We found the function; now find the basic block. Don't use PFS, since we
3230 // might be inside a constant expression.
3232 if (BlockAddressPFS
&& F
== &BlockAddressPFS
->getFunction()) {
3233 if (Label
.Kind
== ValID::t_LocalID
)
3234 BB
= BlockAddressPFS
->getBB(Label
.UIntVal
, Label
.Loc
);
3236 BB
= BlockAddressPFS
->getBB(Label
.StrVal
, Label
.Loc
);
3238 return error(Label
.Loc
, "referenced value is not a basic block");
3240 if (Label
.Kind
== ValID::t_LocalID
)
3241 return error(Label
.Loc
, "cannot take address of numeric label after "
3242 "the function is defined");
3243 BB
= dyn_cast_or_null
<BasicBlock
>(
3244 F
->getValueSymbolTable()->lookup(Label
.StrVal
));
3246 return error(Label
.Loc
, "referenced value is not a basic block");
3249 ID
.ConstantVal
= BlockAddress::get(F
, BB
);
3250 ID
.Kind
= ValID::t_Constant
;
3254 case lltok::kw_dso_local_equivalent
: {
3255 // ValID ::= 'dso_local_equivalent' @foo
3260 if (parseValID(Fn
, PFS
))
3263 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3264 return error(Fn
.Loc
,
3265 "expected global value name in dso_local_equivalent");
3267 // Try to find the function (but skip it if it's forward-referenced).
3268 GlobalValue
*GV
= nullptr;
3269 if (Fn
.Kind
== ValID::t_GlobalID
) {
3270 if (Fn
.UIntVal
< NumberedVals
.size())
3271 GV
= NumberedVals
[Fn
.UIntVal
];
3272 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3273 GV
= M
->getNamedValue(Fn
.StrVal
);
3276 assert(GV
&& "Could not find a corresponding global variable");
3278 if (!GV
->getValueType()->isFunctionTy())
3279 return error(Fn
.Loc
, "expected a function, alias to function, or ifunc "
3280 "in dso_local_equivalent");
3282 ID
.ConstantVal
= DSOLocalEquivalent::get(GV
);
3283 ID
.Kind
= ValID::t_Constant
;
3287 case lltok::kw_trunc
:
3288 case lltok::kw_zext
:
3289 case lltok::kw_sext
:
3290 case lltok::kw_fptrunc
:
3291 case lltok::kw_fpext
:
3292 case lltok::kw_bitcast
:
3293 case lltok::kw_addrspacecast
:
3294 case lltok::kw_uitofp
:
3295 case lltok::kw_sitofp
:
3296 case lltok::kw_fptoui
:
3297 case lltok::kw_fptosi
:
3298 case lltok::kw_inttoptr
:
3299 case lltok::kw_ptrtoint
: {
3300 unsigned Opc
= Lex
.getUIntVal();
3301 Type
*DestTy
= nullptr;
3304 if (parseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
3305 parseGlobalTypeAndValue(SrcVal
) ||
3306 parseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
3307 parseType(DestTy
) ||
3308 parseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
3310 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
3311 return error(ID
.Loc
, "invalid cast opcode for cast from '" +
3312 getTypeString(SrcVal
->getType()) + "' to '" +
3313 getTypeString(DestTy
) + "'");
3314 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
3316 ID
.Kind
= ValID::t_Constant
;
3319 case lltok::kw_extractvalue
: {
3322 SmallVector
<unsigned, 4> Indices
;
3323 if (parseToken(lltok::lparen
,
3324 "expected '(' in extractvalue constantexpr") ||
3325 parseGlobalTypeAndValue(Val
) || parseIndexList(Indices
) ||
3326 parseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
3329 if (!Val
->getType()->isAggregateType())
3330 return error(ID
.Loc
, "extractvalue operand must be aggregate type");
3331 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
3332 return error(ID
.Loc
, "invalid indices for extractvalue");
3333 ID
.ConstantVal
= ConstantExpr::getExtractValue(Val
, Indices
);
3334 ID
.Kind
= ValID::t_Constant
;
3337 case lltok::kw_insertvalue
: {
3339 Constant
*Val0
, *Val1
;
3340 SmallVector
<unsigned, 4> Indices
;
3341 if (parseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr") ||
3342 parseGlobalTypeAndValue(Val0
) ||
3343 parseToken(lltok::comma
,
3344 "expected comma in insertvalue constantexpr") ||
3345 parseGlobalTypeAndValue(Val1
) || parseIndexList(Indices
) ||
3346 parseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
3348 if (!Val0
->getType()->isAggregateType())
3349 return error(ID
.Loc
, "insertvalue operand must be aggregate type");
3351 ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
3353 return error(ID
.Loc
, "invalid indices for insertvalue");
3354 if (IndexedType
!= Val1
->getType())
3355 return error(ID
.Loc
, "insertvalue operand and field disagree in type: '" +
3356 getTypeString(Val1
->getType()) +
3357 "' instead of '" + getTypeString(IndexedType
) +
3359 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
, Indices
);
3360 ID
.Kind
= ValID::t_Constant
;
3363 case lltok::kw_icmp
:
3364 case lltok::kw_fcmp
: {
3365 unsigned PredVal
, Opc
= Lex
.getUIntVal();
3366 Constant
*Val0
, *Val1
;
3368 if (parseCmpPredicate(PredVal
, Opc
) ||
3369 parseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
3370 parseGlobalTypeAndValue(Val0
) ||
3371 parseToken(lltok::comma
, "expected comma in compare constantexpr") ||
3372 parseGlobalTypeAndValue(Val1
) ||
3373 parseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
3376 if (Val0
->getType() != Val1
->getType())
3377 return error(ID
.Loc
, "compare operands must have the same type");
3379 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
3381 if (Opc
== Instruction::FCmp
) {
3382 if (!Val0
->getType()->isFPOrFPVectorTy())
3383 return error(ID
.Loc
, "fcmp requires floating point operands");
3384 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
3386 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
3387 if (!Val0
->getType()->isIntOrIntVectorTy() &&
3388 !Val0
->getType()->isPtrOrPtrVectorTy())
3389 return error(ID
.Loc
, "icmp requires pointer or integer operands");
3390 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
3392 ID
.Kind
= ValID::t_Constant
;
3397 case lltok::kw_fneg
: {
3398 unsigned Opc
= Lex
.getUIntVal();
3401 if (parseToken(lltok::lparen
, "expected '(' in unary constantexpr") ||
3402 parseGlobalTypeAndValue(Val
) ||
3403 parseToken(lltok::rparen
, "expected ')' in unary constantexpr"))
3406 // Check that the type is valid for the operator.
3408 case Instruction::FNeg
:
3409 if (!Val
->getType()->isFPOrFPVectorTy())
3410 return error(ID
.Loc
, "constexpr requires fp operands");
3412 default: llvm_unreachable("Unknown unary operator!");
3415 Constant
*C
= ConstantExpr::get(Opc
, Val
, Flags
);
3417 ID
.Kind
= ValID::t_Constant
;
3420 // Binary Operators.
3422 case lltok::kw_fadd
:
3424 case lltok::kw_fsub
:
3426 case lltok::kw_fmul
:
3427 case lltok::kw_udiv
:
3428 case lltok::kw_sdiv
:
3429 case lltok::kw_fdiv
:
3430 case lltok::kw_urem
:
3431 case lltok::kw_srem
:
3432 case lltok::kw_frem
:
3434 case lltok::kw_lshr
:
3435 case lltok::kw_ashr
: {
3439 unsigned Opc
= Lex
.getUIntVal();
3440 Constant
*Val0
, *Val1
;
3442 if (Opc
== Instruction::Add
|| Opc
== Instruction::Sub
||
3443 Opc
== Instruction::Mul
|| Opc
== Instruction::Shl
) {
3444 if (EatIfPresent(lltok::kw_nuw
))
3446 if (EatIfPresent(lltok::kw_nsw
)) {
3448 if (EatIfPresent(lltok::kw_nuw
))
3451 } else if (Opc
== Instruction::SDiv
|| Opc
== Instruction::UDiv
||
3452 Opc
== Instruction::LShr
|| Opc
== Instruction::AShr
) {
3453 if (EatIfPresent(lltok::kw_exact
))
3456 if (parseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
3457 parseGlobalTypeAndValue(Val0
) ||
3458 parseToken(lltok::comma
, "expected comma in binary constantexpr") ||
3459 parseGlobalTypeAndValue(Val1
) ||
3460 parseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
3462 if (Val0
->getType() != Val1
->getType())
3463 return error(ID
.Loc
, "operands of constexpr must have same type");
3464 // Check that the type is valid for the operator.
3466 case Instruction::Add
:
3467 case Instruction::Sub
:
3468 case Instruction::Mul
:
3469 case Instruction::UDiv
:
3470 case Instruction::SDiv
:
3471 case Instruction::URem
:
3472 case Instruction::SRem
:
3473 case Instruction::Shl
:
3474 case Instruction::AShr
:
3475 case Instruction::LShr
:
3476 if (!Val0
->getType()->isIntOrIntVectorTy())
3477 return error(ID
.Loc
, "constexpr requires integer operands");
3479 case Instruction::FAdd
:
3480 case Instruction::FSub
:
3481 case Instruction::FMul
:
3482 case Instruction::FDiv
:
3483 case Instruction::FRem
:
3484 if (!Val0
->getType()->isFPOrFPVectorTy())
3485 return error(ID
.Loc
, "constexpr requires fp operands");
3487 default: llvm_unreachable("Unknown binary operator!");
3490 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3491 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3492 if (Exact
) Flags
|= PossiblyExactOperator::IsExact
;
3493 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
3495 ID
.Kind
= ValID::t_Constant
;
3499 // Logical Operations
3502 case lltok::kw_xor
: {
3503 unsigned Opc
= Lex
.getUIntVal();
3504 Constant
*Val0
, *Val1
;
3506 if (parseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
3507 parseGlobalTypeAndValue(Val0
) ||
3508 parseToken(lltok::comma
, "expected comma in logical constantexpr") ||
3509 parseGlobalTypeAndValue(Val1
) ||
3510 parseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
3512 if (Val0
->getType() != Val1
->getType())
3513 return error(ID
.Loc
, "operands of constexpr must have same type");
3514 if (!Val0
->getType()->isIntOrIntVectorTy())
3515 return error(ID
.Loc
,
3516 "constexpr requires integer or integer vector operands");
3517 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
3518 ID
.Kind
= ValID::t_Constant
;
3522 case lltok::kw_getelementptr
:
3523 case lltok::kw_shufflevector
:
3524 case lltok::kw_insertelement
:
3525 case lltok::kw_extractelement
:
3526 case lltok::kw_select
: {
3527 unsigned Opc
= Lex
.getUIntVal();
3528 SmallVector
<Constant
*, 16> Elts
;
3529 bool InBounds
= false;
3533 if (Opc
== Instruction::GetElementPtr
)
3534 InBounds
= EatIfPresent(lltok::kw_inbounds
);
3536 if (parseToken(lltok::lparen
, "expected '(' in constantexpr"))
3539 LocTy ExplicitTypeLoc
= Lex
.getLoc();
3540 if (Opc
== Instruction::GetElementPtr
) {
3541 if (parseType(Ty
) ||
3542 parseToken(lltok::comma
, "expected comma after getelementptr's type"))
3546 Optional
<unsigned> InRangeOp
;
3547 if (parseGlobalValueVector(
3548 Elts
, Opc
== Instruction::GetElementPtr
? &InRangeOp
: nullptr) ||
3549 parseToken(lltok::rparen
, "expected ')' in constantexpr"))
3552 if (Opc
== Instruction::GetElementPtr
) {
3553 if (Elts
.size() == 0 ||
3554 !Elts
[0]->getType()->isPtrOrPtrVectorTy())
3555 return error(ID
.Loc
, "base of getelementptr must be a pointer");
3557 Type
*BaseType
= Elts
[0]->getType();
3558 auto *BasePointerType
= cast
<PointerType
>(BaseType
->getScalarType());
3559 if (!BasePointerType
->isOpaqueOrPointeeTypeMatches(Ty
)) {
3562 typeComparisonErrorMessage(
3563 "explicit pointee type doesn't match operand's pointee type",
3564 Ty
, BasePointerType
->getElementType()));
3568 BaseType
->isVectorTy()
3569 ? cast
<FixedVectorType
>(BaseType
)->getNumElements()
3572 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
3573 for (Constant
*Val
: Indices
) {
3574 Type
*ValTy
= Val
->getType();
3575 if (!ValTy
->isIntOrIntVectorTy())
3576 return error(ID
.Loc
, "getelementptr index must be an integer");
3577 if (auto *ValVTy
= dyn_cast
<VectorType
>(ValTy
)) {
3578 unsigned ValNumEl
= cast
<FixedVectorType
>(ValVTy
)->getNumElements();
3579 if (GEPWidth
&& (ValNumEl
!= GEPWidth
))
3582 "getelementptr vector index has a wrong number of elements");
3583 // GEPWidth may have been unknown because the base is a scalar,
3584 // but it is known now.
3585 GEPWidth
= ValNumEl
;
3589 SmallPtrSet
<Type
*, 4> Visited
;
3590 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
3591 return error(ID
.Loc
, "base element of getelementptr must be sized");
3593 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
3594 return error(ID
.Loc
, "invalid getelementptr indices");
3597 if (*InRangeOp
== 0)
3598 return error(ID
.Loc
,
3599 "inrange keyword may not appear on pointer operand");
3603 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Ty
, Elts
[0], Indices
,
3604 InBounds
, InRangeOp
);
3605 } else if (Opc
== Instruction::Select
) {
3606 if (Elts
.size() != 3)
3607 return error(ID
.Loc
, "expected three operands to select");
3608 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
3610 return error(ID
.Loc
, Reason
);
3611 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
3612 } else if (Opc
== Instruction::ShuffleVector
) {
3613 if (Elts
.size() != 3)
3614 return error(ID
.Loc
, "expected three operands to shufflevector");
3615 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3616 return error(ID
.Loc
, "invalid operands to shufflevector");
3617 SmallVector
<int, 16> Mask
;
3618 ShuffleVectorInst::getShuffleMask(cast
<Constant
>(Elts
[2]), Mask
);
3619 ID
.ConstantVal
= ConstantExpr::getShuffleVector(Elts
[0], Elts
[1], Mask
);
3620 } else if (Opc
== Instruction::ExtractElement
) {
3621 if (Elts
.size() != 2)
3622 return error(ID
.Loc
, "expected two operands to extractelement");
3623 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
3624 return error(ID
.Loc
, "invalid extractelement operands");
3625 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
3627 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
3628 if (Elts
.size() != 3)
3629 return error(ID
.Loc
, "expected three operands to insertelement");
3630 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3631 return error(ID
.Loc
, "invalid insertelement operands");
3633 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
3636 ID
.Kind
= ValID::t_Constant
;
3645 /// parseGlobalValue - parse a global value with the specified type.
3646 bool LLParser::parseGlobalValue(Type
*Ty
, Constant
*&C
) {
3650 bool Parsed
= parseValID(ID
, /*PFS=*/nullptr, Ty
) ||
3651 convertValIDToValue(Ty
, ID
, V
, nullptr, /*IsCall=*/false);
3652 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
3653 return error(ID
.Loc
, "global values must be constants");
3657 bool LLParser::parseGlobalTypeAndValue(Constant
*&V
) {
3659 return parseType(Ty
) || parseGlobalValue(Ty
, V
);
3662 bool LLParser::parseOptionalComdat(StringRef GlobalName
, Comdat
*&C
) {
3665 LocTy KwLoc
= Lex
.getLoc();
3666 if (!EatIfPresent(lltok::kw_comdat
))
3669 if (EatIfPresent(lltok::lparen
)) {
3670 if (Lex
.getKind() != lltok::ComdatVar
)
3671 return tokError("expected comdat variable");
3672 C
= getComdat(Lex
.getStrVal(), Lex
.getLoc());
3674 if (parseToken(lltok::rparen
, "expected ')' after comdat var"))
3677 if (GlobalName
.empty())
3678 return tokError("comdat cannot be unnamed");
3679 C
= getComdat(std::string(GlobalName
), KwLoc
);
3685 /// parseGlobalValueVector
3687 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3688 bool LLParser::parseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
,
3689 Optional
<unsigned> *InRangeOp
) {
3691 if (Lex
.getKind() == lltok::rbrace
||
3692 Lex
.getKind() == lltok::rsquare
||
3693 Lex
.getKind() == lltok::greater
||
3694 Lex
.getKind() == lltok::rparen
)
3698 if (InRangeOp
&& !*InRangeOp
&& EatIfPresent(lltok::kw_inrange
))
3699 *InRangeOp
= Elts
.size();
3702 if (parseGlobalTypeAndValue(C
))
3705 } while (EatIfPresent(lltok::comma
));
3710 bool LLParser::parseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
3711 SmallVector
<Metadata
*, 16> Elts
;
3712 if (parseMDNodeVector(Elts
))
3715 MD
= (IsDistinct
? MDTuple::getDistinct
: MDTuple::get
)(Context
, Elts
);
3722 /// ::= !DILocation(...)
3723 bool LLParser::parseMDNode(MDNode
*&N
) {
3724 if (Lex
.getKind() == lltok::MetadataVar
)
3725 return parseSpecializedMDNode(N
);
3727 return parseToken(lltok::exclaim
, "expected '!' here") || parseMDNodeTail(N
);
3730 bool LLParser::parseMDNodeTail(MDNode
*&N
) {
3732 if (Lex
.getKind() == lltok::lbrace
)
3733 return parseMDTuple(N
);
3736 return parseMDNodeID(N
);
3741 /// Structure to represent an optional metadata field.
3742 template <class FieldTy
> struct MDFieldImpl
{
3743 typedef MDFieldImpl ImplTy
;
3747 void assign(FieldTy Val
) {
3749 this->Val
= std::move(Val
);
3752 explicit MDFieldImpl(FieldTy Default
)
3753 : Val(std::move(Default
)), Seen(false) {}
3756 /// Structure to represent an optional metadata field that
3757 /// can be of either type (A or B) and encapsulates the
3758 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3759 /// to reimplement the specifics for representing each Field.
3760 template <class FieldTypeA
, class FieldTypeB
> struct MDEitherFieldImpl
{
3761 typedef MDEitherFieldImpl
<FieldTypeA
, FieldTypeB
> ImplTy
;
3772 void assign(FieldTypeA A
) {
3774 this->A
= std::move(A
);
3778 void assign(FieldTypeB B
) {
3780 this->B
= std::move(B
);
3784 explicit MDEitherFieldImpl(FieldTypeA DefaultA
, FieldTypeB DefaultB
)
3785 : A(std::move(DefaultA
)), B(std::move(DefaultB
)), Seen(false),
3786 WhatIs(IsInvalid
) {}
3789 struct MDUnsignedField
: public MDFieldImpl
<uint64_t> {
3792 MDUnsignedField(uint64_t Default
= 0, uint64_t Max
= UINT64_MAX
)
3793 : ImplTy(Default
), Max(Max
) {}
3796 struct LineField
: public MDUnsignedField
{
3797 LineField() : MDUnsignedField(0, UINT32_MAX
) {}
3800 struct ColumnField
: public MDUnsignedField
{
3801 ColumnField() : MDUnsignedField(0, UINT16_MAX
) {}
3804 struct DwarfTagField
: public MDUnsignedField
{
3805 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user
) {}
3806 DwarfTagField(dwarf::Tag DefaultTag
)
3807 : MDUnsignedField(DefaultTag
, dwarf::DW_TAG_hi_user
) {}
3810 struct DwarfMacinfoTypeField
: public MDUnsignedField
{
3811 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext
) {}
3812 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType
)
3813 : MDUnsignedField(DefaultType
, dwarf::DW_MACINFO_vendor_ext
) {}
3816 struct DwarfAttEncodingField
: public MDUnsignedField
{
3817 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user
) {}
3820 struct DwarfVirtualityField
: public MDUnsignedField
{
3821 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max
) {}
3824 struct DwarfLangField
: public MDUnsignedField
{
3825 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user
) {}
3828 struct DwarfCCField
: public MDUnsignedField
{
3829 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user
) {}
3832 struct EmissionKindField
: public MDUnsignedField
{
3833 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind
) {}
3836 struct NameTableKindField
: public MDUnsignedField
{
3837 NameTableKindField()
3840 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind
) {}
3843 struct DIFlagField
: public MDFieldImpl
<DINode::DIFlags
> {
3844 DIFlagField() : MDFieldImpl(DINode::FlagZero
) {}
3847 struct DISPFlagField
: public MDFieldImpl
<DISubprogram::DISPFlags
> {
3848 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero
) {}
3851 struct MDAPSIntField
: public MDFieldImpl
<APSInt
> {
3852 MDAPSIntField() : ImplTy(APSInt()) {}
3855 struct MDSignedField
: public MDFieldImpl
<int64_t> {
3859 MDSignedField(int64_t Default
= 0)
3860 : ImplTy(Default
), Min(INT64_MIN
), Max(INT64_MAX
) {}
3861 MDSignedField(int64_t Default
, int64_t Min
, int64_t Max
)
3862 : ImplTy(Default
), Min(Min
), Max(Max
) {}
3865 struct MDBoolField
: public MDFieldImpl
<bool> {
3866 MDBoolField(bool Default
= false) : ImplTy(Default
) {}
3869 struct MDField
: public MDFieldImpl
<Metadata
*> {
3872 MDField(bool AllowNull
= true) : ImplTy(nullptr), AllowNull(AllowNull
) {}
3875 struct MDStringField
: public MDFieldImpl
<MDString
*> {
3877 MDStringField(bool AllowEmpty
= true)
3878 : ImplTy(nullptr), AllowEmpty(AllowEmpty
) {}
3881 struct MDFieldList
: public MDFieldImpl
<SmallVector
<Metadata
*, 4>> {
3882 MDFieldList() : ImplTy(SmallVector
<Metadata
*, 4>()) {}
3885 struct ChecksumKindField
: public MDFieldImpl
<DIFile::ChecksumKind
> {
3886 ChecksumKindField(DIFile::ChecksumKind CSKind
) : ImplTy(CSKind
) {}
3889 struct MDSignedOrMDField
: MDEitherFieldImpl
<MDSignedField
, MDField
> {
3890 MDSignedOrMDField(int64_t Default
= 0, bool AllowNull
= true)
3891 : ImplTy(MDSignedField(Default
), MDField(AllowNull
)) {}
3893 MDSignedOrMDField(int64_t Default
, int64_t Min
, int64_t Max
,
3894 bool AllowNull
= true)
3895 : ImplTy(MDSignedField(Default
, Min
, Max
), MDField(AllowNull
)) {}
3897 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3898 bool isMDField() const { return WhatIs
== IsTypeB
; }
3899 int64_t getMDSignedValue() const {
3900 assert(isMDSignedField() && "Wrong field type");
3903 Metadata
*getMDFieldValue() const {
3904 assert(isMDField() && "Wrong field type");
3909 } // end anonymous namespace
3914 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDAPSIntField
&Result
) {
3915 if (Lex
.getKind() != lltok::APSInt
)
3916 return tokError("expected integer");
3918 Result
.assign(Lex
.getAPSIntVal());
3924 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
3925 MDUnsignedField
&Result
) {
3926 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
3927 return tokError("expected unsigned integer");
3929 auto &U
= Lex
.getAPSIntVal();
3930 if (U
.ugt(Result
.Max
))
3931 return tokError("value for '" + Name
+ "' too large, limit is " +
3933 Result
.assign(U
.getZExtValue());
3934 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
3940 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, LineField
&Result
) {
3941 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3944 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, ColumnField
&Result
) {
3945 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3949 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfTagField
&Result
) {
3950 if (Lex
.getKind() == lltok::APSInt
)
3951 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3953 if (Lex
.getKind() != lltok::DwarfTag
)
3954 return tokError("expected DWARF tag");
3956 unsigned Tag
= dwarf::getTag(Lex
.getStrVal());
3957 if (Tag
== dwarf::DW_TAG_invalid
)
3958 return tokError("invalid DWARF tag" + Twine(" '") + Lex
.getStrVal() + "'");
3959 assert(Tag
<= Result
.Max
&& "Expected valid DWARF tag");
3967 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
3968 DwarfMacinfoTypeField
&Result
) {
3969 if (Lex
.getKind() == lltok::APSInt
)
3970 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3972 if (Lex
.getKind() != lltok::DwarfMacinfo
)
3973 return tokError("expected DWARF macinfo type");
3975 unsigned Macinfo
= dwarf::getMacinfo(Lex
.getStrVal());
3976 if (Macinfo
== dwarf::DW_MACINFO_invalid
)
3977 return tokError("invalid DWARF macinfo type" + Twine(" '") +
3978 Lex
.getStrVal() + "'");
3979 assert(Macinfo
<= Result
.Max
&& "Expected valid DWARF macinfo type");
3981 Result
.assign(Macinfo
);
3987 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
3988 DwarfVirtualityField
&Result
) {
3989 if (Lex
.getKind() == lltok::APSInt
)
3990 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3992 if (Lex
.getKind() != lltok::DwarfVirtuality
)
3993 return tokError("expected DWARF virtuality code");
3995 unsigned Virtuality
= dwarf::getVirtuality(Lex
.getStrVal());
3996 if (Virtuality
== dwarf::DW_VIRTUALITY_invalid
)
3997 return tokError("invalid DWARF virtuality code" + Twine(" '") +
3998 Lex
.getStrVal() + "'");
3999 assert(Virtuality
<= Result
.Max
&& "Expected valid DWARF virtuality code");
4000 Result
.assign(Virtuality
);
4006 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfLangField
&Result
) {
4007 if (Lex
.getKind() == lltok::APSInt
)
4008 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4010 if (Lex
.getKind() != lltok::DwarfLang
)
4011 return tokError("expected DWARF language");
4013 unsigned Lang
= dwarf::getLanguage(Lex
.getStrVal());
4015 return tokError("invalid DWARF language" + Twine(" '") + Lex
.getStrVal() +
4017 assert(Lang
<= Result
.Max
&& "Expected valid DWARF language");
4018 Result
.assign(Lang
);
4024 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfCCField
&Result
) {
4025 if (Lex
.getKind() == lltok::APSInt
)
4026 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4028 if (Lex
.getKind() != lltok::DwarfCC
)
4029 return tokError("expected DWARF calling convention");
4031 unsigned CC
= dwarf::getCallingConvention(Lex
.getStrVal());
4033 return tokError("invalid DWARF calling convention" + Twine(" '") +
4034 Lex
.getStrVal() + "'");
4035 assert(CC
<= Result
.Max
&& "Expected valid DWARF calling convention");
4042 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4043 EmissionKindField
&Result
) {
4044 if (Lex
.getKind() == lltok::APSInt
)
4045 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4047 if (Lex
.getKind() != lltok::EmissionKind
)
4048 return tokError("expected emission kind");
4050 auto Kind
= DICompileUnit::getEmissionKind(Lex
.getStrVal());
4052 return tokError("invalid emission kind" + Twine(" '") + Lex
.getStrVal() +
4054 assert(*Kind
<= Result
.Max
&& "Expected valid emission kind");
4055 Result
.assign(*Kind
);
4061 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4062 NameTableKindField
&Result
) {
4063 if (Lex
.getKind() == lltok::APSInt
)
4064 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4066 if (Lex
.getKind() != lltok::NameTableKind
)
4067 return tokError("expected nameTable kind");
4069 auto Kind
= DICompileUnit::getNameTableKind(Lex
.getStrVal());
4071 return tokError("invalid nameTable kind" + Twine(" '") + Lex
.getStrVal() +
4073 assert(((unsigned)*Kind
) <= Result
.Max
&& "Expected valid nameTable kind");
4074 Result
.assign((unsigned)*Kind
);
4080 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4081 DwarfAttEncodingField
&Result
) {
4082 if (Lex
.getKind() == lltok::APSInt
)
4083 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4085 if (Lex
.getKind() != lltok::DwarfAttEncoding
)
4086 return tokError("expected DWARF type attribute encoding");
4088 unsigned Encoding
= dwarf::getAttributeEncoding(Lex
.getStrVal());
4090 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4091 Lex
.getStrVal() + "'");
4092 assert(Encoding
<= Result
.Max
&& "Expected valid DWARF language");
4093 Result
.assign(Encoding
);
4100 /// ::= DIFlagVector
4101 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4103 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DIFlagField
&Result
) {
4105 // parser for a single flag.
4106 auto parseFlag
= [&](DINode::DIFlags
&Val
) {
4107 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4108 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4109 bool Res
= parseUInt32(TempVal
);
4110 Val
= static_cast<DINode::DIFlags
>(TempVal
);
4114 if (Lex
.getKind() != lltok::DIFlag
)
4115 return tokError("expected debug info flag");
4117 Val
= DINode::getFlag(Lex
.getStrVal());
4119 return tokError(Twine("invalid debug info flag flag '") +
4120 Lex
.getStrVal() + "'");
4125 // parse the flags and combine them together.
4126 DINode::DIFlags Combined
= DINode::FlagZero
;
4128 DINode::DIFlags Val
;
4132 } while (EatIfPresent(lltok::bar
));
4134 Result
.assign(Combined
);
4140 /// ::= DISPFlagVector
4141 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4143 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DISPFlagField
&Result
) {
4145 // parser for a single flag.
4146 auto parseFlag
= [&](DISubprogram::DISPFlags
&Val
) {
4147 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4148 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4149 bool Res
= parseUInt32(TempVal
);
4150 Val
= static_cast<DISubprogram::DISPFlags
>(TempVal
);
4154 if (Lex
.getKind() != lltok::DISPFlag
)
4155 return tokError("expected debug info flag");
4157 Val
= DISubprogram::getFlag(Lex
.getStrVal());
4159 return tokError(Twine("invalid subprogram debug info flag '") +
4160 Lex
.getStrVal() + "'");
4165 // parse the flags and combine them together.
4166 DISubprogram::DISPFlags Combined
= DISubprogram::SPFlagZero
;
4168 DISubprogram::DISPFlags Val
;
4172 } while (EatIfPresent(lltok::bar
));
4174 Result
.assign(Combined
);
4179 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDSignedField
&Result
) {
4180 if (Lex
.getKind() != lltok::APSInt
)
4181 return tokError("expected signed integer");
4183 auto &S
= Lex
.getAPSIntVal();
4185 return tokError("value for '" + Name
+ "' too small, limit is " +
4188 return tokError("value for '" + Name
+ "' too large, limit is " +
4190 Result
.assign(S
.getExtValue());
4191 assert(Result
.Val
>= Result
.Min
&& "Expected value in range");
4192 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4198 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDBoolField
&Result
) {
4199 switch (Lex
.getKind()) {
4201 return tokError("expected 'true' or 'false'");
4202 case lltok::kw_true
:
4203 Result
.assign(true);
4205 case lltok::kw_false
:
4206 Result
.assign(false);
4214 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDField
&Result
) {
4215 if (Lex
.getKind() == lltok::kw_null
) {
4216 if (!Result
.AllowNull
)
4217 return tokError("'" + Name
+ "' cannot be null");
4219 Result
.assign(nullptr);
4224 if (parseMetadata(MD
, nullptr))
4232 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4233 MDSignedOrMDField
&Result
) {
4234 // Try to parse a signed int.
4235 if (Lex
.getKind() == lltok::APSInt
) {
4236 MDSignedField Res
= Result
.A
;
4237 if (!parseMDField(Loc
, Name
, Res
)) {
4244 // Otherwise, try to parse as an MDField.
4245 MDField Res
= Result
.B
;
4246 if (!parseMDField(Loc
, Name
, Res
)) {
4255 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDStringField
&Result
) {
4256 LocTy ValueLoc
= Lex
.getLoc();
4258 if (parseStringConstant(S
))
4261 if (!Result
.AllowEmpty
&& S
.empty())
4262 return error(ValueLoc
, "'" + Name
+ "' cannot be empty");
4264 Result
.assign(S
.empty() ? nullptr : MDString::get(Context
, S
));
4269 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDFieldList
&Result
) {
4270 SmallVector
<Metadata
*, 4> MDs
;
4271 if (parseMDNodeVector(MDs
))
4274 Result
.assign(std::move(MDs
));
4279 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4280 ChecksumKindField
&Result
) {
4281 Optional
<DIFile::ChecksumKind
> CSKind
=
4282 DIFile::getChecksumKind(Lex
.getStrVal());
4284 if (Lex
.getKind() != lltok::ChecksumKind
|| !CSKind
)
4285 return tokError("invalid checksum kind" + Twine(" '") + Lex
.getStrVal() +
4288 Result
.assign(*CSKind
);
4293 } // end namespace llvm
4295 template <class ParserTy
>
4296 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField
) {
4298 if (Lex
.getKind() != lltok::LabelStr
)
4299 return tokError("expected field label here");
4303 } while (EatIfPresent(lltok::comma
));
4308 template <class ParserTy
>
4309 bool LLParser::parseMDFieldsImpl(ParserTy ParseField
, LocTy
&ClosingLoc
) {
4310 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4313 if (parseToken(lltok::lparen
, "expected '(' here"))
4315 if (Lex
.getKind() != lltok::rparen
)
4316 if (parseMDFieldsImplBody(ParseField
))
4319 ClosingLoc
= Lex
.getLoc();
4320 return parseToken(lltok::rparen
, "expected ')' here");
4323 template <class FieldTy
>
4324 bool LLParser::parseMDField(StringRef Name
, FieldTy
&Result
) {
4326 return tokError("field '" + Name
+ "' cannot be specified more than once");
4328 LocTy Loc
= Lex
.getLoc();
4330 return parseMDField(Loc
, Name
, Result
);
4333 bool LLParser::parseSpecializedMDNode(MDNode
*&N
, bool IsDistinct
) {
4334 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4336 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4337 if (Lex.getStrVal() == #CLASS) \
4338 return parse##CLASS(N, IsDistinct);
4339 #include "llvm/IR/Metadata.def"
4341 return tokError("expected metadata type");
4344 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4345 #define NOP_FIELD(NAME, TYPE, INIT)
4346 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4348 return error(ClosingLoc, "missing required field '" #NAME "'");
4349 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4350 if (Lex.getStrVal() == #NAME) \
4351 return parseMDField(#NAME, NAME);
4352 #define PARSE_MD_FIELDS() \
4353 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4356 if (parseMDFieldsImpl( \
4358 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4359 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4364 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4366 #define GET_OR_DISTINCT(CLASS, ARGS) \
4367 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4369 /// parseDILocationFields:
4370 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4371 /// isImplicitCode: true)
4372 bool LLParser::parseDILocation(MDNode
*&Result
, bool IsDistinct
) {
4373 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4374 OPTIONAL(line, LineField, ); \
4375 OPTIONAL(column, ColumnField, ); \
4376 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4377 OPTIONAL(inlinedAt, MDField, ); \
4378 OPTIONAL(isImplicitCode, MDBoolField, (false));
4380 #undef VISIT_MD_FIELDS
4383 GET_OR_DISTINCT(DILocation
, (Context
, line
.Val
, column
.Val
, scope
.Val
,
4384 inlinedAt
.Val
, isImplicitCode
.Val
));
4388 /// parseGenericDINode:
4389 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4390 bool LLParser::parseGenericDINode(MDNode
*&Result
, bool IsDistinct
) {
4391 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4392 REQUIRED(tag, DwarfTagField, ); \
4393 OPTIONAL(header, MDStringField, ); \
4394 OPTIONAL(operands, MDFieldList, );
4396 #undef VISIT_MD_FIELDS
4398 Result
= GET_OR_DISTINCT(GenericDINode
,
4399 (Context
, tag
.Val
, header
.Val
, operands
.Val
));
4403 /// parseDISubrange:
4404 /// ::= !DISubrange(count: 30, lowerBound: 2)
4405 /// ::= !DISubrange(count: !node, lowerBound: 2)
4406 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4407 bool LLParser::parseDISubrange(MDNode
*&Result
, bool IsDistinct
) {
4408 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4409 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4410 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4411 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4412 OPTIONAL(stride, MDSignedOrMDField, );
4414 #undef VISIT_MD_FIELDS
4416 Metadata
*Count
= nullptr;
4417 Metadata
*LowerBound
= nullptr;
4418 Metadata
*UpperBound
= nullptr;
4419 Metadata
*Stride
= nullptr;
4421 auto convToMetadata
= [&](MDSignedOrMDField Bound
) -> Metadata
* {
4422 if (Bound
.isMDSignedField())
4423 return ConstantAsMetadata::get(ConstantInt::getSigned(
4424 Type::getInt64Ty(Context
), Bound
.getMDSignedValue()));
4425 if (Bound
.isMDField())
4426 return Bound
.getMDFieldValue();
4430 Count
= convToMetadata(count
);
4431 LowerBound
= convToMetadata(lowerBound
);
4432 UpperBound
= convToMetadata(upperBound
);
4433 Stride
= convToMetadata(stride
);
4435 Result
= GET_OR_DISTINCT(DISubrange
,
4436 (Context
, Count
, LowerBound
, UpperBound
, Stride
));
4441 /// parseDIGenericSubrange:
4442 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4444 bool LLParser::parseDIGenericSubrange(MDNode
*&Result
, bool IsDistinct
) {
4445 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4446 OPTIONAL(count, MDSignedOrMDField, ); \
4447 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4448 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4449 OPTIONAL(stride, MDSignedOrMDField, );
4451 #undef VISIT_MD_FIELDS
4453 auto ConvToMetadata
= [&](MDSignedOrMDField Bound
) -> Metadata
* {
4454 if (Bound
.isMDSignedField())
4455 return DIExpression::get(
4456 Context
, {dwarf::DW_OP_consts
,
4457 static_cast<uint64_t>(Bound
.getMDSignedValue())});
4458 if (Bound
.isMDField())
4459 return Bound
.getMDFieldValue();
4463 Metadata
*Count
= ConvToMetadata(count
);
4464 Metadata
*LowerBound
= ConvToMetadata(lowerBound
);
4465 Metadata
*UpperBound
= ConvToMetadata(upperBound
);
4466 Metadata
*Stride
= ConvToMetadata(stride
);
4468 Result
= GET_OR_DISTINCT(DIGenericSubrange
,
4469 (Context
, Count
, LowerBound
, UpperBound
, Stride
));
4474 /// parseDIEnumerator:
4475 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4476 bool LLParser::parseDIEnumerator(MDNode
*&Result
, bool IsDistinct
) {
4477 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4478 REQUIRED(name, MDStringField, ); \
4479 REQUIRED(value, MDAPSIntField, ); \
4480 OPTIONAL(isUnsigned, MDBoolField, (false));
4482 #undef VISIT_MD_FIELDS
4484 if (isUnsigned
.Val
&& value
.Val
.isNegative())
4485 return tokError("unsigned enumerator with negative value");
4487 APSInt
Value(value
.Val
);
4488 // Add a leading zero so that unsigned values with the msb set are not
4489 // mistaken for negative values when used for signed enumerators.
4490 if (!isUnsigned
.Val
&& value
.Val
.isUnsigned() && value
.Val
.isSignBitSet())
4491 Value
= Value
.zext(Value
.getBitWidth() + 1);
4494 GET_OR_DISTINCT(DIEnumerator
, (Context
, Value
, isUnsigned
.Val
, name
.Val
));
4499 /// parseDIBasicType:
4500 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4501 /// encoding: DW_ATE_encoding, flags: 0)
4502 bool LLParser::parseDIBasicType(MDNode
*&Result
, bool IsDistinct
) {
4503 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4504 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4505 OPTIONAL(name, MDStringField, ); \
4506 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4507 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4508 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4509 OPTIONAL(flags, DIFlagField, );
4511 #undef VISIT_MD_FIELDS
4513 Result
= GET_OR_DISTINCT(DIBasicType
, (Context
, tag
.Val
, name
.Val
, size
.Val
,
4514 align
.Val
, encoding
.Val
, flags
.Val
));
4518 /// parseDIStringType:
4519 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4520 bool LLParser::parseDIStringType(MDNode
*&Result
, bool IsDistinct
) {
4521 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4522 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4523 OPTIONAL(name, MDStringField, ); \
4524 OPTIONAL(stringLength, MDField, ); \
4525 OPTIONAL(stringLengthExpression, MDField, ); \
4526 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4527 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4528 OPTIONAL(encoding, DwarfAttEncodingField, );
4530 #undef VISIT_MD_FIELDS
4532 Result
= GET_OR_DISTINCT(DIStringType
,
4533 (Context
, tag
.Val
, name
.Val
, stringLength
.Val
,
4534 stringLengthExpression
.Val
, size
.Val
, align
.Val
,
4539 /// parseDIDerivedType:
4540 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4541 /// line: 7, scope: !1, baseType: !2, size: 32,
4542 /// align: 32, offset: 0, flags: 0, extraData: !3,
4543 /// dwarfAddressSpace: 3)
4544 bool LLParser::parseDIDerivedType(MDNode
*&Result
, bool IsDistinct
) {
4545 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4546 REQUIRED(tag, DwarfTagField, ); \
4547 OPTIONAL(name, MDStringField, ); \
4548 OPTIONAL(file, MDField, ); \
4549 OPTIONAL(line, LineField, ); \
4550 OPTIONAL(scope, MDField, ); \
4551 REQUIRED(baseType, MDField, ); \
4552 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4553 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4554 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4555 OPTIONAL(flags, DIFlagField, ); \
4556 OPTIONAL(extraData, MDField, ); \
4557 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
4558 OPTIONAL(annotations, MDField, );
4560 #undef VISIT_MD_FIELDS
4562 Optional
<unsigned> DWARFAddressSpace
;
4563 if (dwarfAddressSpace
.Val
!= UINT32_MAX
)
4564 DWARFAddressSpace
= dwarfAddressSpace
.Val
;
4566 Result
= GET_OR_DISTINCT(DIDerivedType
,
4567 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4568 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
,
4569 offset
.Val
, DWARFAddressSpace
, flags
.Val
,
4570 extraData
.Val
, annotations
.Val
));
4574 bool LLParser::parseDICompositeType(MDNode
*&Result
, bool IsDistinct
) {
4575 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4576 REQUIRED(tag, DwarfTagField, ); \
4577 OPTIONAL(name, MDStringField, ); \
4578 OPTIONAL(file, MDField, ); \
4579 OPTIONAL(line, LineField, ); \
4580 OPTIONAL(scope, MDField, ); \
4581 OPTIONAL(baseType, MDField, ); \
4582 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4583 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4584 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4585 OPTIONAL(flags, DIFlagField, ); \
4586 OPTIONAL(elements, MDField, ); \
4587 OPTIONAL(runtimeLang, DwarfLangField, ); \
4588 OPTIONAL(vtableHolder, MDField, ); \
4589 OPTIONAL(templateParams, MDField, ); \
4590 OPTIONAL(identifier, MDStringField, ); \
4591 OPTIONAL(discriminator, MDField, ); \
4592 OPTIONAL(dataLocation, MDField, ); \
4593 OPTIONAL(associated, MDField, ); \
4594 OPTIONAL(allocated, MDField, ); \
4595 OPTIONAL(rank, MDSignedOrMDField, ); \
4596 OPTIONAL(annotations, MDField, );
4598 #undef VISIT_MD_FIELDS
4600 Metadata
*Rank
= nullptr;
4601 if (rank
.isMDSignedField())
4602 Rank
= ConstantAsMetadata::get(ConstantInt::getSigned(
4603 Type::getInt64Ty(Context
), rank
.getMDSignedValue()));
4604 else if (rank
.isMDField())
4605 Rank
= rank
.getMDFieldValue();
4607 // If this has an identifier try to build an ODR type.
4609 if (auto *CT
= DICompositeType::buildODRType(
4610 Context
, *identifier
.Val
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4611 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
, offset
.Val
, flags
.Val
,
4612 elements
.Val
, runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
,
4613 discriminator
.Val
, dataLocation
.Val
, associated
.Val
, allocated
.Val
,
4614 Rank
, annotations
.Val
)) {
4619 // Create a new node, and save it in the context if it belongs in the type
4621 Result
= GET_OR_DISTINCT(
4623 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
, scope
.Val
, baseType
.Val
,
4624 size
.Val
, align
.Val
, offset
.Val
, flags
.Val
, elements
.Val
,
4625 runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
, identifier
.Val
,
4626 discriminator
.Val
, dataLocation
.Val
, associated
.Val
, allocated
.Val
, Rank
,
4631 bool LLParser::parseDISubroutineType(MDNode
*&Result
, bool IsDistinct
) {
4632 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4633 OPTIONAL(flags, DIFlagField, ); \
4634 OPTIONAL(cc, DwarfCCField, ); \
4635 REQUIRED(types, MDField, );
4637 #undef VISIT_MD_FIELDS
4639 Result
= GET_OR_DISTINCT(DISubroutineType
,
4640 (Context
, flags
.Val
, cc
.Val
, types
.Val
));
4644 /// parseDIFileType:
4645 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4646 /// checksumkind: CSK_MD5,
4647 /// checksum: "000102030405060708090a0b0c0d0e0f",
4648 /// source: "source file contents")
4649 bool LLParser::parseDIFile(MDNode
*&Result
, bool IsDistinct
) {
4650 // The default constructed value for checksumkind is required, but will never
4651 // be used, as the parser checks if the field was actually Seen before using
4653 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4654 REQUIRED(filename, MDStringField, ); \
4655 REQUIRED(directory, MDStringField, ); \
4656 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4657 OPTIONAL(checksum, MDStringField, ); \
4658 OPTIONAL(source, MDStringField, );
4660 #undef VISIT_MD_FIELDS
4662 Optional
<DIFile::ChecksumInfo
<MDString
*>> OptChecksum
;
4663 if (checksumkind
.Seen
&& checksum
.Seen
)
4664 OptChecksum
.emplace(checksumkind
.Val
, checksum
.Val
);
4665 else if (checksumkind
.Seen
|| checksum
.Seen
)
4666 return Lex
.Error("'checksumkind' and 'checksum' must be provided together");
4668 Optional
<MDString
*> OptSource
;
4670 OptSource
= source
.Val
;
4671 Result
= GET_OR_DISTINCT(DIFile
, (Context
, filename
.Val
, directory
.Val
,
4672 OptChecksum
, OptSource
));
4676 /// parseDICompileUnit:
4677 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4678 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4679 /// splitDebugFilename: "abc.debug",
4680 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4681 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4682 /// sysroot: "/", sdk: "MacOSX.sdk")
4683 bool LLParser::parseDICompileUnit(MDNode
*&Result
, bool IsDistinct
) {
4685 return Lex
.Error("missing 'distinct', required for !DICompileUnit");
4687 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4688 REQUIRED(language, DwarfLangField, ); \
4689 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4690 OPTIONAL(producer, MDStringField, ); \
4691 OPTIONAL(isOptimized, MDBoolField, ); \
4692 OPTIONAL(flags, MDStringField, ); \
4693 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4694 OPTIONAL(splitDebugFilename, MDStringField, ); \
4695 OPTIONAL(emissionKind, EmissionKindField, ); \
4696 OPTIONAL(enums, MDField, ); \
4697 OPTIONAL(retainedTypes, MDField, ); \
4698 OPTIONAL(globals, MDField, ); \
4699 OPTIONAL(imports, MDField, ); \
4700 OPTIONAL(macros, MDField, ); \
4701 OPTIONAL(dwoId, MDUnsignedField, ); \
4702 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4703 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4704 OPTIONAL(nameTableKind, NameTableKindField, ); \
4705 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
4706 OPTIONAL(sysroot, MDStringField, ); \
4707 OPTIONAL(sdk, MDStringField, );
4709 #undef VISIT_MD_FIELDS
4711 Result
= DICompileUnit::getDistinct(
4712 Context
, language
.Val
, file
.Val
, producer
.Val
, isOptimized
.Val
, flags
.Val
,
4713 runtimeVersion
.Val
, splitDebugFilename
.Val
, emissionKind
.Val
, enums
.Val
,
4714 retainedTypes
.Val
, globals
.Val
, imports
.Val
, macros
.Val
, dwoId
.Val
,
4715 splitDebugInlining
.Val
, debugInfoForProfiling
.Val
, nameTableKind
.Val
,
4716 rangesBaseAddress
.Val
, sysroot
.Val
, sdk
.Val
);
4720 /// parseDISubprogram:
4721 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4722 /// file: !1, line: 7, type: !2, isLocal: false,
4723 /// isDefinition: true, scopeLine: 8, containingType: !3,
4724 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4725 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4726 /// spFlags: 10, isOptimized: false, templateParams: !4,
4727 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4728 bool LLParser::parseDISubprogram(MDNode
*&Result
, bool IsDistinct
) {
4729 auto Loc
= Lex
.getLoc();
4730 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4731 OPTIONAL(scope, MDField, ); \
4732 OPTIONAL(name, MDStringField, ); \
4733 OPTIONAL(linkageName, MDStringField, ); \
4734 OPTIONAL(file, MDField, ); \
4735 OPTIONAL(line, LineField, ); \
4736 OPTIONAL(type, MDField, ); \
4737 OPTIONAL(isLocal, MDBoolField, ); \
4738 OPTIONAL(isDefinition, MDBoolField, (true)); \
4739 OPTIONAL(scopeLine, LineField, ); \
4740 OPTIONAL(containingType, MDField, ); \
4741 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4742 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4743 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4744 OPTIONAL(flags, DIFlagField, ); \
4745 OPTIONAL(spFlags, DISPFlagField, ); \
4746 OPTIONAL(isOptimized, MDBoolField, ); \
4747 OPTIONAL(unit, MDField, ); \
4748 OPTIONAL(templateParams, MDField, ); \
4749 OPTIONAL(declaration, MDField, ); \
4750 OPTIONAL(retainedNodes, MDField, ); \
4751 OPTIONAL(thrownTypes, MDField, );
4753 #undef VISIT_MD_FIELDS
4755 // An explicit spFlags field takes precedence over individual fields in
4756 // older IR versions.
4757 DISubprogram::DISPFlags SPFlags
=
4758 spFlags
.Seen
? spFlags
.Val
4759 : DISubprogram::toSPFlags(isLocal
.Val
, isDefinition
.Val
,
4760 isOptimized
.Val
, virtuality
.Val
);
4761 if ((SPFlags
& DISubprogram::SPFlagDefinition
) && !IsDistinct
)
4764 "missing 'distinct', required for !DISubprogram that is a Definition");
4765 Result
= GET_OR_DISTINCT(
4767 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
, line
.Val
,
4768 type
.Val
, scopeLine
.Val
, containingType
.Val
, virtualIndex
.Val
,
4769 thisAdjustment
.Val
, flags
.Val
, SPFlags
, unit
.Val
, templateParams
.Val
,
4770 declaration
.Val
, retainedNodes
.Val
, thrownTypes
.Val
));
4774 /// parseDILexicalBlock:
4775 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4776 bool LLParser::parseDILexicalBlock(MDNode
*&Result
, bool IsDistinct
) {
4777 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4778 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4779 OPTIONAL(file, MDField, ); \
4780 OPTIONAL(line, LineField, ); \
4781 OPTIONAL(column, ColumnField, );
4783 #undef VISIT_MD_FIELDS
4785 Result
= GET_OR_DISTINCT(
4786 DILexicalBlock
, (Context
, scope
.Val
, file
.Val
, line
.Val
, column
.Val
));
4790 /// parseDILexicalBlockFile:
4791 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4792 bool LLParser::parseDILexicalBlockFile(MDNode
*&Result
, bool IsDistinct
) {
4793 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4794 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4795 OPTIONAL(file, MDField, ); \
4796 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4798 #undef VISIT_MD_FIELDS
4800 Result
= GET_OR_DISTINCT(DILexicalBlockFile
,
4801 (Context
, scope
.Val
, file
.Val
, discriminator
.Val
));
4805 /// parseDICommonBlock:
4806 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4807 bool LLParser::parseDICommonBlock(MDNode
*&Result
, bool IsDistinct
) {
4808 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4809 REQUIRED(scope, MDField, ); \
4810 OPTIONAL(declaration, MDField, ); \
4811 OPTIONAL(name, MDStringField, ); \
4812 OPTIONAL(file, MDField, ); \
4813 OPTIONAL(line, LineField, );
4815 #undef VISIT_MD_FIELDS
4817 Result
= GET_OR_DISTINCT(DICommonBlock
,
4818 (Context
, scope
.Val
, declaration
.Val
, name
.Val
,
4819 file
.Val
, line
.Val
));
4823 /// parseDINamespace:
4824 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4825 bool LLParser::parseDINamespace(MDNode
*&Result
, bool IsDistinct
) {
4826 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4827 REQUIRED(scope, MDField, ); \
4828 OPTIONAL(name, MDStringField, ); \
4829 OPTIONAL(exportSymbols, MDBoolField, );
4831 #undef VISIT_MD_FIELDS
4833 Result
= GET_OR_DISTINCT(DINamespace
,
4834 (Context
, scope
.Val
, name
.Val
, exportSymbols
.Val
));
4839 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4841 bool LLParser::parseDIMacro(MDNode
*&Result
, bool IsDistinct
) {
4842 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4843 REQUIRED(type, DwarfMacinfoTypeField, ); \
4844 OPTIONAL(line, LineField, ); \
4845 REQUIRED(name, MDStringField, ); \
4846 OPTIONAL(value, MDStringField, );
4848 #undef VISIT_MD_FIELDS
4850 Result
= GET_OR_DISTINCT(DIMacro
,
4851 (Context
, type
.Val
, line
.Val
, name
.Val
, value
.Val
));
4855 /// parseDIMacroFile:
4856 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4857 bool LLParser::parseDIMacroFile(MDNode
*&Result
, bool IsDistinct
) {
4858 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4859 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4860 OPTIONAL(line, LineField, ); \
4861 REQUIRED(file, MDField, ); \
4862 OPTIONAL(nodes, MDField, );
4864 #undef VISIT_MD_FIELDS
4866 Result
= GET_OR_DISTINCT(DIMacroFile
,
4867 (Context
, type
.Val
, line
.Val
, file
.Val
, nodes
.Val
));
4872 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
4873 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
4874 /// file: !1, line: 4, isDecl: false)
4875 bool LLParser::parseDIModule(MDNode
*&Result
, bool IsDistinct
) {
4876 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4877 REQUIRED(scope, MDField, ); \
4878 REQUIRED(name, MDStringField, ); \
4879 OPTIONAL(configMacros, MDStringField, ); \
4880 OPTIONAL(includePath, MDStringField, ); \
4881 OPTIONAL(apinotes, MDStringField, ); \
4882 OPTIONAL(file, MDField, ); \
4883 OPTIONAL(line, LineField, ); \
4884 OPTIONAL(isDecl, MDBoolField, );
4886 #undef VISIT_MD_FIELDS
4888 Result
= GET_OR_DISTINCT(DIModule
, (Context
, file
.Val
, scope
.Val
, name
.Val
,
4889 configMacros
.Val
, includePath
.Val
,
4890 apinotes
.Val
, line
.Val
, isDecl
.Val
));
4894 /// parseDITemplateTypeParameter:
4895 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
4896 bool LLParser::parseDITemplateTypeParameter(MDNode
*&Result
, bool IsDistinct
) {
4897 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4898 OPTIONAL(name, MDStringField, ); \
4899 REQUIRED(type, MDField, ); \
4900 OPTIONAL(defaulted, MDBoolField, );
4902 #undef VISIT_MD_FIELDS
4904 Result
= GET_OR_DISTINCT(DITemplateTypeParameter
,
4905 (Context
, name
.Val
, type
.Val
, defaulted
.Val
));
4909 /// parseDITemplateValueParameter:
4910 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4911 /// name: "V", type: !1, defaulted: false,
4913 bool LLParser::parseDITemplateValueParameter(MDNode
*&Result
, bool IsDistinct
) {
4914 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4915 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4916 OPTIONAL(name, MDStringField, ); \
4917 OPTIONAL(type, MDField, ); \
4918 OPTIONAL(defaulted, MDBoolField, ); \
4919 REQUIRED(value, MDField, );
4922 #undef VISIT_MD_FIELDS
4924 Result
= GET_OR_DISTINCT(
4925 DITemplateValueParameter
,
4926 (Context
, tag
.Val
, name
.Val
, type
.Val
, defaulted
.Val
, value
.Val
));
4930 /// parseDIGlobalVariable:
4931 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4932 /// file: !1, line: 7, type: !2, isLocal: false,
4933 /// isDefinition: true, templateParams: !3,
4934 /// declaration: !4, align: 8)
4935 bool LLParser::parseDIGlobalVariable(MDNode
*&Result
, bool IsDistinct
) {
4936 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4937 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4938 OPTIONAL(scope, MDField, ); \
4939 OPTIONAL(linkageName, MDStringField, ); \
4940 OPTIONAL(file, MDField, ); \
4941 OPTIONAL(line, LineField, ); \
4942 OPTIONAL(type, MDField, ); \
4943 OPTIONAL(isLocal, MDBoolField, ); \
4944 OPTIONAL(isDefinition, MDBoolField, (true)); \
4945 OPTIONAL(templateParams, MDField, ); \
4946 OPTIONAL(declaration, MDField, ); \
4947 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4949 #undef VISIT_MD_FIELDS
4952 GET_OR_DISTINCT(DIGlobalVariable
,
4953 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
,
4954 line
.Val
, type
.Val
, isLocal
.Val
, isDefinition
.Val
,
4955 declaration
.Val
, templateParams
.Val
, align
.Val
));
4959 /// parseDILocalVariable:
4960 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4961 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4963 /// ::= !DILocalVariable(scope: !0, name: "foo",
4964 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4966 bool LLParser::parseDILocalVariable(MDNode
*&Result
, bool IsDistinct
) {
4967 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4968 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4969 OPTIONAL(name, MDStringField, ); \
4970 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4971 OPTIONAL(file, MDField, ); \
4972 OPTIONAL(line, LineField, ); \
4973 OPTIONAL(type, MDField, ); \
4974 OPTIONAL(flags, DIFlagField, ); \
4975 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4977 #undef VISIT_MD_FIELDS
4979 Result
= GET_OR_DISTINCT(DILocalVariable
,
4980 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
,
4981 type
.Val
, arg
.Val
, flags
.Val
, align
.Val
));
4986 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4987 bool LLParser::parseDILabel(MDNode
*&Result
, bool IsDistinct
) {
4988 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4989 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4990 REQUIRED(name, MDStringField, ); \
4991 REQUIRED(file, MDField, ); \
4992 REQUIRED(line, LineField, );
4994 #undef VISIT_MD_FIELDS
4996 Result
= GET_OR_DISTINCT(DILabel
,
4997 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
));
5001 /// parseDIExpression:
5002 /// ::= !DIExpression(0, 7, -1)
5003 bool LLParser::parseDIExpression(MDNode
*&Result
, bool IsDistinct
) {
5004 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
5007 if (parseToken(lltok::lparen
, "expected '(' here"))
5010 SmallVector
<uint64_t, 8> Elements
;
5011 if (Lex
.getKind() != lltok::rparen
)
5013 if (Lex
.getKind() == lltok::DwarfOp
) {
5014 if (unsigned Op
= dwarf::getOperationEncoding(Lex
.getStrVal())) {
5016 Elements
.push_back(Op
);
5019 return tokError(Twine("invalid DWARF op '") + Lex
.getStrVal() + "'");
5022 if (Lex
.getKind() == lltok::DwarfAttEncoding
) {
5023 if (unsigned Op
= dwarf::getAttributeEncoding(Lex
.getStrVal())) {
5025 Elements
.push_back(Op
);
5028 return tokError(Twine("invalid DWARF attribute encoding '") +
5029 Lex
.getStrVal() + "'");
5032 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
5033 return tokError("expected unsigned integer");
5035 auto &U
= Lex
.getAPSIntVal();
5036 if (U
.ugt(UINT64_MAX
))
5037 return tokError("element too large, limit is " + Twine(UINT64_MAX
));
5038 Elements
.push_back(U
.getZExtValue());
5040 } while (EatIfPresent(lltok::comma
));
5042 if (parseToken(lltok::rparen
, "expected ')' here"))
5045 Result
= GET_OR_DISTINCT(DIExpression
, (Context
, Elements
));
5049 bool LLParser::parseDIArgList(MDNode
*&Result
, bool IsDistinct
) {
5050 return parseDIArgList(Result
, IsDistinct
, nullptr);
5053 /// ::= !DIArgList(i32 7, i64 %0)
5054 bool LLParser::parseDIArgList(MDNode
*&Result
, bool IsDistinct
,
5055 PerFunctionState
*PFS
) {
5056 assert(PFS
&& "Expected valid function state");
5057 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
5060 if (parseToken(lltok::lparen
, "expected '(' here"))
5063 SmallVector
<ValueAsMetadata
*, 4> Args
;
5064 if (Lex
.getKind() != lltok::rparen
)
5067 if (parseValueAsMetadata(MD
, "expected value-as-metadata operand", PFS
))
5069 Args
.push_back(dyn_cast
<ValueAsMetadata
>(MD
));
5070 } while (EatIfPresent(lltok::comma
));
5072 if (parseToken(lltok::rparen
, "expected ')' here"))
5075 Result
= GET_OR_DISTINCT(DIArgList
, (Context
, Args
));
5079 /// parseDIGlobalVariableExpression:
5080 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5081 bool LLParser::parseDIGlobalVariableExpression(MDNode
*&Result
,
5083 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5084 REQUIRED(var, MDField, ); \
5085 REQUIRED(expr, MDField, );
5087 #undef VISIT_MD_FIELDS
5090 GET_OR_DISTINCT(DIGlobalVariableExpression
, (Context
, var
.Val
, expr
.Val
));
5094 /// parseDIObjCProperty:
5095 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5096 /// getter: "getFoo", attributes: 7, type: !2)
5097 bool LLParser::parseDIObjCProperty(MDNode
*&Result
, bool IsDistinct
) {
5098 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5099 OPTIONAL(name, MDStringField, ); \
5100 OPTIONAL(file, MDField, ); \
5101 OPTIONAL(line, LineField, ); \
5102 OPTIONAL(setter, MDStringField, ); \
5103 OPTIONAL(getter, MDStringField, ); \
5104 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5105 OPTIONAL(type, MDField, );
5107 #undef VISIT_MD_FIELDS
5109 Result
= GET_OR_DISTINCT(DIObjCProperty
,
5110 (Context
, name
.Val
, file
.Val
, line
.Val
, setter
.Val
,
5111 getter
.Val
, attributes
.Val
, type
.Val
));
5115 /// parseDIImportedEntity:
5116 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5117 /// line: 7, name: "foo")
5118 bool LLParser::parseDIImportedEntity(MDNode
*&Result
, bool IsDistinct
) {
5119 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5120 REQUIRED(tag, DwarfTagField, ); \
5121 REQUIRED(scope, MDField, ); \
5122 OPTIONAL(entity, MDField, ); \
5123 OPTIONAL(file, MDField, ); \
5124 OPTIONAL(line, LineField, ); \
5125 OPTIONAL(name, MDStringField, );
5127 #undef VISIT_MD_FIELDS
5129 Result
= GET_OR_DISTINCT(
5131 (Context
, tag
.Val
, scope
.Val
, entity
.Val
, file
.Val
, line
.Val
, name
.Val
));
5135 #undef PARSE_MD_FIELD
5137 #undef REQUIRE_FIELD
5138 #undef DECLARE_FIELD
5140 /// parseMetadataAsValue
5141 /// ::= metadata i32 %local
5142 /// ::= metadata i32 @global
5143 /// ::= metadata i32 7
5145 /// ::= metadata !{...}
5146 /// ::= metadata !"string"
5147 bool LLParser::parseMetadataAsValue(Value
*&V
, PerFunctionState
&PFS
) {
5148 // Note: the type 'metadata' has already been parsed.
5150 if (parseMetadata(MD
, &PFS
))
5153 V
= MetadataAsValue::get(Context
, MD
);
5157 /// parseValueAsMetadata
5161 bool LLParser::parseValueAsMetadata(Metadata
*&MD
, const Twine
&TypeMsg
,
5162 PerFunctionState
*PFS
) {
5165 if (parseType(Ty
, TypeMsg
, Loc
))
5167 if (Ty
->isMetadataTy())
5168 return error(Loc
, "invalid metadata-value-metadata roundtrip");
5171 if (parseValue(Ty
, V
, PFS
))
5174 MD
= ValueAsMetadata::get(V
);
5185 /// ::= !DILocation(...)
5186 bool LLParser::parseMetadata(Metadata
*&MD
, PerFunctionState
*PFS
) {
5187 if (Lex
.getKind() == lltok::MetadataVar
) {
5189 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5190 // so parsing this requires a Function State.
5191 if (Lex
.getStrVal() == "DIArgList") {
5192 if (parseDIArgList(N
, false, PFS
))
5194 } else if (parseSpecializedMDNode(N
)) {
5203 if (Lex
.getKind() != lltok::exclaim
)
5204 return parseValueAsMetadata(MD
, "expected metadata operand", PFS
);
5207 assert(Lex
.getKind() == lltok::exclaim
&& "Expected '!' here");
5211 // ::= '!' STRINGCONSTANT
5212 if (Lex
.getKind() == lltok::StringConstant
) {
5214 if (parseMDString(S
))
5224 if (parseMDNodeTail(N
))
5230 //===----------------------------------------------------------------------===//
5231 // Function Parsing.
5232 //===----------------------------------------------------------------------===//
5234 bool LLParser::convertValIDToValue(Type
*Ty
, ValID
&ID
, Value
*&V
,
5235 PerFunctionState
*PFS
, bool IsCall
) {
5236 if (Ty
->isFunctionTy())
5237 return error(ID
.Loc
, "functions are not values, refer to them as pointers");
5240 case ValID::t_LocalID
:
5242 return error(ID
.Loc
, "invalid use of function-local name");
5243 V
= PFS
->getVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5244 return V
== nullptr;
5245 case ValID::t_LocalName
:
5247 return error(ID
.Loc
, "invalid use of function-local name");
5248 V
= PFS
->getVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5249 return V
== nullptr;
5250 case ValID::t_InlineAsm
: {
5251 if (!ID
.FTy
|| !InlineAsm::Verify(ID
.FTy
, ID
.StrVal2
))
5252 return error(ID
.Loc
, "invalid type for inline asm constraint string");
5254 ID
.FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
& 1, (ID
.UIntVal
>> 1) & 1,
5255 InlineAsm::AsmDialect((ID
.UIntVal
>> 2) & 1), (ID
.UIntVal
>> 3) & 1);
5258 case ValID::t_GlobalName
:
5259 V
= getGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5260 return V
== nullptr;
5261 case ValID::t_GlobalID
:
5262 V
= getGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5263 return V
== nullptr;
5264 case ValID::t_APSInt
:
5265 if (!Ty
->isIntegerTy())
5266 return error(ID
.Loc
, "integer constant must have integer type");
5267 ID
.APSIntVal
= ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
5268 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
5270 case ValID::t_APFloat
:
5271 if (!Ty
->isFloatingPointTy() ||
5272 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
5273 return error(ID
.Loc
, "floating point constant invalid for type");
5275 // The lexer has no type info, so builds all half, bfloat, float, and double
5276 // FP constants as double. Fix this here. Long double does not need this.
5277 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble()) {
5278 // Check for signaling before potentially converting and losing that info.
5279 bool IsSNAN
= ID
.APFloatVal
.isSignaling();
5282 ID
.APFloatVal
.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven
,
5284 else if (Ty
->isBFloatTy())
5285 ID
.APFloatVal
.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven
,
5287 else if (Ty
->isFloatTy())
5288 ID
.APFloatVal
.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven
,
5291 // The convert call above may quiet an SNaN, so manufacture another
5292 // SNaN. The bitcast works because the payload (significand) parameter
5293 // is truncated to fit.
5294 APInt Payload
= ID
.APFloatVal
.bitcastToAPInt();
5295 ID
.APFloatVal
= APFloat::getSNaN(ID
.APFloatVal
.getSemantics(),
5296 ID
.APFloatVal
.isNegative(), &Payload
);
5299 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
5301 if (V
->getType() != Ty
)
5302 return error(ID
.Loc
, "floating point constant does not have type '" +
5303 getTypeString(Ty
) + "'");
5307 if (!Ty
->isPointerTy())
5308 return error(ID
.Loc
, "null must be a pointer type");
5309 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
5311 case ValID::t_Undef
:
5312 // FIXME: LabelTy should not be a first-class type.
5313 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5314 return error(ID
.Loc
, "invalid type for undef constant");
5315 V
= UndefValue::get(Ty
);
5317 case ValID::t_EmptyArray
:
5318 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
5319 return error(ID
.Loc
, "invalid empty array initializer");
5320 V
= UndefValue::get(Ty
);
5323 // FIXME: LabelTy should not be a first-class type.
5324 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5325 return error(ID
.Loc
, "invalid type for null constant");
5326 V
= Constant::getNullValue(Ty
);
5329 if (!Ty
->isTokenTy())
5330 return error(ID
.Loc
, "invalid type for none constant");
5331 V
= Constant::getNullValue(Ty
);
5333 case ValID::t_Poison
:
5334 // FIXME: LabelTy should not be a first-class type.
5335 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5336 return error(ID
.Loc
, "invalid type for poison constant");
5337 V
= PoisonValue::get(Ty
);
5339 case ValID::t_Constant
:
5340 if (ID
.ConstantVal
->getType() != Ty
)
5341 return error(ID
.Loc
, "constant expression type mismatch: got type '" +
5342 getTypeString(ID
.ConstantVal
->getType()) +
5343 "' but expected '" + getTypeString(Ty
) + "'");
5346 case ValID::t_ConstantStruct
:
5347 case ValID::t_PackedConstantStruct
:
5348 if (StructType
*ST
= dyn_cast
<StructType
>(Ty
)) {
5349 if (ST
->getNumElements() != ID
.UIntVal
)
5350 return error(ID
.Loc
,
5351 "initializer with struct type has wrong # elements");
5352 if (ST
->isPacked() != (ID
.Kind
== ValID::t_PackedConstantStruct
))
5353 return error(ID
.Loc
, "packed'ness of initializer and type don't match");
5355 // Verify that the elements are compatible with the structtype.
5356 for (unsigned i
= 0, e
= ID
.UIntVal
; i
!= e
; ++i
)
5357 if (ID
.ConstantStructElts
[i
]->getType() != ST
->getElementType(i
))
5360 "element " + Twine(i
) +
5361 " of struct initializer doesn't match struct element type");
5363 V
= ConstantStruct::get(
5364 ST
, makeArrayRef(ID
.ConstantStructElts
.get(), ID
.UIntVal
));
5366 return error(ID
.Loc
, "constant expression type mismatch");
5369 llvm_unreachable("Invalid ValID");
5372 bool LLParser::parseConstantValue(Type
*Ty
, Constant
*&C
) {
5375 auto Loc
= Lex
.getLoc();
5376 if (parseValID(ID
, /*PFS=*/nullptr))
5379 case ValID::t_APSInt
:
5380 case ValID::t_APFloat
:
5381 case ValID::t_Undef
:
5382 case ValID::t_Constant
:
5383 case ValID::t_ConstantStruct
:
5384 case ValID::t_PackedConstantStruct
: {
5386 if (convertValIDToValue(Ty
, ID
, V
, /*PFS=*/nullptr, /*IsCall=*/false))
5388 assert(isa
<Constant
>(V
) && "Expected a constant value");
5389 C
= cast
<Constant
>(V
);
5393 C
= Constant::getNullValue(Ty
);
5396 return error(Loc
, "expected a constant value");
5400 bool LLParser::parseValue(Type
*Ty
, Value
*&V
, PerFunctionState
*PFS
) {
5403 return parseValID(ID
, PFS
, Ty
) ||
5404 convertValIDToValue(Ty
, ID
, V
, PFS
, /*IsCall=*/false);
5407 bool LLParser::parseTypeAndValue(Value
*&V
, PerFunctionState
*PFS
) {
5409 return parseType(Ty
) || parseValue(Ty
, V
, PFS
);
5412 bool LLParser::parseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
5413 PerFunctionState
&PFS
) {
5416 if (parseTypeAndValue(V
, PFS
))
5418 if (!isa
<BasicBlock
>(V
))
5419 return error(Loc
, "expected a basic block");
5420 BB
= cast
<BasicBlock
>(V
);
5425 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5426 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5427 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5428 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5429 bool LLParser::parseFunctionHeader(Function
*&Fn
, bool IsDefine
) {
5430 // parse the linkage.
5431 LocTy LinkageLoc
= Lex
.getLoc();
5433 unsigned Visibility
;
5434 unsigned DLLStorageClass
;
5436 AttrBuilder RetAttrs
;
5439 Type
*RetType
= nullptr;
5440 LocTy RetTypeLoc
= Lex
.getLoc();
5441 if (parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
5443 parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
5444 parseType(RetType
, RetTypeLoc
, true /*void allowed*/))
5447 // Verify that the linkage is ok.
5448 switch ((GlobalValue::LinkageTypes
)Linkage
) {
5449 case GlobalValue::ExternalLinkage
:
5450 break; // always ok.
5451 case GlobalValue::ExternalWeakLinkage
:
5453 return error(LinkageLoc
, "invalid linkage for function definition");
5455 case GlobalValue::PrivateLinkage
:
5456 case GlobalValue::InternalLinkage
:
5457 case GlobalValue::AvailableExternallyLinkage
:
5458 case GlobalValue::LinkOnceAnyLinkage
:
5459 case GlobalValue::LinkOnceODRLinkage
:
5460 case GlobalValue::WeakAnyLinkage
:
5461 case GlobalValue::WeakODRLinkage
:
5463 return error(LinkageLoc
, "invalid linkage for function declaration");
5465 case GlobalValue::AppendingLinkage
:
5466 case GlobalValue::CommonLinkage
:
5467 return error(LinkageLoc
, "invalid function linkage type");
5470 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
5471 return error(LinkageLoc
,
5472 "symbol with local linkage must have default visibility");
5474 if (!FunctionType::isValidReturnType(RetType
))
5475 return error(RetTypeLoc
, "invalid function return type");
5477 LocTy NameLoc
= Lex
.getLoc();
5479 std::string FunctionName
;
5480 if (Lex
.getKind() == lltok::GlobalVar
) {
5481 FunctionName
= Lex
.getStrVal();
5482 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
5483 unsigned NameID
= Lex
.getUIntVal();
5485 if (NameID
!= NumberedVals
.size())
5486 return tokError("function expected to be numbered '%" +
5487 Twine(NumberedVals
.size()) + "'");
5489 return tokError("expected function name");
5494 if (Lex
.getKind() != lltok::lparen
)
5495 return tokError("expected '(' in function argument list");
5497 SmallVector
<ArgInfo
, 8> ArgList
;
5499 AttrBuilder FuncAttrs
;
5500 std::vector
<unsigned> FwdRefAttrGrps
;
5502 std::string Section
;
5503 std::string Partition
;
5504 MaybeAlign Alignment
;
5506 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
5507 unsigned AddrSpace
= 0;
5508 Constant
*Prefix
= nullptr;
5509 Constant
*Prologue
= nullptr;
5510 Constant
*PersonalityFn
= nullptr;
5513 if (parseArgumentList(ArgList
, IsVarArg
) ||
5514 parseOptionalUnnamedAddr(UnnamedAddr
) ||
5515 parseOptionalProgramAddrSpace(AddrSpace
) ||
5516 parseFnAttributeValuePairs(FuncAttrs
, FwdRefAttrGrps
, false,
5518 (EatIfPresent(lltok::kw_section
) && parseStringConstant(Section
)) ||
5519 (EatIfPresent(lltok::kw_partition
) && parseStringConstant(Partition
)) ||
5520 parseOptionalComdat(FunctionName
, C
) ||
5521 parseOptionalAlignment(Alignment
) ||
5522 (EatIfPresent(lltok::kw_gc
) && parseStringConstant(GC
)) ||
5523 (EatIfPresent(lltok::kw_prefix
) && parseGlobalTypeAndValue(Prefix
)) ||
5524 (EatIfPresent(lltok::kw_prologue
) && parseGlobalTypeAndValue(Prologue
)) ||
5525 (EatIfPresent(lltok::kw_personality
) &&
5526 parseGlobalTypeAndValue(PersonalityFn
)))
5529 if (FuncAttrs
.contains(Attribute::Builtin
))
5530 return error(BuiltinLoc
, "'builtin' attribute not valid on function");
5532 // If the alignment was parsed as an attribute, move to the alignment field.
5533 if (FuncAttrs
.hasAlignmentAttr()) {
5534 Alignment
= FuncAttrs
.getAlignment();
5535 FuncAttrs
.removeAttribute(Attribute::Alignment
);
5538 // Okay, if we got here, the function is syntactically valid. Convert types
5539 // and do semantic checks.
5540 std::vector
<Type
*> ParamTypeList
;
5541 SmallVector
<AttributeSet
, 8> Attrs
;
5543 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5544 ParamTypeList
.push_back(ArgList
[i
].Ty
);
5545 Attrs
.push_back(ArgList
[i
].Attrs
);
5549 AttributeList::get(Context
, AttributeSet::get(Context
, FuncAttrs
),
5550 AttributeSet::get(Context
, RetAttrs
), Attrs
);
5552 if (PAL
.hasParamAttr(0, Attribute::StructRet
) && !RetType
->isVoidTy())
5553 return error(RetTypeLoc
, "functions with 'sret' argument must return void");
5555 FunctionType
*FT
= FunctionType::get(RetType
, ParamTypeList
, IsVarArg
);
5556 PointerType
*PFT
= PointerType::get(FT
, AddrSpace
);
5559 GlobalValue
*FwdFn
= nullptr;
5560 if (!FunctionName
.empty()) {
5561 // If this was a definition of a forward reference, remove the definition
5562 // from the forward reference table and fill in the forward ref.
5563 auto FRVI
= ForwardRefVals
.find(FunctionName
);
5564 if (FRVI
!= ForwardRefVals
.end()) {
5565 FwdFn
= FRVI
->second
.first
;
5566 if (!FwdFn
->getType()->isOpaque()) {
5567 if (!FwdFn
->getType()->getPointerElementType()->isFunctionTy())
5568 return error(FRVI
->second
.second
, "invalid forward reference to "
5569 "function as global value!");
5570 if (FwdFn
->getType() != PFT
)
5571 return error(FRVI
->second
.second
,
5572 "invalid forward reference to "
5575 "' with wrong type: "
5577 getTypeString(PFT
) + "' but was '" +
5578 getTypeString(FwdFn
->getType()) + "'");
5580 ForwardRefVals
.erase(FRVI
);
5581 } else if ((Fn
= M
->getFunction(FunctionName
))) {
5582 // Reject redefinitions.
5583 return error(NameLoc
,
5584 "invalid redefinition of function '" + FunctionName
+ "'");
5585 } else if (M
->getNamedValue(FunctionName
)) {
5586 return error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
5590 // If this is a definition of a forward referenced function, make sure the
5592 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
5593 if (I
!= ForwardRefValIDs
.end()) {
5594 FwdFn
= cast
<Function
>(I
->second
.first
);
5595 if (!FwdFn
->getType()->isOpaque() && FwdFn
->getType() != PFT
)
5596 return error(NameLoc
, "type of definition and forward reference of '@" +
5597 Twine(NumberedVals
.size()) +
5600 getTypeString(PFT
) + "' but was '" +
5601 getTypeString(FwdFn
->getType()) + "'");
5602 ForwardRefValIDs
.erase(I
);
5606 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, AddrSpace
,
5609 assert(Fn
->getAddressSpace() == AddrSpace
&& "Created function in wrong AS");
5611 if (FunctionName
.empty())
5612 NumberedVals
.push_back(Fn
);
5614 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
5615 maybeSetDSOLocal(DSOLocal
, *Fn
);
5616 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
5617 Fn
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
5618 Fn
->setCallingConv(CC
);
5619 Fn
->setAttributes(PAL
);
5620 Fn
->setUnnamedAddr(UnnamedAddr
);
5621 Fn
->setAlignment(MaybeAlign(Alignment
));
5622 Fn
->setSection(Section
);
5623 Fn
->setPartition(Partition
);
5625 Fn
->setPersonalityFn(PersonalityFn
);
5626 if (!GC
.empty()) Fn
->setGC(GC
);
5627 Fn
->setPrefixData(Prefix
);
5628 Fn
->setPrologueData(Prologue
);
5629 ForwardRefAttrGroups
[Fn
] = FwdRefAttrGrps
;
5631 // Add all of the arguments we parsed to the function.
5632 Function::arg_iterator ArgIt
= Fn
->arg_begin();
5633 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
5634 // If the argument has a name, insert it into the argument symbol table.
5635 if (ArgList
[i
].Name
.empty()) continue;
5637 // Set the name, if it conflicted, it will be auto-renamed.
5638 ArgIt
->setName(ArgList
[i
].Name
);
5640 if (ArgIt
->getName() != ArgList
[i
].Name
)
5641 return error(ArgList
[i
].Loc
,
5642 "redefinition of argument '%" + ArgList
[i
].Name
+ "'");
5646 FwdFn
->replaceAllUsesWith(Fn
);
5647 FwdFn
->eraseFromParent();
5653 // Check the declaration has no block address forward references.
5655 if (FunctionName
.empty()) {
5656 ID
.Kind
= ValID::t_GlobalID
;
5657 ID
.UIntVal
= NumberedVals
.size() - 1;
5659 ID
.Kind
= ValID::t_GlobalName
;
5660 ID
.StrVal
= FunctionName
;
5662 auto Blocks
= ForwardRefBlockAddresses
.find(ID
);
5663 if (Blocks
!= ForwardRefBlockAddresses
.end())
5664 return error(Blocks
->first
.Loc
,
5665 "cannot take blockaddress inside a declaration");
5669 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5671 if (FunctionNumber
== -1) {
5672 ID
.Kind
= ValID::t_GlobalName
;
5673 ID
.StrVal
= std::string(F
.getName());
5675 ID
.Kind
= ValID::t_GlobalID
;
5676 ID
.UIntVal
= FunctionNumber
;
5679 auto Blocks
= P
.ForwardRefBlockAddresses
.find(ID
);
5680 if (Blocks
== P
.ForwardRefBlockAddresses
.end())
5683 for (const auto &I
: Blocks
->second
) {
5684 const ValID
&BBID
= I
.first
;
5685 GlobalValue
*GV
= I
.second
;
5687 assert((BBID
.Kind
== ValID::t_LocalID
|| BBID
.Kind
== ValID::t_LocalName
) &&
5688 "Expected local id or name");
5690 if (BBID
.Kind
== ValID::t_LocalName
)
5691 BB
= getBB(BBID
.StrVal
, BBID
.Loc
);
5693 BB
= getBB(BBID
.UIntVal
, BBID
.Loc
);
5695 return P
.error(BBID
.Loc
, "referenced value is not a basic block");
5697 Value
*ResolvedVal
= BlockAddress::get(&F
, BB
);
5698 ResolvedVal
= P
.checkValidVariableType(BBID
.Loc
, BBID
.StrVal
, GV
->getType(),
5699 ResolvedVal
, false);
5702 GV
->replaceAllUsesWith(ResolvedVal
);
5703 GV
->eraseFromParent();
5706 P
.ForwardRefBlockAddresses
.erase(Blocks
);
5710 /// parseFunctionBody
5711 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5712 bool LLParser::parseFunctionBody(Function
&Fn
) {
5713 if (Lex
.getKind() != lltok::lbrace
)
5714 return tokError("expected '{' in function body");
5715 Lex
.Lex(); // eat the {.
5717 int FunctionNumber
= -1;
5718 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
5720 PerFunctionState
PFS(*this, Fn
, FunctionNumber
);
5722 // Resolve block addresses and allow basic blocks to be forward-declared
5723 // within this function.
5724 if (PFS
.resolveForwardRefBlockAddresses())
5726 SaveAndRestore
<PerFunctionState
*> ScopeExit(BlockAddressPFS
, &PFS
);
5728 // We need at least one basic block.
5729 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_uselistorder
)
5730 return tokError("function body requires at least one basic block");
5732 while (Lex
.getKind() != lltok::rbrace
&&
5733 Lex
.getKind() != lltok::kw_uselistorder
)
5734 if (parseBasicBlock(PFS
))
5737 while (Lex
.getKind() != lltok::rbrace
)
5738 if (parseUseListOrder(&PFS
))
5744 // Verify function is ok.
5745 return PFS
.finishFunction();
5749 /// ::= (LabelStr|LabelID)? Instruction*
5750 bool LLParser::parseBasicBlock(PerFunctionState
&PFS
) {
5751 // If this basic block starts out with a name, remember it.
5754 LocTy NameLoc
= Lex
.getLoc();
5755 if (Lex
.getKind() == lltok::LabelStr
) {
5756 Name
= Lex
.getStrVal();
5758 } else if (Lex
.getKind() == lltok::LabelID
) {
5759 NameID
= Lex
.getUIntVal();
5763 BasicBlock
*BB
= PFS
.defineBB(Name
, NameID
, NameLoc
);
5767 std::string NameStr
;
5769 // parse the instructions in this block until we get a terminator.
5772 // This instruction may have three possibilities for a name: a) none
5773 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5774 LocTy NameLoc
= Lex
.getLoc();
5778 if (Lex
.getKind() == lltok::LocalVarID
) {
5779 NameID
= Lex
.getUIntVal();
5781 if (parseToken(lltok::equal
, "expected '=' after instruction id"))
5783 } else if (Lex
.getKind() == lltok::LocalVar
) {
5784 NameStr
= Lex
.getStrVal();
5786 if (parseToken(lltok::equal
, "expected '=' after instruction name"))
5790 switch (parseInstruction(Inst
, BB
, PFS
)) {
5792 llvm_unreachable("Unknown parseInstruction result!");
5793 case InstError
: return true;
5795 BB
->getInstList().push_back(Inst
);
5797 // With a normal result, we check to see if the instruction is followed by
5798 // a comma and metadata.
5799 if (EatIfPresent(lltok::comma
))
5800 if (parseInstructionMetadata(*Inst
))
5803 case InstExtraComma
:
5804 BB
->getInstList().push_back(Inst
);
5806 // If the instruction parser ate an extra comma at the end of it, it
5807 // *must* be followed by metadata.
5808 if (parseInstructionMetadata(*Inst
))
5813 // Set the name on the instruction.
5814 if (PFS
.setInstName(NameID
, NameStr
, NameLoc
, Inst
))
5816 } while (!Inst
->isTerminator());
5821 //===----------------------------------------------------------------------===//
5822 // Instruction Parsing.
5823 //===----------------------------------------------------------------------===//
5825 /// parseInstruction - parse one of the many different instructions.
5827 int LLParser::parseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
5828 PerFunctionState
&PFS
) {
5829 lltok::Kind Token
= Lex
.getKind();
5830 if (Token
== lltok::Eof
)
5831 return tokError("found end of file when expecting more instructions");
5832 LocTy Loc
= Lex
.getLoc();
5833 unsigned KeywordVal
= Lex
.getUIntVal();
5834 Lex
.Lex(); // Eat the keyword.
5838 return error(Loc
, "expected instruction opcode");
5839 // Terminator Instructions.
5840 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
5842 return parseRet(Inst
, BB
, PFS
);
5844 return parseBr(Inst
, PFS
);
5845 case lltok::kw_switch
:
5846 return parseSwitch(Inst
, PFS
);
5847 case lltok::kw_indirectbr
:
5848 return parseIndirectBr(Inst
, PFS
);
5849 case lltok::kw_invoke
:
5850 return parseInvoke(Inst
, PFS
);
5851 case lltok::kw_resume
:
5852 return parseResume(Inst
, PFS
);
5853 case lltok::kw_cleanupret
:
5854 return parseCleanupRet(Inst
, PFS
);
5855 case lltok::kw_catchret
:
5856 return parseCatchRet(Inst
, PFS
);
5857 case lltok::kw_catchswitch
:
5858 return parseCatchSwitch(Inst
, PFS
);
5859 case lltok::kw_catchpad
:
5860 return parseCatchPad(Inst
, PFS
);
5861 case lltok::kw_cleanuppad
:
5862 return parseCleanupPad(Inst
, PFS
);
5863 case lltok::kw_callbr
:
5864 return parseCallBr(Inst
, PFS
);
5866 case lltok::kw_fneg
: {
5867 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5868 int Res
= parseUnaryOp(Inst
, PFS
, KeywordVal
, /*IsFP*/ true);
5872 Inst
->setFastMathFlags(FMF
);
5875 // Binary Operators.
5879 case lltok::kw_shl
: {
5880 bool NUW
= EatIfPresent(lltok::kw_nuw
);
5881 bool NSW
= EatIfPresent(lltok::kw_nsw
);
5882 if (!NUW
) NUW
= EatIfPresent(lltok::kw_nuw
);
5884 if (parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ false))
5887 if (NUW
) cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
5888 if (NSW
) cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
5891 case lltok::kw_fadd
:
5892 case lltok::kw_fsub
:
5893 case lltok::kw_fmul
:
5894 case lltok::kw_fdiv
:
5895 case lltok::kw_frem
: {
5896 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5897 int Res
= parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ true);
5901 Inst
->setFastMathFlags(FMF
);
5905 case lltok::kw_sdiv
:
5906 case lltok::kw_udiv
:
5907 case lltok::kw_lshr
:
5908 case lltok::kw_ashr
: {
5909 bool Exact
= EatIfPresent(lltok::kw_exact
);
5911 if (parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ false))
5913 if (Exact
) cast
<BinaryOperator
>(Inst
)->setIsExact(true);
5917 case lltok::kw_urem
:
5918 case lltok::kw_srem
:
5919 return parseArithmetic(Inst
, PFS
, KeywordVal
,
5924 return parseLogical(Inst
, PFS
, KeywordVal
);
5925 case lltok::kw_icmp
:
5926 return parseCompare(Inst
, PFS
, KeywordVal
);
5927 case lltok::kw_fcmp
: {
5928 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5929 int Res
= parseCompare(Inst
, PFS
, KeywordVal
);
5933 Inst
->setFastMathFlags(FMF
);
5938 case lltok::kw_trunc
:
5939 case lltok::kw_zext
:
5940 case lltok::kw_sext
:
5941 case lltok::kw_fptrunc
:
5942 case lltok::kw_fpext
:
5943 case lltok::kw_bitcast
:
5944 case lltok::kw_addrspacecast
:
5945 case lltok::kw_uitofp
:
5946 case lltok::kw_sitofp
:
5947 case lltok::kw_fptoui
:
5948 case lltok::kw_fptosi
:
5949 case lltok::kw_inttoptr
:
5950 case lltok::kw_ptrtoint
:
5951 return parseCast(Inst
, PFS
, KeywordVal
);
5953 case lltok::kw_select
: {
5954 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5955 int Res
= parseSelect(Inst
, PFS
);
5959 if (!isa
<FPMathOperator
>(Inst
))
5960 return error(Loc
, "fast-math-flags specified for select without "
5961 "floating-point scalar or vector return type");
5962 Inst
->setFastMathFlags(FMF
);
5966 case lltok::kw_va_arg
:
5967 return parseVAArg(Inst
, PFS
);
5968 case lltok::kw_extractelement
:
5969 return parseExtractElement(Inst
, PFS
);
5970 case lltok::kw_insertelement
:
5971 return parseInsertElement(Inst
, PFS
);
5972 case lltok::kw_shufflevector
:
5973 return parseShuffleVector(Inst
, PFS
);
5974 case lltok::kw_phi
: {
5975 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5976 int Res
= parsePHI(Inst
, PFS
);
5980 if (!isa
<FPMathOperator
>(Inst
))
5981 return error(Loc
, "fast-math-flags specified for phi without "
5982 "floating-point scalar or vector return type");
5983 Inst
->setFastMathFlags(FMF
);
5987 case lltok::kw_landingpad
:
5988 return parseLandingPad(Inst
, PFS
);
5989 case lltok::kw_freeze
:
5990 return parseFreeze(Inst
, PFS
);
5992 case lltok::kw_call
:
5993 return parseCall(Inst
, PFS
, CallInst::TCK_None
);
5994 case lltok::kw_tail
:
5995 return parseCall(Inst
, PFS
, CallInst::TCK_Tail
);
5996 case lltok::kw_musttail
:
5997 return parseCall(Inst
, PFS
, CallInst::TCK_MustTail
);
5998 case lltok::kw_notail
:
5999 return parseCall(Inst
, PFS
, CallInst::TCK_NoTail
);
6001 case lltok::kw_alloca
:
6002 return parseAlloc(Inst
, PFS
);
6003 case lltok::kw_load
:
6004 return parseLoad(Inst
, PFS
);
6005 case lltok::kw_store
:
6006 return parseStore(Inst
, PFS
);
6007 case lltok::kw_cmpxchg
:
6008 return parseCmpXchg(Inst
, PFS
);
6009 case lltok::kw_atomicrmw
:
6010 return parseAtomicRMW(Inst
, PFS
);
6011 case lltok::kw_fence
:
6012 return parseFence(Inst
, PFS
);
6013 case lltok::kw_getelementptr
:
6014 return parseGetElementPtr(Inst
, PFS
);
6015 case lltok::kw_extractvalue
:
6016 return parseExtractValue(Inst
, PFS
);
6017 case lltok::kw_insertvalue
:
6018 return parseInsertValue(Inst
, PFS
);
6022 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6023 bool LLParser::parseCmpPredicate(unsigned &P
, unsigned Opc
) {
6024 if (Opc
== Instruction::FCmp
) {
6025 switch (Lex
.getKind()) {
6027 return tokError("expected fcmp predicate (e.g. 'oeq')");
6028 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
6029 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
6030 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
6031 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
6032 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
6033 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
6034 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
6035 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
6036 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
6037 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
6038 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
6039 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
6040 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
6041 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
6042 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
6043 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
6046 switch (Lex
.getKind()) {
6048 return tokError("expected icmp predicate (e.g. 'eq')");
6049 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
6050 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
6051 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
6052 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
6053 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
6054 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
6055 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
6056 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
6057 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
6058 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
6065 //===----------------------------------------------------------------------===//
6066 // Terminator Instructions.
6067 //===----------------------------------------------------------------------===//
6069 /// parseRet - parse a return instruction.
6070 /// ::= 'ret' void (',' !dbg, !1)*
6071 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6072 bool LLParser::parseRet(Instruction
*&Inst
, BasicBlock
*BB
,
6073 PerFunctionState
&PFS
) {
6074 SMLoc TypeLoc
= Lex
.getLoc();
6076 if (parseType(Ty
, true /*void allowed*/))
6079 Type
*ResType
= PFS
.getFunction().getReturnType();
6081 if (Ty
->isVoidTy()) {
6082 if (!ResType
->isVoidTy())
6083 return error(TypeLoc
, "value doesn't match function result type '" +
6084 getTypeString(ResType
) + "'");
6086 Inst
= ReturnInst::Create(Context
);
6091 if (parseValue(Ty
, RV
, PFS
))
6094 if (ResType
!= RV
->getType())
6095 return error(TypeLoc
, "value doesn't match function result type '" +
6096 getTypeString(ResType
) + "'");
6098 Inst
= ReturnInst::Create(Context
, RV
);
6103 /// ::= 'br' TypeAndValue
6104 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6105 bool LLParser::parseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6108 BasicBlock
*Op1
, *Op2
;
6109 if (parseTypeAndValue(Op0
, Loc
, PFS
))
6112 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
6113 Inst
= BranchInst::Create(BB
);
6117 if (Op0
->getType() != Type::getInt1Ty(Context
))
6118 return error(Loc
, "branch condition must have 'i1' type");
6120 if (parseToken(lltok::comma
, "expected ',' after branch condition") ||
6121 parseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
6122 parseToken(lltok::comma
, "expected ',' after true destination") ||
6123 parseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
6126 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
6132 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6134 /// ::= (TypeAndValue ',' TypeAndValue)*
6135 bool LLParser::parseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6136 LocTy CondLoc
, BBLoc
;
6138 BasicBlock
*DefaultBB
;
6139 if (parseTypeAndValue(Cond
, CondLoc
, PFS
) ||
6140 parseToken(lltok::comma
, "expected ',' after switch condition") ||
6141 parseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
6142 parseToken(lltok::lsquare
, "expected '[' with switch table"))
6145 if (!Cond
->getType()->isIntegerTy())
6146 return error(CondLoc
, "switch condition must have integer type");
6148 // parse the jump table pairs.
6149 SmallPtrSet
<Value
*, 32> SeenCases
;
6150 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
6151 while (Lex
.getKind() != lltok::rsquare
) {
6155 if (parseTypeAndValue(Constant
, CondLoc
, PFS
) ||
6156 parseToken(lltok::comma
, "expected ',' after case value") ||
6157 parseTypeAndBasicBlock(DestBB
, PFS
))
6160 if (!SeenCases
.insert(Constant
).second
)
6161 return error(CondLoc
, "duplicate case value in switch");
6162 if (!isa
<ConstantInt
>(Constant
))
6163 return error(CondLoc
, "case value is not a constant integer");
6165 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
6168 Lex
.Lex(); // Eat the ']'.
6170 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
6171 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
6172 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
6179 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6180 bool LLParser::parseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6183 if (parseTypeAndValue(Address
, AddrLoc
, PFS
) ||
6184 parseToken(lltok::comma
, "expected ',' after indirectbr address") ||
6185 parseToken(lltok::lsquare
, "expected '[' with indirectbr"))
6188 if (!Address
->getType()->isPointerTy())
6189 return error(AddrLoc
, "indirectbr address must have pointer type");
6191 // parse the destination list.
6192 SmallVector
<BasicBlock
*, 16> DestList
;
6194 if (Lex
.getKind() != lltok::rsquare
) {
6196 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6198 DestList
.push_back(DestBB
);
6200 while (EatIfPresent(lltok::comma
)) {
6201 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6203 DestList
.push_back(DestBB
);
6207 if (parseToken(lltok::rsquare
, "expected ']' at end of block list"))
6210 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
6211 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
6212 IBI
->addDestination(DestList
[i
]);
6218 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6219 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6220 bool LLParser::parseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6221 LocTy CallLoc
= Lex
.getLoc();
6222 AttrBuilder RetAttrs
, FnAttrs
;
6223 std::vector
<unsigned> FwdRefAttrGrps
;
6226 unsigned InvokeAddrSpace
;
6227 Type
*RetType
= nullptr;
6230 SmallVector
<ParamInfo
, 16> ArgList
;
6231 SmallVector
<OperandBundleDef
, 2> BundleList
;
6233 BasicBlock
*NormalBB
, *UnwindBB
;
6234 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
6235 parseOptionalProgramAddrSpace(InvokeAddrSpace
) ||
6236 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6237 parseValID(CalleeID
, &PFS
) || parseParameterList(ArgList
, PFS
) ||
6238 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6240 parseOptionalOperandBundles(BundleList
, PFS
) ||
6241 parseToken(lltok::kw_to
, "expected 'to' in invoke") ||
6242 parseTypeAndBasicBlock(NormalBB
, PFS
) ||
6243 parseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
6244 parseTypeAndBasicBlock(UnwindBB
, PFS
))
6247 // If RetType is a non-function pointer type, then this is the short syntax
6248 // for the call, which means that RetType is just the return type. Infer the
6249 // rest of the function argument types from the arguments that are present.
6250 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6252 // Pull out the types of all of the arguments...
6253 std::vector
<Type
*> ParamTypes
;
6254 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6255 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6257 if (!FunctionType::isValidReturnType(RetType
))
6258 return error(RetTypeLoc
, "Invalid result type for LLVM function");
6260 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6265 // Look up the callee.
6267 if (convertValIDToValue(PointerType::get(Ty
, InvokeAddrSpace
), CalleeID
,
6268 Callee
, &PFS
, /*IsCall=*/true))
6271 // Set up the Attribute for the function.
6272 SmallVector
<Value
*, 8> Args
;
6273 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6275 // Loop through FunctionType's arguments and ensure they are specified
6276 // correctly. Also, gather any parameter attributes.
6277 FunctionType::param_iterator I
= Ty
->param_begin();
6278 FunctionType::param_iterator E
= Ty
->param_end();
6279 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6280 Type
*ExpectedTy
= nullptr;
6283 } else if (!Ty
->isVarArg()) {
6284 return error(ArgList
[i
].Loc
, "too many arguments specified");
6287 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6288 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6289 getTypeString(ExpectedTy
) + "'");
6290 Args
.push_back(ArgList
[i
].V
);
6291 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6295 return error(CallLoc
, "not enough parameters specified for call");
6297 if (FnAttrs
.hasAlignmentAttr())
6298 return error(CallLoc
, "invoke instructions may not have an alignment");
6300 // Finish off the Attribute and check them
6302 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6303 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6306 InvokeInst::Create(Ty
, Callee
, NormalBB
, UnwindBB
, Args
, BundleList
);
6307 II
->setCallingConv(CC
);
6308 II
->setAttributes(PAL
);
6309 ForwardRefAttrGroups
[II
] = FwdRefAttrGrps
;
6315 /// ::= 'resume' TypeAndValue
6316 bool LLParser::parseResume(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6317 Value
*Exn
; LocTy ExnLoc
;
6318 if (parseTypeAndValue(Exn
, ExnLoc
, PFS
))
6321 ResumeInst
*RI
= ResumeInst::Create(Exn
);
6326 bool LLParser::parseExceptionArgs(SmallVectorImpl
<Value
*> &Args
,
6327 PerFunctionState
&PFS
) {
6328 if (parseToken(lltok::lsquare
, "expected '[' in catchpad/cleanuppad"))
6331 while (Lex
.getKind() != lltok::rsquare
) {
6332 // If this isn't the first argument, we need a comma.
6333 if (!Args
.empty() &&
6334 parseToken(lltok::comma
, "expected ',' in argument list"))
6337 // parse the argument.
6339 Type
*ArgTy
= nullptr;
6340 if (parseType(ArgTy
, ArgLoc
))
6344 if (ArgTy
->isMetadataTy()) {
6345 if (parseMetadataAsValue(V
, PFS
))
6348 if (parseValue(ArgTy
, V
, PFS
))
6354 Lex
.Lex(); // Lex the ']'.
6359 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6360 bool LLParser::parseCleanupRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6361 Value
*CleanupPad
= nullptr;
6363 if (parseToken(lltok::kw_from
, "expected 'from' after cleanupret"))
6366 if (parseValue(Type::getTokenTy(Context
), CleanupPad
, PFS
))
6369 if (parseToken(lltok::kw_unwind
, "expected 'unwind' in cleanupret"))
6372 BasicBlock
*UnwindBB
= nullptr;
6373 if (Lex
.getKind() == lltok::kw_to
) {
6375 if (parseToken(lltok::kw_caller
, "expected 'caller' in cleanupret"))
6378 if (parseTypeAndBasicBlock(UnwindBB
, PFS
)) {
6383 Inst
= CleanupReturnInst::Create(CleanupPad
, UnwindBB
);
6388 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6389 bool LLParser::parseCatchRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6390 Value
*CatchPad
= nullptr;
6392 if (parseToken(lltok::kw_from
, "expected 'from' after catchret"))
6395 if (parseValue(Type::getTokenTy(Context
), CatchPad
, PFS
))
6399 if (parseToken(lltok::kw_to
, "expected 'to' in catchret") ||
6400 parseTypeAndBasicBlock(BB
, PFS
))
6403 Inst
= CatchReturnInst::Create(CatchPad
, BB
);
6407 /// parseCatchSwitch
6408 /// ::= 'catchswitch' within Parent
6409 bool LLParser::parseCatchSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6412 if (parseToken(lltok::kw_within
, "expected 'within' after catchswitch"))
6415 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6416 Lex
.getKind() != lltok::LocalVarID
)
6417 return tokError("expected scope value for catchswitch");
6419 if (parseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6422 if (parseToken(lltok::lsquare
, "expected '[' with catchswitch labels"))
6425 SmallVector
<BasicBlock
*, 32> Table
;
6428 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6430 Table
.push_back(DestBB
);
6431 } while (EatIfPresent(lltok::comma
));
6433 if (parseToken(lltok::rsquare
, "expected ']' after catchswitch labels"))
6436 if (parseToken(lltok::kw_unwind
, "expected 'unwind' after catchswitch scope"))
6439 BasicBlock
*UnwindBB
= nullptr;
6440 if (EatIfPresent(lltok::kw_to
)) {
6441 if (parseToken(lltok::kw_caller
, "expected 'caller' in catchswitch"))
6444 if (parseTypeAndBasicBlock(UnwindBB
, PFS
))
6449 CatchSwitchInst::Create(ParentPad
, UnwindBB
, Table
.size());
6450 for (BasicBlock
*DestBB
: Table
)
6451 CatchSwitch
->addHandler(DestBB
);
6457 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6458 bool LLParser::parseCatchPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6459 Value
*CatchSwitch
= nullptr;
6461 if (parseToken(lltok::kw_within
, "expected 'within' after catchpad"))
6464 if (Lex
.getKind() != lltok::LocalVar
&& Lex
.getKind() != lltok::LocalVarID
)
6465 return tokError("expected scope value for catchpad");
6467 if (parseValue(Type::getTokenTy(Context
), CatchSwitch
, PFS
))
6470 SmallVector
<Value
*, 8> Args
;
6471 if (parseExceptionArgs(Args
, PFS
))
6474 Inst
= CatchPadInst::Create(CatchSwitch
, Args
);
6479 /// ::= 'cleanuppad' within Parent ParamList
6480 bool LLParser::parseCleanupPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6481 Value
*ParentPad
= nullptr;
6483 if (parseToken(lltok::kw_within
, "expected 'within' after cleanuppad"))
6486 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6487 Lex
.getKind() != lltok::LocalVarID
)
6488 return tokError("expected scope value for cleanuppad");
6490 if (parseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6493 SmallVector
<Value
*, 8> Args
;
6494 if (parseExceptionArgs(Args
, PFS
))
6497 Inst
= CleanupPadInst::Create(ParentPad
, Args
);
6501 //===----------------------------------------------------------------------===//
6503 //===----------------------------------------------------------------------===//
6506 /// ::= UnaryOp TypeAndValue ',' Value
6508 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6509 /// operand is allowed.
6510 bool LLParser::parseUnaryOp(Instruction
*&Inst
, PerFunctionState
&PFS
,
6511 unsigned Opc
, bool IsFP
) {
6512 LocTy Loc
; Value
*LHS
;
6513 if (parseTypeAndValue(LHS
, Loc
, PFS
))
6516 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
6517 : LHS
->getType()->isIntOrIntVectorTy();
6520 return error(Loc
, "invalid operand type for instruction");
6522 Inst
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
6527 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6528 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6529 /// '[' LabelList ']'
6530 bool LLParser::parseCallBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6531 LocTy CallLoc
= Lex
.getLoc();
6532 AttrBuilder RetAttrs
, FnAttrs
;
6533 std::vector
<unsigned> FwdRefAttrGrps
;
6536 Type
*RetType
= nullptr;
6539 SmallVector
<ParamInfo
, 16> ArgList
;
6540 SmallVector
<OperandBundleDef
, 2> BundleList
;
6542 BasicBlock
*DefaultDest
;
6543 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
6544 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6545 parseValID(CalleeID
, &PFS
) || parseParameterList(ArgList
, PFS
) ||
6546 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6548 parseOptionalOperandBundles(BundleList
, PFS
) ||
6549 parseToken(lltok::kw_to
, "expected 'to' in callbr") ||
6550 parseTypeAndBasicBlock(DefaultDest
, PFS
) ||
6551 parseToken(lltok::lsquare
, "expected '[' in callbr"))
6554 // parse the destination list.
6555 SmallVector
<BasicBlock
*, 16> IndirectDests
;
6557 if (Lex
.getKind() != lltok::rsquare
) {
6559 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6561 IndirectDests
.push_back(DestBB
);
6563 while (EatIfPresent(lltok::comma
)) {
6564 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6566 IndirectDests
.push_back(DestBB
);
6570 if (parseToken(lltok::rsquare
, "expected ']' at end of block list"))
6573 // If RetType is a non-function pointer type, then this is the short syntax
6574 // for the call, which means that RetType is just the return type. Infer the
6575 // rest of the function argument types from the arguments that are present.
6576 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6578 // Pull out the types of all of the arguments...
6579 std::vector
<Type
*> ParamTypes
;
6580 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6581 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6583 if (!FunctionType::isValidReturnType(RetType
))
6584 return error(RetTypeLoc
, "Invalid result type for LLVM function");
6586 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6591 // Look up the callee.
6593 if (convertValIDToValue(PointerType::getUnqual(Ty
), CalleeID
, Callee
, &PFS
,
6597 // Set up the Attribute for the function.
6598 SmallVector
<Value
*, 8> Args
;
6599 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6601 // Loop through FunctionType's arguments and ensure they are specified
6602 // correctly. Also, gather any parameter attributes.
6603 FunctionType::param_iterator I
= Ty
->param_begin();
6604 FunctionType::param_iterator E
= Ty
->param_end();
6605 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6606 Type
*ExpectedTy
= nullptr;
6609 } else if (!Ty
->isVarArg()) {
6610 return error(ArgList
[i
].Loc
, "too many arguments specified");
6613 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6614 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6615 getTypeString(ExpectedTy
) + "'");
6616 Args
.push_back(ArgList
[i
].V
);
6617 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6621 return error(CallLoc
, "not enough parameters specified for call");
6623 if (FnAttrs
.hasAlignmentAttr())
6624 return error(CallLoc
, "callbr instructions may not have an alignment");
6626 // Finish off the Attribute and check them
6628 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6629 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6632 CallBrInst::Create(Ty
, Callee
, DefaultDest
, IndirectDests
, Args
,
6634 CBI
->setCallingConv(CC
);
6635 CBI
->setAttributes(PAL
);
6636 ForwardRefAttrGroups
[CBI
] = FwdRefAttrGrps
;
6641 //===----------------------------------------------------------------------===//
6642 // Binary Operators.
6643 //===----------------------------------------------------------------------===//
6646 /// ::= ArithmeticOps TypeAndValue ',' Value
6648 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6649 /// operand is allowed.
6650 bool LLParser::parseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
6651 unsigned Opc
, bool IsFP
) {
6652 LocTy Loc
; Value
*LHS
, *RHS
;
6653 if (parseTypeAndValue(LHS
, Loc
, PFS
) ||
6654 parseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
6655 parseValue(LHS
->getType(), RHS
, PFS
))
6658 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
6659 : LHS
->getType()->isIntOrIntVectorTy();
6662 return error(Loc
, "invalid operand type for instruction");
6664 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6669 /// ::= ArithmeticOps TypeAndValue ',' Value {
6670 bool LLParser::parseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
6672 LocTy Loc
; Value
*LHS
, *RHS
;
6673 if (parseTypeAndValue(LHS
, Loc
, PFS
) ||
6674 parseToken(lltok::comma
, "expected ',' in logical operation") ||
6675 parseValue(LHS
->getType(), RHS
, PFS
))
6678 if (!LHS
->getType()->isIntOrIntVectorTy())
6680 "instruction requires integer or integer vector operands");
6682 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6687 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6688 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6689 bool LLParser::parseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
6691 // parse the integer/fp comparison predicate.
6695 if (parseCmpPredicate(Pred
, Opc
) || parseTypeAndValue(LHS
, Loc
, PFS
) ||
6696 parseToken(lltok::comma
, "expected ',' after compare value") ||
6697 parseValue(LHS
->getType(), RHS
, PFS
))
6700 if (Opc
== Instruction::FCmp
) {
6701 if (!LHS
->getType()->isFPOrFPVectorTy())
6702 return error(Loc
, "fcmp requires floating point operands");
6703 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6705 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
6706 if (!LHS
->getType()->isIntOrIntVectorTy() &&
6707 !LHS
->getType()->isPtrOrPtrVectorTy())
6708 return error(Loc
, "icmp requires integer operands");
6709 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6714 //===----------------------------------------------------------------------===//
6715 // Other Instructions.
6716 //===----------------------------------------------------------------------===//
6719 /// ::= CastOpc TypeAndValue 'to' Type
6720 bool LLParser::parseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
6724 Type
*DestTy
= nullptr;
6725 if (parseTypeAndValue(Op
, Loc
, PFS
) ||
6726 parseToken(lltok::kw_to
, "expected 'to' after cast value") ||
6730 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
6731 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
6732 return error(Loc
, "invalid cast opcode for cast from '" +
6733 getTypeString(Op
->getType()) + "' to '" +
6734 getTypeString(DestTy
) + "'");
6736 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
6741 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6742 bool LLParser::parseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6744 Value
*Op0
, *Op1
, *Op2
;
6745 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
6746 parseToken(lltok::comma
, "expected ',' after select condition") ||
6747 parseTypeAndValue(Op1
, PFS
) ||
6748 parseToken(lltok::comma
, "expected ',' after select value") ||
6749 parseTypeAndValue(Op2
, PFS
))
6752 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
6753 return error(Loc
, Reason
);
6755 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
6760 /// ::= 'va_arg' TypeAndValue ',' Type
6761 bool LLParser::parseVAArg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6763 Type
*EltTy
= nullptr;
6765 if (parseTypeAndValue(Op
, PFS
) ||
6766 parseToken(lltok::comma
, "expected ',' after vaarg operand") ||
6767 parseType(EltTy
, TypeLoc
))
6770 if (!EltTy
->isFirstClassType())
6771 return error(TypeLoc
, "va_arg requires operand with first class type");
6773 Inst
= new VAArgInst(Op
, EltTy
);
6777 /// parseExtractElement
6778 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6779 bool LLParser::parseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6782 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
6783 parseToken(lltok::comma
, "expected ',' after extract value") ||
6784 parseTypeAndValue(Op1
, PFS
))
6787 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
6788 return error(Loc
, "invalid extractelement operands");
6790 Inst
= ExtractElementInst::Create(Op0
, Op1
);
6794 /// parseInsertElement
6795 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6796 bool LLParser::parseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6798 Value
*Op0
, *Op1
, *Op2
;
6799 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
6800 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
6801 parseTypeAndValue(Op1
, PFS
) ||
6802 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
6803 parseTypeAndValue(Op2
, PFS
))
6806 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
6807 return error(Loc
, "invalid insertelement operands");
6809 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
6813 /// parseShuffleVector
6814 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6815 bool LLParser::parseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6817 Value
*Op0
, *Op1
, *Op2
;
6818 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
6819 parseToken(lltok::comma
, "expected ',' after shuffle mask") ||
6820 parseTypeAndValue(Op1
, PFS
) ||
6821 parseToken(lltok::comma
, "expected ',' after shuffle value") ||
6822 parseTypeAndValue(Op2
, PFS
))
6825 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
6826 return error(Loc
, "invalid shufflevector operands");
6828 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
6833 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6834 int LLParser::parsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6835 Type
*Ty
= nullptr; LocTy TypeLoc
;
6838 if (parseType(Ty
, TypeLoc
) ||
6839 parseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6840 parseValue(Ty
, Op0
, PFS
) ||
6841 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
6842 parseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6843 parseToken(lltok::rsquare
, "expected ']' in phi value list"))
6846 bool AteExtraComma
= false;
6847 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
6850 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
6852 if (!EatIfPresent(lltok::comma
))
6855 if (Lex
.getKind() == lltok::MetadataVar
) {
6856 AteExtraComma
= true;
6860 if (parseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6861 parseValue(Ty
, Op0
, PFS
) ||
6862 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
6863 parseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6864 parseToken(lltok::rsquare
, "expected ']' in phi value list"))
6868 if (!Ty
->isFirstClassType())
6869 return error(TypeLoc
, "phi node must have first class type");
6871 PHINode
*PN
= PHINode::Create(Ty
, PHIVals
.size());
6872 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
6873 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
6875 return AteExtraComma
? InstExtraComma
: InstNormal
;
6879 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6881 /// ::= 'catch' TypeAndValue
6883 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6884 bool LLParser::parseLandingPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6885 Type
*Ty
= nullptr; LocTy TyLoc
;
6887 if (parseType(Ty
, TyLoc
))
6890 std::unique_ptr
<LandingPadInst
> LP(LandingPadInst::Create(Ty
, 0));
6891 LP
->setCleanup(EatIfPresent(lltok::kw_cleanup
));
6893 while (Lex
.getKind() == lltok::kw_catch
|| Lex
.getKind() == lltok::kw_filter
){
6894 LandingPadInst::ClauseType CT
;
6895 if (EatIfPresent(lltok::kw_catch
))
6896 CT
= LandingPadInst::Catch
;
6897 else if (EatIfPresent(lltok::kw_filter
))
6898 CT
= LandingPadInst::Filter
;
6900 return tokError("expected 'catch' or 'filter' clause type");
6904 if (parseTypeAndValue(V
, VLoc
, PFS
))
6907 // A 'catch' type expects a non-array constant. A filter clause expects an
6909 if (CT
== LandingPadInst::Catch
) {
6910 if (isa
<ArrayType
>(V
->getType()))
6911 error(VLoc
, "'catch' clause has an invalid type");
6913 if (!isa
<ArrayType
>(V
->getType()))
6914 error(VLoc
, "'filter' clause has an invalid type");
6917 Constant
*CV
= dyn_cast
<Constant
>(V
);
6919 return error(VLoc
, "clause argument must be a constant");
6923 Inst
= LP
.release();
6928 /// ::= 'freeze' Type Value
6929 bool LLParser::parseFreeze(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6932 if (parseTypeAndValue(Op
, Loc
, PFS
))
6935 Inst
= new FreezeInst(Op
);
6940 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6941 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6942 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6943 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6944 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6945 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6946 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6947 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6948 bool LLParser::parseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
6949 CallInst::TailCallKind TCK
) {
6950 AttrBuilder RetAttrs
, FnAttrs
;
6951 std::vector
<unsigned> FwdRefAttrGrps
;
6953 unsigned CallAddrSpace
;
6955 Type
*RetType
= nullptr;
6958 SmallVector
<ParamInfo
, 16> ArgList
;
6959 SmallVector
<OperandBundleDef
, 2> BundleList
;
6960 LocTy CallLoc
= Lex
.getLoc();
6962 if (TCK
!= CallInst::TCK_None
&&
6963 parseToken(lltok::kw_call
,
6964 "expected 'tail call', 'musttail call', or 'notail call'"))
6967 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6969 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
6970 parseOptionalProgramAddrSpace(CallAddrSpace
) ||
6971 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6972 parseValID(CalleeID
, &PFS
) ||
6973 parseParameterList(ArgList
, PFS
, TCK
== CallInst::TCK_MustTail
,
6974 PFS
.getFunction().isVarArg()) ||
6975 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false, BuiltinLoc
) ||
6976 parseOptionalOperandBundles(BundleList
, PFS
))
6979 // If RetType is a non-function pointer type, then this is the short syntax
6980 // for the call, which means that RetType is just the return type. Infer the
6981 // rest of the function argument types from the arguments that are present.
6982 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6984 // Pull out the types of all of the arguments...
6985 std::vector
<Type
*> ParamTypes
;
6986 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6987 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6989 if (!FunctionType::isValidReturnType(RetType
))
6990 return error(RetTypeLoc
, "Invalid result type for LLVM function");
6992 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6997 // Look up the callee.
6999 if (convertValIDToValue(PointerType::get(Ty
, CallAddrSpace
), CalleeID
, Callee
,
7000 &PFS
, /*IsCall=*/true))
7003 // Set up the Attribute for the function.
7004 SmallVector
<AttributeSet
, 8> Attrs
;
7006 SmallVector
<Value
*, 8> Args
;
7008 // Loop through FunctionType's arguments and ensure they are specified
7009 // correctly. Also, gather any parameter attributes.
7010 FunctionType::param_iterator I
= Ty
->param_begin();
7011 FunctionType::param_iterator E
= Ty
->param_end();
7012 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
7013 Type
*ExpectedTy
= nullptr;
7016 } else if (!Ty
->isVarArg()) {
7017 return error(ArgList
[i
].Loc
, "too many arguments specified");
7020 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
7021 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
7022 getTypeString(ExpectedTy
) + "'");
7023 Args
.push_back(ArgList
[i
].V
);
7024 Attrs
.push_back(ArgList
[i
].Attrs
);
7028 return error(CallLoc
, "not enough parameters specified for call");
7030 if (FnAttrs
.hasAlignmentAttr())
7031 return error(CallLoc
, "call instructions may not have an alignment");
7033 // Finish off the Attribute and check them
7035 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
7036 AttributeSet::get(Context
, RetAttrs
), Attrs
);
7038 CallInst
*CI
= CallInst::Create(Ty
, Callee
, Args
, BundleList
);
7039 CI
->setTailCallKind(TCK
);
7040 CI
->setCallingConv(CC
);
7042 if (!isa
<FPMathOperator
>(CI
)) {
7044 return error(CallLoc
, "fast-math-flags specified for call without "
7045 "floating-point scalar or vector return type");
7047 CI
->setFastMathFlags(FMF
);
7049 CI
->setAttributes(PAL
);
7050 ForwardRefAttrGroups
[CI
] = FwdRefAttrGrps
;
7055 //===----------------------------------------------------------------------===//
7056 // Memory Instructions.
7057 //===----------------------------------------------------------------------===//
7060 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7061 /// (',' 'align' i32)? (',', 'addrspace(n))?
7062 int LLParser::parseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7063 Value
*Size
= nullptr;
7064 LocTy SizeLoc
, TyLoc
, ASLoc
;
7065 MaybeAlign Alignment
;
7066 unsigned AddrSpace
= 0;
7069 bool IsInAlloca
= EatIfPresent(lltok::kw_inalloca
);
7070 bool IsSwiftError
= EatIfPresent(lltok::kw_swifterror
);
7072 if (parseType(Ty
, TyLoc
))
7075 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
7076 return error(TyLoc
, "invalid type for alloca");
7078 bool AteExtraComma
= false;
7079 if (EatIfPresent(lltok::comma
)) {
7080 if (Lex
.getKind() == lltok::kw_align
) {
7081 if (parseOptionalAlignment(Alignment
))
7083 if (parseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
7085 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
7086 ASLoc
= Lex
.getLoc();
7087 if (parseOptionalAddrSpace(AddrSpace
))
7089 } else if (Lex
.getKind() == lltok::MetadataVar
) {
7090 AteExtraComma
= true;
7092 if (parseTypeAndValue(Size
, SizeLoc
, PFS
))
7094 if (EatIfPresent(lltok::comma
)) {
7095 if (Lex
.getKind() == lltok::kw_align
) {
7096 if (parseOptionalAlignment(Alignment
))
7098 if (parseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
7100 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
7101 ASLoc
= Lex
.getLoc();
7102 if (parseOptionalAddrSpace(AddrSpace
))
7104 } else if (Lex
.getKind() == lltok::MetadataVar
) {
7105 AteExtraComma
= true;
7111 if (Size
&& !Size
->getType()->isIntegerTy())
7112 return error(SizeLoc
, "element count must have integer type");
7114 SmallPtrSet
<Type
*, 4> Visited
;
7115 if (!Alignment
&& !Ty
->isSized(&Visited
))
7116 return error(TyLoc
, "Cannot allocate unsized type");
7118 Alignment
= M
->getDataLayout().getPrefTypeAlign(Ty
);
7119 AllocaInst
*AI
= new AllocaInst(Ty
, AddrSpace
, Size
, *Alignment
);
7120 AI
->setUsedWithInAlloca(IsInAlloca
);
7121 AI
->setSwiftError(IsSwiftError
);
7123 return AteExtraComma
? InstExtraComma
: InstNormal
;
7127 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7128 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7129 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7130 int LLParser::parseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7131 Value
*Val
; LocTy Loc
;
7132 MaybeAlign Alignment
;
7133 bool AteExtraComma
= false;
7134 bool isAtomic
= false;
7135 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7136 SyncScope::ID SSID
= SyncScope::System
;
7138 if (Lex
.getKind() == lltok::kw_atomic
) {
7143 bool isVolatile
= false;
7144 if (Lex
.getKind() == lltok::kw_volatile
) {
7150 LocTy ExplicitTypeLoc
= Lex
.getLoc();
7151 if (parseType(Ty
) ||
7152 parseToken(lltok::comma
, "expected comma after load's type") ||
7153 parseTypeAndValue(Val
, Loc
, PFS
) ||
7154 parseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
7155 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7158 if (!Val
->getType()->isPointerTy() || !Ty
->isFirstClassType())
7159 return error(Loc
, "load operand must be a pointer to a first class type");
7160 if (isAtomic
&& !Alignment
)
7161 return error(Loc
, "atomic load must have explicit non-zero alignment");
7162 if (Ordering
== AtomicOrdering::Release
||
7163 Ordering
== AtomicOrdering::AcquireRelease
)
7164 return error(Loc
, "atomic load cannot use Release ordering");
7166 if (!cast
<PointerType
>(Val
->getType())->isOpaqueOrPointeeTypeMatches(Ty
)) {
7169 typeComparisonErrorMessage(
7170 "explicit pointee type doesn't match operand's pointee type", Ty
,
7171 cast
<PointerType
>(Val
->getType())->getElementType()));
7173 SmallPtrSet
<Type
*, 4> Visited
;
7174 if (!Alignment
&& !Ty
->isSized(&Visited
))
7175 return error(ExplicitTypeLoc
, "loading unsized types is not allowed");
7177 Alignment
= M
->getDataLayout().getABITypeAlign(Ty
);
7178 Inst
= new LoadInst(Ty
, Val
, "", isVolatile
, *Alignment
, Ordering
, SSID
);
7179 return AteExtraComma
? InstExtraComma
: InstNormal
;
7184 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7185 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7186 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7187 int LLParser::parseStore(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7188 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
7189 MaybeAlign Alignment
;
7190 bool AteExtraComma
= false;
7191 bool isAtomic
= false;
7192 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7193 SyncScope::ID SSID
= SyncScope::System
;
7195 if (Lex
.getKind() == lltok::kw_atomic
) {
7200 bool isVolatile
= false;
7201 if (Lex
.getKind() == lltok::kw_volatile
) {
7206 if (parseTypeAndValue(Val
, Loc
, PFS
) ||
7207 parseToken(lltok::comma
, "expected ',' after store operand") ||
7208 parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7209 parseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
7210 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7213 if (!Ptr
->getType()->isPointerTy())
7214 return error(PtrLoc
, "store operand must be a pointer");
7215 if (!Val
->getType()->isFirstClassType())
7216 return error(Loc
, "store operand must be a first class value");
7217 if (!cast
<PointerType
>(Ptr
->getType())
7218 ->isOpaqueOrPointeeTypeMatches(Val
->getType()))
7219 return error(Loc
, "stored value and pointer type do not match");
7220 if (isAtomic
&& !Alignment
)
7221 return error(Loc
, "atomic store must have explicit non-zero alignment");
7222 if (Ordering
== AtomicOrdering::Acquire
||
7223 Ordering
== AtomicOrdering::AcquireRelease
)
7224 return error(Loc
, "atomic store cannot use Acquire ordering");
7225 SmallPtrSet
<Type
*, 4> Visited
;
7226 if (!Alignment
&& !Val
->getType()->isSized(&Visited
))
7227 return error(Loc
, "storing unsized types is not allowed");
7229 Alignment
= M
->getDataLayout().getABITypeAlign(Val
->getType());
7231 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, *Alignment
, Ordering
, SSID
);
7232 return AteExtraComma
? InstExtraComma
: InstNormal
;
7236 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7237 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7239 int LLParser::parseCmpXchg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7240 Value
*Ptr
, *Cmp
, *New
; LocTy PtrLoc
, CmpLoc
, NewLoc
;
7241 bool AteExtraComma
= false;
7242 AtomicOrdering SuccessOrdering
= AtomicOrdering::NotAtomic
;
7243 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
;
7244 SyncScope::ID SSID
= SyncScope::System
;
7245 bool isVolatile
= false;
7246 bool isWeak
= false;
7247 MaybeAlign Alignment
;
7249 if (EatIfPresent(lltok::kw_weak
))
7252 if (EatIfPresent(lltok::kw_volatile
))
7255 if (parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7256 parseToken(lltok::comma
, "expected ',' after cmpxchg address") ||
7257 parseTypeAndValue(Cmp
, CmpLoc
, PFS
) ||
7258 parseToken(lltok::comma
, "expected ',' after cmpxchg cmp operand") ||
7259 parseTypeAndValue(New
, NewLoc
, PFS
) ||
7260 parseScopeAndOrdering(true /*Always atomic*/, SSID
, SuccessOrdering
) ||
7261 parseOrdering(FailureOrdering
) ||
7262 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7265 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering
))
7266 return tokError("invalid cmpxchg success ordering");
7267 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering
))
7268 return tokError("invalid cmpxchg failure ordering");
7269 if (!Ptr
->getType()->isPointerTy())
7270 return error(PtrLoc
, "cmpxchg operand must be a pointer");
7271 if (!cast
<PointerType
>(Ptr
->getType())
7272 ->isOpaqueOrPointeeTypeMatches(Cmp
->getType()))
7273 return error(CmpLoc
, "compare value and pointer type do not match");
7274 if (!cast
<PointerType
>(Ptr
->getType())
7275 ->isOpaqueOrPointeeTypeMatches(New
->getType()))
7276 return error(NewLoc
, "new value and pointer type do not match");
7277 if (Cmp
->getType() != New
->getType())
7278 return error(NewLoc
, "compare value and new value type do not match");
7279 if (!New
->getType()->isFirstClassType())
7280 return error(NewLoc
, "cmpxchg operand must be a first class value");
7282 const Align
DefaultAlignment(
7283 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7286 AtomicCmpXchgInst
*CXI
= new AtomicCmpXchgInst(
7287 Ptr
, Cmp
, New
, Alignment
.getValueOr(DefaultAlignment
), SuccessOrdering
,
7288 FailureOrdering
, SSID
);
7289 CXI
->setVolatile(isVolatile
);
7290 CXI
->setWeak(isWeak
);
7293 return AteExtraComma
? InstExtraComma
: InstNormal
;
7297 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7298 /// 'singlethread'? AtomicOrdering
7299 int LLParser::parseAtomicRMW(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7300 Value
*Ptr
, *Val
; LocTy PtrLoc
, ValLoc
;
7301 bool AteExtraComma
= false;
7302 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7303 SyncScope::ID SSID
= SyncScope::System
;
7304 bool isVolatile
= false;
7306 AtomicRMWInst::BinOp Operation
;
7307 MaybeAlign Alignment
;
7309 if (EatIfPresent(lltok::kw_volatile
))
7312 switch (Lex
.getKind()) {
7314 return tokError("expected binary operation in atomicrmw");
7315 case lltok::kw_xchg
: Operation
= AtomicRMWInst::Xchg
; break;
7316 case lltok::kw_add
: Operation
= AtomicRMWInst::Add
; break;
7317 case lltok::kw_sub
: Operation
= AtomicRMWInst::Sub
; break;
7318 case lltok::kw_and
: Operation
= AtomicRMWInst::And
; break;
7319 case lltok::kw_nand
: Operation
= AtomicRMWInst::Nand
; break;
7320 case lltok::kw_or
: Operation
= AtomicRMWInst::Or
; break;
7321 case lltok::kw_xor
: Operation
= AtomicRMWInst::Xor
; break;
7322 case lltok::kw_max
: Operation
= AtomicRMWInst::Max
; break;
7323 case lltok::kw_min
: Operation
= AtomicRMWInst::Min
; break;
7324 case lltok::kw_umax
: Operation
= AtomicRMWInst::UMax
; break;
7325 case lltok::kw_umin
: Operation
= AtomicRMWInst::UMin
; break;
7326 case lltok::kw_fadd
:
7327 Operation
= AtomicRMWInst::FAdd
;
7330 case lltok::kw_fsub
:
7331 Operation
= AtomicRMWInst::FSub
;
7335 Lex
.Lex(); // Eat the operation.
7337 if (parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7338 parseToken(lltok::comma
, "expected ',' after atomicrmw address") ||
7339 parseTypeAndValue(Val
, ValLoc
, PFS
) ||
7340 parseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
) ||
7341 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7344 if (Ordering
== AtomicOrdering::Unordered
)
7345 return tokError("atomicrmw cannot be unordered");
7346 if (!Ptr
->getType()->isPointerTy())
7347 return error(PtrLoc
, "atomicrmw operand must be a pointer");
7348 if (!cast
<PointerType
>(Ptr
->getType())
7349 ->isOpaqueOrPointeeTypeMatches(Val
->getType()))
7350 return error(ValLoc
, "atomicrmw value and pointer type do not match");
7352 if (Operation
== AtomicRMWInst::Xchg
) {
7353 if (!Val
->getType()->isIntegerTy() &&
7354 !Val
->getType()->isFloatingPointTy()) {
7355 return error(ValLoc
,
7356 "atomicrmw " + AtomicRMWInst::getOperationName(Operation
) +
7357 " operand must be an integer or floating point type");
7360 if (!Val
->getType()->isFloatingPointTy()) {
7361 return error(ValLoc
, "atomicrmw " +
7362 AtomicRMWInst::getOperationName(Operation
) +
7363 " operand must be a floating point type");
7366 if (!Val
->getType()->isIntegerTy()) {
7367 return error(ValLoc
, "atomicrmw " +
7368 AtomicRMWInst::getOperationName(Operation
) +
7369 " operand must be an integer");
7373 unsigned Size
= Val
->getType()->getPrimitiveSizeInBits();
7374 if (Size
< 8 || (Size
& (Size
- 1)))
7375 return error(ValLoc
, "atomicrmw operand must be power-of-two byte-sized"
7377 const Align
DefaultAlignment(
7378 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7380 AtomicRMWInst
*RMWI
=
7381 new AtomicRMWInst(Operation
, Ptr
, Val
,
7382 Alignment
.getValueOr(DefaultAlignment
), Ordering
, SSID
);
7383 RMWI
->setVolatile(isVolatile
);
7385 return AteExtraComma
? InstExtraComma
: InstNormal
;
7389 /// ::= 'fence' 'singlethread'? AtomicOrdering
7390 int LLParser::parseFence(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7391 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7392 SyncScope::ID SSID
= SyncScope::System
;
7393 if (parseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7396 if (Ordering
== AtomicOrdering::Unordered
)
7397 return tokError("fence cannot be unordered");
7398 if (Ordering
== AtomicOrdering::Monotonic
)
7399 return tokError("fence cannot be monotonic");
7401 Inst
= new FenceInst(Context
, Ordering
, SSID
);
7405 /// parseGetElementPtr
7406 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7407 int LLParser::parseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7408 Value
*Ptr
= nullptr;
7409 Value
*Val
= nullptr;
7412 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
7415 LocTy ExplicitTypeLoc
= Lex
.getLoc();
7416 if (parseType(Ty
) ||
7417 parseToken(lltok::comma
, "expected comma after getelementptr's type") ||
7418 parseTypeAndValue(Ptr
, Loc
, PFS
))
7421 Type
*BaseType
= Ptr
->getType();
7422 PointerType
*BasePointerType
= dyn_cast
<PointerType
>(BaseType
->getScalarType());
7423 if (!BasePointerType
)
7424 return error(Loc
, "base of getelementptr must be a pointer");
7426 if (!BasePointerType
->isOpaqueOrPointeeTypeMatches(Ty
)) {
7429 typeComparisonErrorMessage(
7430 "explicit pointee type doesn't match operand's pointee type", Ty
,
7431 BasePointerType
->getElementType()));
7434 SmallVector
<Value
*, 16> Indices
;
7435 bool AteExtraComma
= false;
7436 // GEP returns a vector of pointers if at least one of parameters is a vector.
7437 // All vector parameters should have the same vector width.
7438 ElementCount GEPWidth
= BaseType
->isVectorTy()
7439 ? cast
<VectorType
>(BaseType
)->getElementCount()
7440 : ElementCount::getFixed(0);
7442 while (EatIfPresent(lltok::comma
)) {
7443 if (Lex
.getKind() == lltok::MetadataVar
) {
7444 AteExtraComma
= true;
7447 if (parseTypeAndValue(Val
, EltLoc
, PFS
))
7449 if (!Val
->getType()->isIntOrIntVectorTy())
7450 return error(EltLoc
, "getelementptr index must be an integer");
7452 if (auto *ValVTy
= dyn_cast
<VectorType
>(Val
->getType())) {
7453 ElementCount ValNumEl
= ValVTy
->getElementCount();
7454 if (GEPWidth
!= ElementCount::getFixed(0) && GEPWidth
!= ValNumEl
)
7457 "getelementptr vector index has a wrong number of elements");
7458 GEPWidth
= ValNumEl
;
7460 Indices
.push_back(Val
);
7463 SmallPtrSet
<Type
*, 4> Visited
;
7464 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
7465 return error(Loc
, "base element of getelementptr must be sized");
7467 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
7468 return error(Loc
, "invalid getelementptr indices");
7469 Inst
= GetElementPtrInst::Create(Ty
, Ptr
, Indices
);
7471 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
7472 return AteExtraComma
? InstExtraComma
: InstNormal
;
7475 /// parseExtractValue
7476 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7477 int LLParser::parseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7478 Value
*Val
; LocTy Loc
;
7479 SmallVector
<unsigned, 4> Indices
;
7481 if (parseTypeAndValue(Val
, Loc
, PFS
) ||
7482 parseIndexList(Indices
, AteExtraComma
))
7485 if (!Val
->getType()->isAggregateType())
7486 return error(Loc
, "extractvalue operand must be aggregate type");
7488 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
7489 return error(Loc
, "invalid indices for extractvalue");
7490 Inst
= ExtractValueInst::Create(Val
, Indices
);
7491 return AteExtraComma
? InstExtraComma
: InstNormal
;
7494 /// parseInsertValue
7495 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7496 int LLParser::parseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7497 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
7498 SmallVector
<unsigned, 4> Indices
;
7500 if (parseTypeAndValue(Val0
, Loc0
, PFS
) ||
7501 parseToken(lltok::comma
, "expected comma after insertvalue operand") ||
7502 parseTypeAndValue(Val1
, Loc1
, PFS
) ||
7503 parseIndexList(Indices
, AteExtraComma
))
7506 if (!Val0
->getType()->isAggregateType())
7507 return error(Loc0
, "insertvalue operand must be aggregate type");
7509 Type
*IndexedType
= ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
7511 return error(Loc0
, "invalid indices for insertvalue");
7512 if (IndexedType
!= Val1
->getType())
7513 return error(Loc1
, "insertvalue operand and field disagree in type: '" +
7514 getTypeString(Val1
->getType()) + "' instead of '" +
7515 getTypeString(IndexedType
) + "'");
7516 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
);
7517 return AteExtraComma
? InstExtraComma
: InstNormal
;
7520 //===----------------------------------------------------------------------===//
7521 // Embedded metadata.
7522 //===----------------------------------------------------------------------===//
7524 /// parseMDNodeVector
7525 /// ::= { Element (',' Element)* }
7527 /// ::= 'null' | TypeAndValue
7528 bool LLParser::parseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
7529 if (parseToken(lltok::lbrace
, "expected '{' here"))
7532 // Check for an empty list.
7533 if (EatIfPresent(lltok::rbrace
))
7537 // Null is a special case since it is typeless.
7538 if (EatIfPresent(lltok::kw_null
)) {
7539 Elts
.push_back(nullptr);
7544 if (parseMetadata(MD
, nullptr))
7547 } while (EatIfPresent(lltok::comma
));
7549 return parseToken(lltok::rbrace
, "expected end of metadata node");
7552 //===----------------------------------------------------------------------===//
7553 // Use-list order directives.
7554 //===----------------------------------------------------------------------===//
7555 bool LLParser::sortUseListOrder(Value
*V
, ArrayRef
<unsigned> Indexes
,
7558 return error(Loc
, "value has no uses");
7560 unsigned NumUses
= 0;
7561 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
7562 for (const Use
&U
: V
->uses()) {
7563 if (++NumUses
> Indexes
.size())
7565 Order
[&U
] = Indexes
[NumUses
- 1];
7568 return error(Loc
, "value only has one use");
7569 if (Order
.size() != Indexes
.size() || NumUses
> Indexes
.size())
7571 "wrong number of indexes, expected " + Twine(V
->getNumUses()));
7573 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
7574 return Order
.lookup(&L
) < Order
.lookup(&R
);
7579 /// parseUseListOrderIndexes
7580 /// ::= '{' uint32 (',' uint32)+ '}'
7581 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl
<unsigned> &Indexes
) {
7582 SMLoc Loc
= Lex
.getLoc();
7583 if (parseToken(lltok::lbrace
, "expected '{' here"))
7585 if (Lex
.getKind() == lltok::rbrace
)
7586 return Lex
.Error("expected non-empty list of uselistorder indexes");
7588 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7589 // indexes should be distinct numbers in the range [0, size-1], and should
7591 unsigned Offset
= 0;
7593 bool IsOrdered
= true;
7594 assert(Indexes
.empty() && "Expected empty order vector");
7597 if (parseUInt32(Index
))
7600 // Update consistency checks.
7601 Offset
+= Index
- Indexes
.size();
7602 Max
= std::max(Max
, Index
);
7603 IsOrdered
&= Index
== Indexes
.size();
7605 Indexes
.push_back(Index
);
7606 } while (EatIfPresent(lltok::comma
));
7608 if (parseToken(lltok::rbrace
, "expected '}' here"))
7611 if (Indexes
.size() < 2)
7612 return error(Loc
, "expected >= 2 uselistorder indexes");
7613 if (Offset
!= 0 || Max
>= Indexes
.size())
7615 "expected distinct uselistorder indexes in range [0, size)");
7617 return error(Loc
, "expected uselistorder indexes to change the order");
7622 /// parseUseListOrder
7623 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7624 bool LLParser::parseUseListOrder(PerFunctionState
*PFS
) {
7625 SMLoc Loc
= Lex
.getLoc();
7626 if (parseToken(lltok::kw_uselistorder
, "expected uselistorder directive"))
7630 SmallVector
<unsigned, 16> Indexes
;
7631 if (parseTypeAndValue(V
, PFS
) ||
7632 parseToken(lltok::comma
, "expected comma in uselistorder directive") ||
7633 parseUseListOrderIndexes(Indexes
))
7636 return sortUseListOrder(V
, Indexes
, Loc
);
7639 /// parseUseListOrderBB
7640 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7641 bool LLParser::parseUseListOrderBB() {
7642 assert(Lex
.getKind() == lltok::kw_uselistorder_bb
);
7643 SMLoc Loc
= Lex
.getLoc();
7647 SmallVector
<unsigned, 16> Indexes
;
7648 if (parseValID(Fn
, /*PFS=*/nullptr) ||
7649 parseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7650 parseValID(Label
, /*PFS=*/nullptr) ||
7651 parseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7652 parseUseListOrderIndexes(Indexes
))
7655 // Check the function.
7657 if (Fn
.Kind
== ValID::t_GlobalName
)
7658 GV
= M
->getNamedValue(Fn
.StrVal
);
7659 else if (Fn
.Kind
== ValID::t_GlobalID
)
7660 GV
= Fn
.UIntVal
< NumberedVals
.size() ? NumberedVals
[Fn
.UIntVal
] : nullptr;
7662 return error(Fn
.Loc
, "expected function name in uselistorder_bb");
7664 return error(Fn
.Loc
,
7665 "invalid function forward reference in uselistorder_bb");
7666 auto *F
= dyn_cast
<Function
>(GV
);
7668 return error(Fn
.Loc
, "expected function name in uselistorder_bb");
7669 if (F
->isDeclaration())
7670 return error(Fn
.Loc
, "invalid declaration in uselistorder_bb");
7672 // Check the basic block.
7673 if (Label
.Kind
== ValID::t_LocalID
)
7674 return error(Label
.Loc
, "invalid numeric label in uselistorder_bb");
7675 if (Label
.Kind
!= ValID::t_LocalName
)
7676 return error(Label
.Loc
, "expected basic block name in uselistorder_bb");
7677 Value
*V
= F
->getValueSymbolTable()->lookup(Label
.StrVal
);
7679 return error(Label
.Loc
, "invalid basic block in uselistorder_bb");
7680 if (!isa
<BasicBlock
>(V
))
7681 return error(Label
.Loc
, "expected basic block in uselistorder_bb");
7683 return sortUseListOrder(V
, Indexes
, Loc
);
7687 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7688 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7689 bool LLParser::parseModuleEntry(unsigned ID
) {
7690 assert(Lex
.getKind() == lltok::kw_module
);
7694 if (parseToken(lltok::colon
, "expected ':' here") ||
7695 parseToken(lltok::lparen
, "expected '(' here") ||
7696 parseToken(lltok::kw_path
, "expected 'path' here") ||
7697 parseToken(lltok::colon
, "expected ':' here") ||
7698 parseStringConstant(Path
) ||
7699 parseToken(lltok::comma
, "expected ',' here") ||
7700 parseToken(lltok::kw_hash
, "expected 'hash' here") ||
7701 parseToken(lltok::colon
, "expected ':' here") ||
7702 parseToken(lltok::lparen
, "expected '(' here"))
7706 if (parseUInt32(Hash
[0]) || parseToken(lltok::comma
, "expected ',' here") ||
7707 parseUInt32(Hash
[1]) || parseToken(lltok::comma
, "expected ',' here") ||
7708 parseUInt32(Hash
[2]) || parseToken(lltok::comma
, "expected ',' here") ||
7709 parseUInt32(Hash
[3]) || parseToken(lltok::comma
, "expected ',' here") ||
7710 parseUInt32(Hash
[4]))
7713 if (parseToken(lltok::rparen
, "expected ')' here") ||
7714 parseToken(lltok::rparen
, "expected ')' here"))
7717 auto ModuleEntry
= Index
->addModule(Path
, ID
, Hash
);
7718 ModuleIdMap
[ID
] = ModuleEntry
->first();
7724 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7725 bool LLParser::parseTypeIdEntry(unsigned ID
) {
7726 assert(Lex
.getKind() == lltok::kw_typeid
);
7730 if (parseToken(lltok::colon
, "expected ':' here") ||
7731 parseToken(lltok::lparen
, "expected '(' here") ||
7732 parseToken(lltok::kw_name
, "expected 'name' here") ||
7733 parseToken(lltok::colon
, "expected ':' here") ||
7734 parseStringConstant(Name
))
7737 TypeIdSummary
&TIS
= Index
->getOrInsertTypeIdSummary(Name
);
7738 if (parseToken(lltok::comma
, "expected ',' here") ||
7739 parseTypeIdSummary(TIS
) || parseToken(lltok::rparen
, "expected ')' here"))
7742 // Check if this ID was forward referenced, and if so, update the
7743 // corresponding GUIDs.
7744 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
7745 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
7746 for (auto TIDRef
: FwdRefTIDs
->second
) {
7747 assert(!*TIDRef
.first
&&
7748 "Forward referenced type id GUID expected to be 0");
7749 *TIDRef
.first
= GlobalValue::getGUID(Name
);
7751 ForwardRefTypeIds
.erase(FwdRefTIDs
);
7758 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7759 bool LLParser::parseTypeIdSummary(TypeIdSummary
&TIS
) {
7760 if (parseToken(lltok::kw_summary
, "expected 'summary' here") ||
7761 parseToken(lltok::colon
, "expected ':' here") ||
7762 parseToken(lltok::lparen
, "expected '(' here") ||
7763 parseTypeTestResolution(TIS
.TTRes
))
7766 if (EatIfPresent(lltok::comma
)) {
7767 // Expect optional wpdResolutions field
7768 if (parseOptionalWpdResolutions(TIS
.WPDRes
))
7772 if (parseToken(lltok::rparen
, "expected ')' here"))
7778 static ValueInfo EmptyVI
=
7779 ValueInfo(false, (GlobalValueSummaryMapTy::value_type
*)-8);
7781 /// TypeIdCompatibleVtableEntry
7782 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7783 /// TypeIdCompatibleVtableInfo
7785 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID
) {
7786 assert(Lex
.getKind() == lltok::kw_typeidCompatibleVTable
);
7790 if (parseToken(lltok::colon
, "expected ':' here") ||
7791 parseToken(lltok::lparen
, "expected '(' here") ||
7792 parseToken(lltok::kw_name
, "expected 'name' here") ||
7793 parseToken(lltok::colon
, "expected ':' here") ||
7794 parseStringConstant(Name
))
7797 TypeIdCompatibleVtableInfo
&TI
=
7798 Index
->getOrInsertTypeIdCompatibleVtableSummary(Name
);
7799 if (parseToken(lltok::comma
, "expected ',' here") ||
7800 parseToken(lltok::kw_summary
, "expected 'summary' here") ||
7801 parseToken(lltok::colon
, "expected ':' here") ||
7802 parseToken(lltok::lparen
, "expected '(' here"))
7805 IdToIndexMapType IdToIndexMap
;
7806 // parse each call edge
7809 if (parseToken(lltok::lparen
, "expected '(' here") ||
7810 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
7811 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(Offset
) ||
7812 parseToken(lltok::comma
, "expected ',' here"))
7815 LocTy Loc
= Lex
.getLoc();
7818 if (parseGVReference(VI
, GVId
))
7821 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7822 // forward reference. We will save the location of the ValueInfo needing an
7823 // update, but can only do so once the std::vector is finalized.
7825 IdToIndexMap
[GVId
].push_back(std::make_pair(TI
.size(), Loc
));
7826 TI
.push_back({Offset
, VI
});
7828 if (parseToken(lltok::rparen
, "expected ')' in call"))
7830 } while (EatIfPresent(lltok::comma
));
7832 // Now that the TI vector is finalized, it is safe to save the locations
7833 // of any forward GV references that need updating later.
7834 for (auto I
: IdToIndexMap
) {
7835 auto &Infos
= ForwardRefValueInfos
[I
.first
];
7836 for (auto P
: I
.second
) {
7837 assert(TI
[P
.first
].VTableVI
== EmptyVI
&&
7838 "Forward referenced ValueInfo expected to be empty");
7839 Infos
.emplace_back(&TI
[P
.first
].VTableVI
, P
.second
);
7843 if (parseToken(lltok::rparen
, "expected ')' here") ||
7844 parseToken(lltok::rparen
, "expected ')' here"))
7847 // Check if this ID was forward referenced, and if so, update the
7848 // corresponding GUIDs.
7849 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
7850 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
7851 for (auto TIDRef
: FwdRefTIDs
->second
) {
7852 assert(!*TIDRef
.first
&&
7853 "Forward referenced type id GUID expected to be 0");
7854 *TIDRef
.first
= GlobalValue::getGUID(Name
);
7856 ForwardRefTypeIds
.erase(FwdRefTIDs
);
7862 /// TypeTestResolution
7863 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7864 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7865 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7866 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7867 /// [',' 'inlinesBits' ':' UInt64]? ')'
7868 bool LLParser::parseTypeTestResolution(TypeTestResolution
&TTRes
) {
7869 if (parseToken(lltok::kw_typeTestRes
, "expected 'typeTestRes' here") ||
7870 parseToken(lltok::colon
, "expected ':' here") ||
7871 parseToken(lltok::lparen
, "expected '(' here") ||
7872 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
7873 parseToken(lltok::colon
, "expected ':' here"))
7876 switch (Lex
.getKind()) {
7877 case lltok::kw_unknown
:
7878 TTRes
.TheKind
= TypeTestResolution::Unknown
;
7880 case lltok::kw_unsat
:
7881 TTRes
.TheKind
= TypeTestResolution::Unsat
;
7883 case lltok::kw_byteArray
:
7884 TTRes
.TheKind
= TypeTestResolution::ByteArray
;
7886 case lltok::kw_inline
:
7887 TTRes
.TheKind
= TypeTestResolution::Inline
;
7889 case lltok::kw_single
:
7890 TTRes
.TheKind
= TypeTestResolution::Single
;
7892 case lltok::kw_allOnes
:
7893 TTRes
.TheKind
= TypeTestResolution::AllOnes
;
7896 return error(Lex
.getLoc(), "unexpected TypeTestResolution kind");
7900 if (parseToken(lltok::comma
, "expected ',' here") ||
7901 parseToken(lltok::kw_sizeM1BitWidth
, "expected 'sizeM1BitWidth' here") ||
7902 parseToken(lltok::colon
, "expected ':' here") ||
7903 parseUInt32(TTRes
.SizeM1BitWidth
))
7906 // parse optional fields
7907 while (EatIfPresent(lltok::comma
)) {
7908 switch (Lex
.getKind()) {
7909 case lltok::kw_alignLog2
:
7911 if (parseToken(lltok::colon
, "expected ':'") ||
7912 parseUInt64(TTRes
.AlignLog2
))
7915 case lltok::kw_sizeM1
:
7917 if (parseToken(lltok::colon
, "expected ':'") || parseUInt64(TTRes
.SizeM1
))
7920 case lltok::kw_bitMask
: {
7923 if (parseToken(lltok::colon
, "expected ':'") || parseUInt32(Val
))
7925 assert(Val
<= 0xff);
7926 TTRes
.BitMask
= (uint8_t)Val
;
7929 case lltok::kw_inlineBits
:
7931 if (parseToken(lltok::colon
, "expected ':'") ||
7932 parseUInt64(TTRes
.InlineBits
))
7936 return error(Lex
.getLoc(), "expected optional TypeTestResolution field");
7940 if (parseToken(lltok::rparen
, "expected ')' here"))
7946 /// OptionalWpdResolutions
7947 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7948 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7949 bool LLParser::parseOptionalWpdResolutions(
7950 std::map
<uint64_t, WholeProgramDevirtResolution
> &WPDResMap
) {
7951 if (parseToken(lltok::kw_wpdResolutions
, "expected 'wpdResolutions' here") ||
7952 parseToken(lltok::colon
, "expected ':' here") ||
7953 parseToken(lltok::lparen
, "expected '(' here"))
7958 WholeProgramDevirtResolution WPDRes
;
7959 if (parseToken(lltok::lparen
, "expected '(' here") ||
7960 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
7961 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(Offset
) ||
7962 parseToken(lltok::comma
, "expected ',' here") || parseWpdRes(WPDRes
) ||
7963 parseToken(lltok::rparen
, "expected ')' here"))
7965 WPDResMap
[Offset
] = WPDRes
;
7966 } while (EatIfPresent(lltok::comma
));
7968 if (parseToken(lltok::rparen
, "expected ')' here"))
7975 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7976 /// [',' OptionalResByArg]? ')'
7977 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7978 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7979 /// [',' OptionalResByArg]? ')'
7980 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7981 /// [',' OptionalResByArg]? ')'
7982 bool LLParser::parseWpdRes(WholeProgramDevirtResolution
&WPDRes
) {
7983 if (parseToken(lltok::kw_wpdRes
, "expected 'wpdRes' here") ||
7984 parseToken(lltok::colon
, "expected ':' here") ||
7985 parseToken(lltok::lparen
, "expected '(' here") ||
7986 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
7987 parseToken(lltok::colon
, "expected ':' here"))
7990 switch (Lex
.getKind()) {
7991 case lltok::kw_indir
:
7992 WPDRes
.TheKind
= WholeProgramDevirtResolution::Indir
;
7994 case lltok::kw_singleImpl
:
7995 WPDRes
.TheKind
= WholeProgramDevirtResolution::SingleImpl
;
7997 case lltok::kw_branchFunnel
:
7998 WPDRes
.TheKind
= WholeProgramDevirtResolution::BranchFunnel
;
8001 return error(Lex
.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8005 // parse optional fields
8006 while (EatIfPresent(lltok::comma
)) {
8007 switch (Lex
.getKind()) {
8008 case lltok::kw_singleImplName
:
8010 if (parseToken(lltok::colon
, "expected ':' here") ||
8011 parseStringConstant(WPDRes
.SingleImplName
))
8014 case lltok::kw_resByArg
:
8015 if (parseOptionalResByArg(WPDRes
.ResByArg
))
8019 return error(Lex
.getLoc(),
8020 "expected optional WholeProgramDevirtResolution field");
8024 if (parseToken(lltok::rparen
, "expected ')' here"))
8030 /// OptionalResByArg
8031 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8032 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8033 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8034 /// 'virtualConstProp' )
8035 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8036 /// [',' 'bit' ':' UInt32]? ')'
8037 bool LLParser::parseOptionalResByArg(
8038 std::map
<std::vector
<uint64_t>, WholeProgramDevirtResolution::ByArg
>
8040 if (parseToken(lltok::kw_resByArg
, "expected 'resByArg' here") ||
8041 parseToken(lltok::colon
, "expected ':' here") ||
8042 parseToken(lltok::lparen
, "expected '(' here"))
8046 std::vector
<uint64_t> Args
;
8047 if (parseArgs(Args
) || parseToken(lltok::comma
, "expected ',' here") ||
8048 parseToken(lltok::kw_byArg
, "expected 'byArg here") ||
8049 parseToken(lltok::colon
, "expected ':' here") ||
8050 parseToken(lltok::lparen
, "expected '(' here") ||
8051 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
8052 parseToken(lltok::colon
, "expected ':' here"))
8055 WholeProgramDevirtResolution::ByArg ByArg
;
8056 switch (Lex
.getKind()) {
8057 case lltok::kw_indir
:
8058 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::Indir
;
8060 case lltok::kw_uniformRetVal
:
8061 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniformRetVal
;
8063 case lltok::kw_uniqueRetVal
:
8064 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniqueRetVal
;
8066 case lltok::kw_virtualConstProp
:
8067 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::VirtualConstProp
;
8070 return error(Lex
.getLoc(),
8071 "unexpected WholeProgramDevirtResolution::ByArg kind");
8075 // parse optional fields
8076 while (EatIfPresent(lltok::comma
)) {
8077 switch (Lex
.getKind()) {
8078 case lltok::kw_info
:
8080 if (parseToken(lltok::colon
, "expected ':' here") ||
8081 parseUInt64(ByArg
.Info
))
8084 case lltok::kw_byte
:
8086 if (parseToken(lltok::colon
, "expected ':' here") ||
8087 parseUInt32(ByArg
.Byte
))
8092 if (parseToken(lltok::colon
, "expected ':' here") ||
8093 parseUInt32(ByArg
.Bit
))
8097 return error(Lex
.getLoc(),
8098 "expected optional whole program devirt field");
8102 if (parseToken(lltok::rparen
, "expected ')' here"))
8105 ResByArg
[Args
] = ByArg
;
8106 } while (EatIfPresent(lltok::comma
));
8108 if (parseToken(lltok::rparen
, "expected ')' here"))
8114 /// OptionalResByArg
8115 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8116 bool LLParser::parseArgs(std::vector
<uint64_t> &Args
) {
8117 if (parseToken(lltok::kw_args
, "expected 'args' here") ||
8118 parseToken(lltok::colon
, "expected ':' here") ||
8119 parseToken(lltok::lparen
, "expected '(' here"))
8124 if (parseUInt64(Val
))
8126 Args
.push_back(Val
);
8127 } while (EatIfPresent(lltok::comma
));
8129 if (parseToken(lltok::rparen
, "expected ')' here"))
8135 static const auto FwdVIRef
= (GlobalValueSummaryMapTy::value_type
*)-8;
8137 static void resolveFwdRef(ValueInfo
*Fwd
, ValueInfo
&Resolved
) {
8138 bool ReadOnly
= Fwd
->isReadOnly();
8139 bool WriteOnly
= Fwd
->isWriteOnly();
8140 assert(!(ReadOnly
&& WriteOnly
));
8145 Fwd
->setWriteOnly();
8148 /// Stores the given Name/GUID and associated summary into the Index.
8149 /// Also updates any forward references to the associated entry ID.
8150 void LLParser::addGlobalValueToIndex(
8151 std::string Name
, GlobalValue::GUID GUID
, GlobalValue::LinkageTypes Linkage
,
8152 unsigned ID
, std::unique_ptr
<GlobalValueSummary
> Summary
) {
8153 // First create the ValueInfo utilizing the Name or GUID.
8156 assert(Name
.empty());
8157 VI
= Index
->getOrInsertValueInfo(GUID
);
8159 assert(!Name
.empty());
8161 auto *GV
= M
->getNamedValue(Name
);
8163 VI
= Index
->getOrInsertValueInfo(GV
);
8166 (!GlobalValue::isLocalLinkage(Linkage
) || !SourceFileName
.empty()) &&
8167 "Need a source_filename to compute GUID for local");
8168 GUID
= GlobalValue::getGUID(
8169 GlobalValue::getGlobalIdentifier(Name
, Linkage
, SourceFileName
));
8170 VI
= Index
->getOrInsertValueInfo(GUID
, Index
->saveString(Name
));
8174 // Resolve forward references from calls/refs
8175 auto FwdRefVIs
= ForwardRefValueInfos
.find(ID
);
8176 if (FwdRefVIs
!= ForwardRefValueInfos
.end()) {
8177 for (auto VIRef
: FwdRefVIs
->second
) {
8178 assert(VIRef
.first
->getRef() == FwdVIRef
&&
8179 "Forward referenced ValueInfo expected to be empty");
8180 resolveFwdRef(VIRef
.first
, VI
);
8182 ForwardRefValueInfos
.erase(FwdRefVIs
);
8185 // Resolve forward references from aliases
8186 auto FwdRefAliasees
= ForwardRefAliasees
.find(ID
);
8187 if (FwdRefAliasees
!= ForwardRefAliasees
.end()) {
8188 for (auto AliaseeRef
: FwdRefAliasees
->second
) {
8189 assert(!AliaseeRef
.first
->hasAliasee() &&
8190 "Forward referencing alias already has aliasee");
8191 assert(Summary
&& "Aliasee must be a definition");
8192 AliaseeRef
.first
->setAliasee(VI
, Summary
.get());
8194 ForwardRefAliasees
.erase(FwdRefAliasees
);
8197 // Add the summary if one was provided.
8199 Index
->addGlobalValueSummary(VI
, std::move(Summary
));
8201 // Save the associated ValueInfo for use in later references by ID.
8202 if (ID
== NumberedValueInfos
.size())
8203 NumberedValueInfos
.push_back(VI
);
8205 // Handle non-continuous numbers (to make test simplification easier).
8206 if (ID
> NumberedValueInfos
.size())
8207 NumberedValueInfos
.resize(ID
+ 1);
8208 NumberedValueInfos
[ID
] = VI
;
8212 /// parseSummaryIndexFlags
8213 /// ::= 'flags' ':' UInt64
8214 bool LLParser::parseSummaryIndexFlags() {
8215 assert(Lex
.getKind() == lltok::kw_flags
);
8218 if (parseToken(lltok::colon
, "expected ':' here"))
8221 if (parseUInt64(Flags
))
8224 Index
->setFlags(Flags
);
8229 /// ::= 'blockcount' ':' UInt64
8230 bool LLParser::parseBlockCount() {
8231 assert(Lex
.getKind() == lltok::kw_blockcount
);
8234 if (parseToken(lltok::colon
, "expected ':' here"))
8236 uint64_t BlockCount
;
8237 if (parseUInt64(BlockCount
))
8240 Index
->setBlockCount(BlockCount
);
8245 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8246 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8247 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8248 bool LLParser::parseGVEntry(unsigned ID
) {
8249 assert(Lex
.getKind() == lltok::kw_gv
);
8252 if (parseToken(lltok::colon
, "expected ':' here") ||
8253 parseToken(lltok::lparen
, "expected '(' here"))
8257 GlobalValue::GUID GUID
= 0;
8258 switch (Lex
.getKind()) {
8259 case lltok::kw_name
:
8261 if (parseToken(lltok::colon
, "expected ':' here") ||
8262 parseStringConstant(Name
))
8264 // Can't create GUID/ValueInfo until we have the linkage.
8266 case lltok::kw_guid
:
8268 if (parseToken(lltok::colon
, "expected ':' here") || parseUInt64(GUID
))
8272 return error(Lex
.getLoc(), "expected name or guid tag");
8275 if (!EatIfPresent(lltok::comma
)) {
8276 // No summaries. Wrap up.
8277 if (parseToken(lltok::rparen
, "expected ')' here"))
8279 // This was created for a call to an external or indirect target.
8280 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8281 // created for indirect calls with VP. A Name with no GUID came from
8282 // an external definition. We pass ExternalLinkage since that is only
8283 // used when the GUID must be computed from Name, and in that case
8284 // the symbol must have external linkage.
8285 addGlobalValueToIndex(Name
, GUID
, GlobalValue::ExternalLinkage
, ID
,
8290 // Have a list of summaries
8291 if (parseToken(lltok::kw_summaries
, "expected 'summaries' here") ||
8292 parseToken(lltok::colon
, "expected ':' here") ||
8293 parseToken(lltok::lparen
, "expected '(' here"))
8296 switch (Lex
.getKind()) {
8297 case lltok::kw_function
:
8298 if (parseFunctionSummary(Name
, GUID
, ID
))
8301 case lltok::kw_variable
:
8302 if (parseVariableSummary(Name
, GUID
, ID
))
8305 case lltok::kw_alias
:
8306 if (parseAliasSummary(Name
, GUID
, ID
))
8310 return error(Lex
.getLoc(), "expected summary type");
8312 } while (EatIfPresent(lltok::comma
));
8314 if (parseToken(lltok::rparen
, "expected ')' here") ||
8315 parseToken(lltok::rparen
, "expected ')' here"))
8322 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8323 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8324 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8325 /// [',' OptionalRefs]? ')'
8326 bool LLParser::parseFunctionSummary(std::string Name
, GlobalValue::GUID GUID
,
8328 assert(Lex
.getKind() == lltok::kw_function
);
8331 StringRef ModulePath
;
8332 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8333 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8334 /*NotEligibleToImport=*/false,
8335 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8337 std::vector
<FunctionSummary::EdgeTy
> Calls
;
8338 FunctionSummary::TypeIdInfo TypeIdInfo
;
8339 std::vector
<FunctionSummary::ParamAccess
> ParamAccesses
;
8340 std::vector
<ValueInfo
> Refs
;
8341 // Default is all-zeros (conservative values).
8342 FunctionSummary::FFlags FFlags
= {};
8343 if (parseToken(lltok::colon
, "expected ':' here") ||
8344 parseToken(lltok::lparen
, "expected '(' here") ||
8345 parseModuleReference(ModulePath
) ||
8346 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8347 parseToken(lltok::comma
, "expected ',' here") ||
8348 parseToken(lltok::kw_insts
, "expected 'insts' here") ||
8349 parseToken(lltok::colon
, "expected ':' here") || parseUInt32(InstCount
))
8352 // parse optional fields
8353 while (EatIfPresent(lltok::comma
)) {
8354 switch (Lex
.getKind()) {
8355 case lltok::kw_funcFlags
:
8356 if (parseOptionalFFlags(FFlags
))
8359 case lltok::kw_calls
:
8360 if (parseOptionalCalls(Calls
))
8363 case lltok::kw_typeIdInfo
:
8364 if (parseOptionalTypeIdInfo(TypeIdInfo
))
8367 case lltok::kw_refs
:
8368 if (parseOptionalRefs(Refs
))
8371 case lltok::kw_params
:
8372 if (parseOptionalParamAccesses(ParamAccesses
))
8376 return error(Lex
.getLoc(), "expected optional function summary field");
8380 if (parseToken(lltok::rparen
, "expected ')' here"))
8383 auto FS
= std::make_unique
<FunctionSummary
>(
8384 GVFlags
, InstCount
, FFlags
, /*EntryCount=*/0, std::move(Refs
),
8385 std::move(Calls
), std::move(TypeIdInfo
.TypeTests
),
8386 std::move(TypeIdInfo
.TypeTestAssumeVCalls
),
8387 std::move(TypeIdInfo
.TypeCheckedLoadVCalls
),
8388 std::move(TypeIdInfo
.TypeTestAssumeConstVCalls
),
8389 std::move(TypeIdInfo
.TypeCheckedLoadConstVCalls
),
8390 std::move(ParamAccesses
));
8392 FS
->setModulePath(ModulePath
);
8394 addGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8401 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8402 /// [',' OptionalRefs]? ')'
8403 bool LLParser::parseVariableSummary(std::string Name
, GlobalValue::GUID GUID
,
8405 assert(Lex
.getKind() == lltok::kw_variable
);
8408 StringRef ModulePath
;
8409 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8410 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8411 /*NotEligibleToImport=*/false,
8412 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8413 GlobalVarSummary::GVarFlags
GVarFlags(/*ReadOnly*/ false,
8414 /* WriteOnly */ false,
8415 /* Constant */ false,
8416 GlobalObject::VCallVisibilityPublic
);
8417 std::vector
<ValueInfo
> Refs
;
8418 VTableFuncList VTableFuncs
;
8419 if (parseToken(lltok::colon
, "expected ':' here") ||
8420 parseToken(lltok::lparen
, "expected '(' here") ||
8421 parseModuleReference(ModulePath
) ||
8422 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8423 parseToken(lltok::comma
, "expected ',' here") ||
8424 parseGVarFlags(GVarFlags
))
8427 // parse optional fields
8428 while (EatIfPresent(lltok::comma
)) {
8429 switch (Lex
.getKind()) {
8430 case lltok::kw_vTableFuncs
:
8431 if (parseOptionalVTableFuncs(VTableFuncs
))
8434 case lltok::kw_refs
:
8435 if (parseOptionalRefs(Refs
))
8439 return error(Lex
.getLoc(), "expected optional variable summary field");
8443 if (parseToken(lltok::rparen
, "expected ')' here"))
8447 std::make_unique
<GlobalVarSummary
>(GVFlags
, GVarFlags
, std::move(Refs
));
8449 GS
->setModulePath(ModulePath
);
8450 GS
->setVTableFuncs(std::move(VTableFuncs
));
8452 addGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8459 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8460 /// 'aliasee' ':' GVReference ')'
8461 bool LLParser::parseAliasSummary(std::string Name
, GlobalValue::GUID GUID
,
8463 assert(Lex
.getKind() == lltok::kw_alias
);
8464 LocTy Loc
= Lex
.getLoc();
8467 StringRef ModulePath
;
8468 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8469 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8470 /*NotEligibleToImport=*/false,
8471 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8472 if (parseToken(lltok::colon
, "expected ':' here") ||
8473 parseToken(lltok::lparen
, "expected '(' here") ||
8474 parseModuleReference(ModulePath
) ||
8475 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8476 parseToken(lltok::comma
, "expected ',' here") ||
8477 parseToken(lltok::kw_aliasee
, "expected 'aliasee' here") ||
8478 parseToken(lltok::colon
, "expected ':' here"))
8481 ValueInfo AliaseeVI
;
8483 if (parseGVReference(AliaseeVI
, GVId
))
8486 if (parseToken(lltok::rparen
, "expected ')' here"))
8489 auto AS
= std::make_unique
<AliasSummary
>(GVFlags
);
8491 AS
->setModulePath(ModulePath
);
8493 // Record forward reference if the aliasee is not parsed yet.
8494 if (AliaseeVI
.getRef() == FwdVIRef
) {
8495 ForwardRefAliasees
[GVId
].emplace_back(AS
.get(), Loc
);
8497 auto Summary
= Index
->findSummaryInModule(AliaseeVI
, ModulePath
);
8498 assert(Summary
&& "Aliasee must be a definition");
8499 AS
->setAliasee(AliaseeVI
, Summary
);
8502 addGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8510 bool LLParser::parseFlag(unsigned &Val
) {
8511 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
8512 return tokError("expected integer");
8513 Val
= (unsigned)Lex
.getAPSIntVal().getBoolValue();
8519 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8520 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8521 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8522 /// [',' 'noInline' ':' Flag]? ')'
8523 /// [',' 'alwaysInline' ':' Flag]? ')'
8525 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags
&FFlags
) {
8526 assert(Lex
.getKind() == lltok::kw_funcFlags
);
8529 if (parseToken(lltok::colon
, "expected ':' in funcFlags") |
8530 parseToken(lltok::lparen
, "expected '(' in funcFlags"))
8535 switch (Lex
.getKind()) {
8536 case lltok::kw_readNone
:
8538 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8540 FFlags
.ReadNone
= Val
;
8542 case lltok::kw_readOnly
:
8544 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8546 FFlags
.ReadOnly
= Val
;
8548 case lltok::kw_noRecurse
:
8550 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8552 FFlags
.NoRecurse
= Val
;
8554 case lltok::kw_returnDoesNotAlias
:
8556 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8558 FFlags
.ReturnDoesNotAlias
= Val
;
8560 case lltok::kw_noInline
:
8562 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8564 FFlags
.NoInline
= Val
;
8566 case lltok::kw_alwaysInline
:
8568 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
8570 FFlags
.AlwaysInline
= Val
;
8573 return error(Lex
.getLoc(), "expected function flag type");
8575 } while (EatIfPresent(lltok::comma
));
8577 if (parseToken(lltok::rparen
, "expected ')' in funcFlags"))
8584 /// := 'calls' ':' '(' Call [',' Call]* ')'
8585 /// Call ::= '(' 'callee' ':' GVReference
8586 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8587 bool LLParser::parseOptionalCalls(std::vector
<FunctionSummary::EdgeTy
> &Calls
) {
8588 assert(Lex
.getKind() == lltok::kw_calls
);
8591 if (parseToken(lltok::colon
, "expected ':' in calls") |
8592 parseToken(lltok::lparen
, "expected '(' in calls"))
8595 IdToIndexMapType IdToIndexMap
;
8596 // parse each call edge
8599 if (parseToken(lltok::lparen
, "expected '(' in call") ||
8600 parseToken(lltok::kw_callee
, "expected 'callee' in call") ||
8601 parseToken(lltok::colon
, "expected ':'"))
8604 LocTy Loc
= Lex
.getLoc();
8606 if (parseGVReference(VI
, GVId
))
8609 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
8611 if (EatIfPresent(lltok::comma
)) {
8612 // Expect either hotness or relbf
8613 if (EatIfPresent(lltok::kw_hotness
)) {
8614 if (parseToken(lltok::colon
, "expected ':'") || parseHotness(Hotness
))
8617 if (parseToken(lltok::kw_relbf
, "expected relbf") ||
8618 parseToken(lltok::colon
, "expected ':'") || parseUInt32(RelBF
))
8622 // Keep track of the Call array index needing a forward reference.
8623 // We will save the location of the ValueInfo needing an update, but
8624 // can only do so once the std::vector is finalized.
8625 if (VI
.getRef() == FwdVIRef
)
8626 IdToIndexMap
[GVId
].push_back(std::make_pair(Calls
.size(), Loc
));
8627 Calls
.push_back(FunctionSummary::EdgeTy
{VI
, CalleeInfo(Hotness
, RelBF
)});
8629 if (parseToken(lltok::rparen
, "expected ')' in call"))
8631 } while (EatIfPresent(lltok::comma
));
8633 // Now that the Calls vector is finalized, it is safe to save the locations
8634 // of any forward GV references that need updating later.
8635 for (auto I
: IdToIndexMap
) {
8636 auto &Infos
= ForwardRefValueInfos
[I
.first
];
8637 for (auto P
: I
.second
) {
8638 assert(Calls
[P
.first
].first
.getRef() == FwdVIRef
&&
8639 "Forward referenced ValueInfo expected to be empty");
8640 Infos
.emplace_back(&Calls
[P
.first
].first
, P
.second
);
8644 if (parseToken(lltok::rparen
, "expected ')' in calls"))
8651 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8652 bool LLParser::parseHotness(CalleeInfo::HotnessType
&Hotness
) {
8653 switch (Lex
.getKind()) {
8654 case lltok::kw_unknown
:
8655 Hotness
= CalleeInfo::HotnessType::Unknown
;
8657 case lltok::kw_cold
:
8658 Hotness
= CalleeInfo::HotnessType::Cold
;
8660 case lltok::kw_none
:
8661 Hotness
= CalleeInfo::HotnessType::None
;
8664 Hotness
= CalleeInfo::HotnessType::Hot
;
8666 case lltok::kw_critical
:
8667 Hotness
= CalleeInfo::HotnessType::Critical
;
8670 return error(Lex
.getLoc(), "invalid call edge hotness");
8676 /// OptionalVTableFuncs
8677 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8678 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8679 bool LLParser::parseOptionalVTableFuncs(VTableFuncList
&VTableFuncs
) {
8680 assert(Lex
.getKind() == lltok::kw_vTableFuncs
);
8683 if (parseToken(lltok::colon
, "expected ':' in vTableFuncs") |
8684 parseToken(lltok::lparen
, "expected '(' in vTableFuncs"))
8687 IdToIndexMapType IdToIndexMap
;
8688 // parse each virtual function pair
8691 if (parseToken(lltok::lparen
, "expected '(' in vTableFunc") ||
8692 parseToken(lltok::kw_virtFunc
, "expected 'callee' in vTableFunc") ||
8693 parseToken(lltok::colon
, "expected ':'"))
8696 LocTy Loc
= Lex
.getLoc();
8698 if (parseGVReference(VI
, GVId
))
8702 if (parseToken(lltok::comma
, "expected comma") ||
8703 parseToken(lltok::kw_offset
, "expected offset") ||
8704 parseToken(lltok::colon
, "expected ':'") || parseUInt64(Offset
))
8707 // Keep track of the VTableFuncs array index needing a forward reference.
8708 // We will save the location of the ValueInfo needing an update, but
8709 // can only do so once the std::vector is finalized.
8711 IdToIndexMap
[GVId
].push_back(std::make_pair(VTableFuncs
.size(), Loc
));
8712 VTableFuncs
.push_back({VI
, Offset
});
8714 if (parseToken(lltok::rparen
, "expected ')' in vTableFunc"))
8716 } while (EatIfPresent(lltok::comma
));
8718 // Now that the VTableFuncs vector is finalized, it is safe to save the
8719 // locations of any forward GV references that need updating later.
8720 for (auto I
: IdToIndexMap
) {
8721 auto &Infos
= ForwardRefValueInfos
[I
.first
];
8722 for (auto P
: I
.second
) {
8723 assert(VTableFuncs
[P
.first
].FuncVI
== EmptyVI
&&
8724 "Forward referenced ValueInfo expected to be empty");
8725 Infos
.emplace_back(&VTableFuncs
[P
.first
].FuncVI
, P
.second
);
8729 if (parseToken(lltok::rparen
, "expected ')' in vTableFuncs"))
8735 /// ParamNo := 'param' ':' UInt64
8736 bool LLParser::parseParamNo(uint64_t &ParamNo
) {
8737 if (parseToken(lltok::kw_param
, "expected 'param' here") ||
8738 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(ParamNo
))
8743 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
8744 bool LLParser::parseParamAccessOffset(ConstantRange
&Range
) {
8747 auto ParseAPSInt
= [&](APSInt
&Val
) {
8748 if (Lex
.getKind() != lltok::APSInt
)
8749 return tokError("expected integer");
8750 Val
= Lex
.getAPSIntVal();
8751 Val
= Val
.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth
);
8752 Val
.setIsSigned(true);
8756 if (parseToken(lltok::kw_offset
, "expected 'offset' here") ||
8757 parseToken(lltok::colon
, "expected ':' here") ||
8758 parseToken(lltok::lsquare
, "expected '[' here") || ParseAPSInt(Lower
) ||
8759 parseToken(lltok::comma
, "expected ',' here") || ParseAPSInt(Upper
) ||
8760 parseToken(lltok::rsquare
, "expected ']' here"))
8765 (Lower
== Upper
&& !Lower
.isMaxValue())
8766 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth
)
8767 : ConstantRange(Lower
, Upper
);
8773 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
8774 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call
&Call
,
8775 IdLocListType
&IdLocList
) {
8776 if (parseToken(lltok::lparen
, "expected '(' here") ||
8777 parseToken(lltok::kw_callee
, "expected 'callee' here") ||
8778 parseToken(lltok::colon
, "expected ':' here"))
8783 LocTy Loc
= Lex
.getLoc();
8784 if (parseGVReference(VI
, GVId
))
8788 IdLocList
.emplace_back(GVId
, Loc
);
8790 if (parseToken(lltok::comma
, "expected ',' here") ||
8791 parseParamNo(Call
.ParamNo
) ||
8792 parseToken(lltok::comma
, "expected ',' here") ||
8793 parseParamAccessOffset(Call
.Offsets
))
8796 if (parseToken(lltok::rparen
, "expected ')' here"))
8803 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8804 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
8805 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess
&Param
,
8806 IdLocListType
&IdLocList
) {
8807 if (parseToken(lltok::lparen
, "expected '(' here") ||
8808 parseParamNo(Param
.ParamNo
) ||
8809 parseToken(lltok::comma
, "expected ',' here") ||
8810 parseParamAccessOffset(Param
.Use
))
8813 if (EatIfPresent(lltok::comma
)) {
8814 if (parseToken(lltok::kw_calls
, "expected 'calls' here") ||
8815 parseToken(lltok::colon
, "expected ':' here") ||
8816 parseToken(lltok::lparen
, "expected '(' here"))
8819 FunctionSummary::ParamAccess::Call Call
;
8820 if (parseParamAccessCall(Call
, IdLocList
))
8822 Param
.Calls
.push_back(Call
);
8823 } while (EatIfPresent(lltok::comma
));
8825 if (parseToken(lltok::rparen
, "expected ')' here"))
8829 if (parseToken(lltok::rparen
, "expected ')' here"))
8835 /// OptionalParamAccesses
8836 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
8837 bool LLParser::parseOptionalParamAccesses(
8838 std::vector
<FunctionSummary::ParamAccess
> &Params
) {
8839 assert(Lex
.getKind() == lltok::kw_params
);
8842 if (parseToken(lltok::colon
, "expected ':' here") ||
8843 parseToken(lltok::lparen
, "expected '(' here"))
8846 IdLocListType VContexts
;
8847 size_t CallsNum
= 0;
8849 FunctionSummary::ParamAccess ParamAccess
;
8850 if (parseParamAccess(ParamAccess
, VContexts
))
8852 CallsNum
+= ParamAccess
.Calls
.size();
8853 assert(VContexts
.size() == CallsNum
);
8855 Params
.emplace_back(std::move(ParamAccess
));
8856 } while (EatIfPresent(lltok::comma
));
8858 if (parseToken(lltok::rparen
, "expected ')' here"))
8861 // Now that the Params is finalized, it is safe to save the locations
8862 // of any forward GV references that need updating later.
8863 IdLocListType::const_iterator ItContext
= VContexts
.begin();
8864 for (auto &PA
: Params
) {
8865 for (auto &C
: PA
.Calls
) {
8866 if (C
.Callee
.getRef() == FwdVIRef
)
8867 ForwardRefValueInfos
[ItContext
->first
].emplace_back(&C
.Callee
,
8872 assert(ItContext
== VContexts
.end());
8878 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8879 bool LLParser::parseOptionalRefs(std::vector
<ValueInfo
> &Refs
) {
8880 assert(Lex
.getKind() == lltok::kw_refs
);
8883 if (parseToken(lltok::colon
, "expected ':' in refs") ||
8884 parseToken(lltok::lparen
, "expected '(' in refs"))
8887 struct ValueContext
{
8892 std::vector
<ValueContext
> VContexts
;
8893 // parse each ref edge
8896 VC
.Loc
= Lex
.getLoc();
8897 if (parseGVReference(VC
.VI
, VC
.GVId
))
8899 VContexts
.push_back(VC
);
8900 } while (EatIfPresent(lltok::comma
));
8902 // Sort value contexts so that ones with writeonly
8903 // and readonly ValueInfo are at the end of VContexts vector.
8904 // See FunctionSummary::specialRefCounts()
8905 llvm::sort(VContexts
, [](const ValueContext
&VC1
, const ValueContext
&VC2
) {
8906 return VC1
.VI
.getAccessSpecifier() < VC2
.VI
.getAccessSpecifier();
8909 IdToIndexMapType IdToIndexMap
;
8910 for (auto &VC
: VContexts
) {
8911 // Keep track of the Refs array index needing a forward reference.
8912 // We will save the location of the ValueInfo needing an update, but
8913 // can only do so once the std::vector is finalized.
8914 if (VC
.VI
.getRef() == FwdVIRef
)
8915 IdToIndexMap
[VC
.GVId
].push_back(std::make_pair(Refs
.size(), VC
.Loc
));
8916 Refs
.push_back(VC
.VI
);
8919 // Now that the Refs vector is finalized, it is safe to save the locations
8920 // of any forward GV references that need updating later.
8921 for (auto I
: IdToIndexMap
) {
8922 auto &Infos
= ForwardRefValueInfos
[I
.first
];
8923 for (auto P
: I
.second
) {
8924 assert(Refs
[P
.first
].getRef() == FwdVIRef
&&
8925 "Forward referenced ValueInfo expected to be empty");
8926 Infos
.emplace_back(&Refs
[P
.first
], P
.second
);
8930 if (parseToken(lltok::rparen
, "expected ')' in refs"))
8936 /// OptionalTypeIdInfo
8937 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8938 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8939 /// [',' TypeCheckedLoadConstVCalls]? ')'
8940 bool LLParser::parseOptionalTypeIdInfo(
8941 FunctionSummary::TypeIdInfo
&TypeIdInfo
) {
8942 assert(Lex
.getKind() == lltok::kw_typeIdInfo
);
8945 if (parseToken(lltok::colon
, "expected ':' here") ||
8946 parseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8950 switch (Lex
.getKind()) {
8951 case lltok::kw_typeTests
:
8952 if (parseTypeTests(TypeIdInfo
.TypeTests
))
8955 case lltok::kw_typeTestAssumeVCalls
:
8956 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls
,
8957 TypeIdInfo
.TypeTestAssumeVCalls
))
8960 case lltok::kw_typeCheckedLoadVCalls
:
8961 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls
,
8962 TypeIdInfo
.TypeCheckedLoadVCalls
))
8965 case lltok::kw_typeTestAssumeConstVCalls
:
8966 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls
,
8967 TypeIdInfo
.TypeTestAssumeConstVCalls
))
8970 case lltok::kw_typeCheckedLoadConstVCalls
:
8971 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls
,
8972 TypeIdInfo
.TypeCheckedLoadConstVCalls
))
8976 return error(Lex
.getLoc(), "invalid typeIdInfo list type");
8978 } while (EatIfPresent(lltok::comma
));
8980 if (parseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8987 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8988 /// [',' (SummaryID | UInt64)]* ')'
8989 bool LLParser::parseTypeTests(std::vector
<GlobalValue::GUID
> &TypeTests
) {
8990 assert(Lex
.getKind() == lltok::kw_typeTests
);
8993 if (parseToken(lltok::colon
, "expected ':' here") ||
8994 parseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8997 IdToIndexMapType IdToIndexMap
;
8999 GlobalValue::GUID GUID
= 0;
9000 if (Lex
.getKind() == lltok::SummaryID
) {
9001 unsigned ID
= Lex
.getUIntVal();
9002 LocTy Loc
= Lex
.getLoc();
9003 // Keep track of the TypeTests array index needing a forward reference.
9004 // We will save the location of the GUID needing an update, but
9005 // can only do so once the std::vector is finalized.
9006 IdToIndexMap
[ID
].push_back(std::make_pair(TypeTests
.size(), Loc
));
9008 } else if (parseUInt64(GUID
))
9010 TypeTests
.push_back(GUID
);
9011 } while (EatIfPresent(lltok::comma
));
9013 // Now that the TypeTests vector is finalized, it is safe to save the
9014 // locations of any forward GV references that need updating later.
9015 for (auto I
: IdToIndexMap
) {
9016 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9017 for (auto P
: I
.second
) {
9018 assert(TypeTests
[P
.first
] == 0 &&
9019 "Forward referenced type id GUID expected to be 0");
9020 Ids
.emplace_back(&TypeTests
[P
.first
], P
.second
);
9024 if (parseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
9031 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9032 bool LLParser::parseVFuncIdList(
9033 lltok::Kind Kind
, std::vector
<FunctionSummary::VFuncId
> &VFuncIdList
) {
9034 assert(Lex
.getKind() == Kind
);
9037 if (parseToken(lltok::colon
, "expected ':' here") ||
9038 parseToken(lltok::lparen
, "expected '(' here"))
9041 IdToIndexMapType IdToIndexMap
;
9043 FunctionSummary::VFuncId VFuncId
;
9044 if (parseVFuncId(VFuncId
, IdToIndexMap
, VFuncIdList
.size()))
9046 VFuncIdList
.push_back(VFuncId
);
9047 } while (EatIfPresent(lltok::comma
));
9049 if (parseToken(lltok::rparen
, "expected ')' here"))
9052 // Now that the VFuncIdList vector is finalized, it is safe to save the
9053 // locations of any forward GV references that need updating later.
9054 for (auto I
: IdToIndexMap
) {
9055 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9056 for (auto P
: I
.second
) {
9057 assert(VFuncIdList
[P
.first
].GUID
== 0 &&
9058 "Forward referenced type id GUID expected to be 0");
9059 Ids
.emplace_back(&VFuncIdList
[P
.first
].GUID
, P
.second
);
9067 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9068 bool LLParser::parseConstVCallList(
9070 std::vector
<FunctionSummary::ConstVCall
> &ConstVCallList
) {
9071 assert(Lex
.getKind() == Kind
);
9074 if (parseToken(lltok::colon
, "expected ':' here") ||
9075 parseToken(lltok::lparen
, "expected '(' here"))
9078 IdToIndexMapType IdToIndexMap
;
9080 FunctionSummary::ConstVCall ConstVCall
;
9081 if (parseConstVCall(ConstVCall
, IdToIndexMap
, ConstVCallList
.size()))
9083 ConstVCallList
.push_back(ConstVCall
);
9084 } while (EatIfPresent(lltok::comma
));
9086 if (parseToken(lltok::rparen
, "expected ')' here"))
9089 // Now that the ConstVCallList vector is finalized, it is safe to save the
9090 // locations of any forward GV references that need updating later.
9091 for (auto I
: IdToIndexMap
) {
9092 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9093 for (auto P
: I
.second
) {
9094 assert(ConstVCallList
[P
.first
].VFunc
.GUID
== 0 &&
9095 "Forward referenced type id GUID expected to be 0");
9096 Ids
.emplace_back(&ConstVCallList
[P
.first
].VFunc
.GUID
, P
.second
);
9104 /// ::= '(' VFuncId ',' Args ')'
9105 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall
&ConstVCall
,
9106 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
9107 if (parseToken(lltok::lparen
, "expected '(' here") ||
9108 parseVFuncId(ConstVCall
.VFunc
, IdToIndexMap
, Index
))
9111 if (EatIfPresent(lltok::comma
))
9112 if (parseArgs(ConstVCall
.Args
))
9115 if (parseToken(lltok::rparen
, "expected ')' here"))
9122 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9123 /// 'offset' ':' UInt64 ')'
9124 bool LLParser::parseVFuncId(FunctionSummary::VFuncId
&VFuncId
,
9125 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
9126 assert(Lex
.getKind() == lltok::kw_vFuncId
);
9129 if (parseToken(lltok::colon
, "expected ':' here") ||
9130 parseToken(lltok::lparen
, "expected '(' here"))
9133 if (Lex
.getKind() == lltok::SummaryID
) {
9135 unsigned ID
= Lex
.getUIntVal();
9136 LocTy Loc
= Lex
.getLoc();
9137 // Keep track of the array index needing a forward reference.
9138 // We will save the location of the GUID needing an update, but
9139 // can only do so once the caller's std::vector is finalized.
9140 IdToIndexMap
[ID
].push_back(std::make_pair(Index
, Loc
));
9142 } else if (parseToken(lltok::kw_guid
, "expected 'guid' here") ||
9143 parseToken(lltok::colon
, "expected ':' here") ||
9144 parseUInt64(VFuncId
.GUID
))
9147 if (parseToken(lltok::comma
, "expected ',' here") ||
9148 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
9149 parseToken(lltok::colon
, "expected ':' here") ||
9150 parseUInt64(VFuncId
.Offset
) ||
9151 parseToken(lltok::rparen
, "expected ')' here"))
9158 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9159 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9160 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9161 /// 'canAutoHide' ':' Flag ',' ')'
9162 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags
&GVFlags
) {
9163 assert(Lex
.getKind() == lltok::kw_flags
);
9166 if (parseToken(lltok::colon
, "expected ':' here") ||
9167 parseToken(lltok::lparen
, "expected '(' here"))
9172 switch (Lex
.getKind()) {
9173 case lltok::kw_linkage
:
9175 if (parseToken(lltok::colon
, "expected ':'"))
9178 GVFlags
.Linkage
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
9179 assert(HasLinkage
&& "Linkage not optional in summary entry");
9182 case lltok::kw_visibility
:
9184 if (parseToken(lltok::colon
, "expected ':'"))
9186 parseOptionalVisibility(Flag
);
9187 GVFlags
.Visibility
= Flag
;
9189 case lltok::kw_notEligibleToImport
:
9191 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9193 GVFlags
.NotEligibleToImport
= Flag
;
9195 case lltok::kw_live
:
9197 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9199 GVFlags
.Live
= Flag
;
9201 case lltok::kw_dsoLocal
:
9203 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9205 GVFlags
.DSOLocal
= Flag
;
9207 case lltok::kw_canAutoHide
:
9209 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9211 GVFlags
.CanAutoHide
= Flag
;
9214 return error(Lex
.getLoc(), "expected gv flag type");
9216 } while (EatIfPresent(lltok::comma
));
9218 if (parseToken(lltok::rparen
, "expected ')' here"))
9225 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9226 /// ',' 'writeonly' ':' Flag
9227 /// ',' 'constant' ':' Flag ')'
9228 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags
&GVarFlags
) {
9229 assert(Lex
.getKind() == lltok::kw_varFlags
);
9232 if (parseToken(lltok::colon
, "expected ':' here") ||
9233 parseToken(lltok::lparen
, "expected '(' here"))
9236 auto ParseRest
= [this](unsigned int &Val
) {
9238 if (parseToken(lltok::colon
, "expected ':'"))
9240 return parseFlag(Val
);
9245 switch (Lex
.getKind()) {
9246 case lltok::kw_readonly
:
9247 if (ParseRest(Flag
))
9249 GVarFlags
.MaybeReadOnly
= Flag
;
9251 case lltok::kw_writeonly
:
9252 if (ParseRest(Flag
))
9254 GVarFlags
.MaybeWriteOnly
= Flag
;
9256 case lltok::kw_constant
:
9257 if (ParseRest(Flag
))
9259 GVarFlags
.Constant
= Flag
;
9261 case lltok::kw_vcall_visibility
:
9262 if (ParseRest(Flag
))
9264 GVarFlags
.VCallVisibility
= Flag
;
9267 return error(Lex
.getLoc(), "expected gvar flag type");
9269 } while (EatIfPresent(lltok::comma
));
9270 return parseToken(lltok::rparen
, "expected ')' here");
9274 /// ::= 'module' ':' UInt
9275 bool LLParser::parseModuleReference(StringRef
&ModulePath
) {
9277 if (parseToken(lltok::kw_module
, "expected 'module' here") ||
9278 parseToken(lltok::colon
, "expected ':' here") ||
9279 parseToken(lltok::SummaryID
, "expected module ID"))
9282 unsigned ModuleID
= Lex
.getUIntVal();
9283 auto I
= ModuleIdMap
.find(ModuleID
);
9284 // We should have already parsed all module IDs
9285 assert(I
!= ModuleIdMap
.end());
9286 ModulePath
= I
->second
;
9292 bool LLParser::parseGVReference(ValueInfo
&VI
, unsigned &GVId
) {
9293 bool WriteOnly
= false, ReadOnly
= EatIfPresent(lltok::kw_readonly
);
9295 WriteOnly
= EatIfPresent(lltok::kw_writeonly
);
9296 if (parseToken(lltok::SummaryID
, "expected GV ID"))
9299 GVId
= Lex
.getUIntVal();
9300 // Check if we already have a VI for this GV
9301 if (GVId
< NumberedValueInfos
.size()) {
9302 assert(NumberedValueInfos
[GVId
].getRef() != FwdVIRef
);
9303 VI
= NumberedValueInfos
[GVId
];
9305 // We will create a forward reference to the stored location.
9306 VI
= ValueInfo(false, FwdVIRef
);