1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.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/Constants.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/IR/ValueSymbolTable.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
57 static std::string getTypeString(Type *T) {
59 raw_string_ostream Tmp(Result);
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run() {
69 if (Context.shouldDiscardValueNames())
72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
93 restoreParsingState(Slots);
97 SMLoc Start = Lex.getLoc();
101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
122 bool LLParser::ValidateEndOfModule() {
123 // Handle any function attribute group forward references.
124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
132 if (Function *Fn = dyn_cast<Function>(V)) {
133 AttributeList AS = Fn->getAttributes();
134 AttrBuilder FnAttrs(AS.getFnAttributes());
135 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
139 // If the alignment was parsed as an attribute, move to the alignment
141 if (FnAttrs.hasAlignmentAttr()) {
142 Fn->setAlignment(FnAttrs.getAlignment());
143 FnAttrs.removeAttribute(Attribute::Alignment);
146 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
147 AttributeSet::get(Context, FnAttrs));
148 Fn->setAttributes(AS);
149 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
150 AttributeList AS = CI->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes());
152 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
154 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
155 AttributeSet::get(Context, FnAttrs));
156 CI->setAttributes(AS);
157 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
158 AttributeList AS = II->getAttributes();
159 AttrBuilder FnAttrs(AS.getFnAttributes());
160 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
163 AttributeSet::get(Context, FnAttrs));
164 II->setAttributes(AS);
165 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
166 AttrBuilder Attrs(GV->getAttributes());
168 GV->setAttributes(AttributeSet::get(Context,Attrs));
170 llvm_unreachable("invalid object with forward attribute group reference");
174 // If there are entries in ForwardRefBlockAddresses at this point, the
175 // function was never defined.
176 if (!ForwardRefBlockAddresses.empty())
177 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
178 "expected function name in blockaddress");
180 for (const auto &NT : NumberedTypes)
181 if (NT.second.second.isValid())
182 return Error(NT.second.second,
183 "use of undefined type '%" + Twine(NT.first) + "'");
185 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
186 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
187 if (I->second.second.isValid())
188 return Error(I->second.second,
189 "use of undefined type named '" + I->getKey() + "'");
191 if (!ForwardRefComdats.empty())
192 return Error(ForwardRefComdats.begin()->second,
193 "use of undefined comdat '$" +
194 ForwardRefComdats.begin()->first + "'");
196 if (!ForwardRefVals.empty())
197 return Error(ForwardRefVals.begin()->second.second,
198 "use of undefined value '@" + ForwardRefVals.begin()->first +
201 if (!ForwardRefValIDs.empty())
202 return Error(ForwardRefValIDs.begin()->second.second,
203 "use of undefined value '@" +
204 Twine(ForwardRefValIDs.begin()->first) + "'");
206 if (!ForwardRefMDNodes.empty())
207 return Error(ForwardRefMDNodes.begin()->second.second,
208 "use of undefined metadata '!" +
209 Twine(ForwardRefMDNodes.begin()->first) + "'");
211 // Resolve metadata cycles.
212 for (auto &N : NumberedMetadata) {
213 if (N.second && !N.second->isResolved())
214 N.second->resolveCycles();
217 for (auto *Inst : InstsWithTBAATag) {
218 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
219 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
220 auto *UpgradedMD = UpgradeTBAANode(*MD);
221 if (MD != UpgradedMD)
222 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
225 // Look for intrinsic functions and CallInst that need to be upgraded
226 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
227 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
229 // Some types could be renamed during loading if several modules are
230 // loaded in the same LLVMContext (LTO scenario). In this case we should
231 // remangle intrinsics names as well.
232 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
233 Function *F = &*FI++;
234 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
235 F->replaceAllUsesWith(Remangled.getValue());
236 F->eraseFromParent();
240 if (UpgradeDebugInfo)
241 llvm::UpgradeDebugInfo(*M);
243 UpgradeModuleFlags(*M);
244 UpgradeSectionAttributes(*M);
248 // Initialize the slot mapping.
249 // Because by this point we've parsed and validated everything, we can "steal"
250 // the mapping from LLParser as it doesn't need it anymore.
251 Slots->GlobalValues = std::move(NumberedVals);
252 Slots->MetadataNodes = std::move(NumberedMetadata);
253 for (const auto &I : NamedTypes)
254 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
255 for (const auto &I : NumberedTypes)
256 Slots->Types.insert(std::make_pair(I.first, I.second.first));
261 //===----------------------------------------------------------------------===//
262 // Top-Level Entities
263 //===----------------------------------------------------------------------===//
265 bool LLParser::ParseTopLevelEntities() {
267 switch (Lex.getKind()) {
268 default: return TokError("expected top-level entity");
269 case lltok::Eof: return false;
270 case lltok::kw_declare: if (ParseDeclare()) return true; break;
271 case lltok::kw_define: if (ParseDefine()) return true; break;
272 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
273 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
274 case lltok::kw_source_filename:
275 if (ParseSourceFileName())
278 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
279 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
280 case lltok::LocalVar: if (ParseNamedType()) return true; break;
281 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
282 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
283 case lltok::ComdatVar: if (parseComdat()) return true; break;
284 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
285 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
287 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
288 case lltok::kw_uselistorder_bb:
289 if (ParseUseListOrderBB())
297 /// ::= 'module' 'asm' STRINGCONSTANT
298 bool LLParser::ParseModuleAsm() {
299 assert(Lex.getKind() == lltok::kw_module);
303 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
304 ParseStringConstant(AsmStr)) return true;
306 M->appendModuleInlineAsm(AsmStr);
311 /// ::= 'target' 'triple' '=' STRINGCONSTANT
312 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
313 bool LLParser::ParseTargetDefinition() {
314 assert(Lex.getKind() == lltok::kw_target);
317 default: return TokError("unknown target property");
318 case lltok::kw_triple:
320 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
321 ParseStringConstant(Str))
323 M->setTargetTriple(Str);
325 case lltok::kw_datalayout:
327 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
328 ParseStringConstant(Str))
330 if (DataLayoutStr.empty())
331 M->setDataLayout(Str);
337 /// ::= 'source_filename' '=' STRINGCONSTANT
338 bool LLParser::ParseSourceFileName() {
339 assert(Lex.getKind() == lltok::kw_source_filename);
342 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
343 ParseStringConstant(Str))
345 M->setSourceFileName(Str);
350 /// ::= 'deplibs' '=' '[' ']'
351 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
352 /// FIXME: Remove in 4.0. Currently parse, but ignore.
353 bool LLParser::ParseDepLibs() {
354 assert(Lex.getKind() == lltok::kw_deplibs);
356 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
357 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
360 if (EatIfPresent(lltok::rsquare))
365 if (ParseStringConstant(Str)) return true;
366 } while (EatIfPresent(lltok::comma));
368 return ParseToken(lltok::rsquare, "expected ']' at end of list");
371 /// ParseUnnamedType:
372 /// ::= LocalVarID '=' 'type' type
373 bool LLParser::ParseUnnamedType() {
374 LocTy TypeLoc = Lex.getLoc();
375 unsigned TypeID = Lex.getUIntVal();
376 Lex.Lex(); // eat LocalVarID;
378 if (ParseToken(lltok::equal, "expected '=' after name") ||
379 ParseToken(lltok::kw_type, "expected 'type' after '='"))
382 Type *Result = nullptr;
383 if (ParseStructDefinition(TypeLoc, "",
384 NumberedTypes[TypeID], Result)) return true;
386 if (!isa<StructType>(Result)) {
387 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
389 return Error(TypeLoc, "non-struct types may not be recursive");
390 Entry.first = Result;
391 Entry.second = SMLoc();
398 /// ::= LocalVar '=' 'type' type
399 bool LLParser::ParseNamedType() {
400 std::string Name = Lex.getStrVal();
401 LocTy NameLoc = Lex.getLoc();
402 Lex.Lex(); // eat LocalVar.
404 if (ParseToken(lltok::equal, "expected '=' after name") ||
405 ParseToken(lltok::kw_type, "expected 'type' after name"))
408 Type *Result = nullptr;
409 if (ParseStructDefinition(NameLoc, Name,
410 NamedTypes[Name], Result)) return true;
412 if (!isa<StructType>(Result)) {
413 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
415 return Error(NameLoc, "non-struct types may not be recursive");
416 Entry.first = Result;
417 Entry.second = SMLoc();
424 /// ::= 'declare' FunctionHeader
425 bool LLParser::ParseDeclare() {
426 assert(Lex.getKind() == lltok::kw_declare);
429 std::vector<std::pair<unsigned, MDNode *>> MDs;
430 while (Lex.getKind() == lltok::MetadataVar) {
433 if (ParseMetadataAttachment(MDK, N))
435 MDs.push_back({MDK, N});
439 if (ParseFunctionHeader(F, false))
442 F->addMetadata(MD.first, *MD.second);
447 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
448 bool LLParser::ParseDefine() {
449 assert(Lex.getKind() == lltok::kw_define);
453 return ParseFunctionHeader(F, true) ||
454 ParseOptionalFunctionMetadata(*F) ||
455 ParseFunctionBody(*F);
461 bool LLParser::ParseGlobalType(bool &IsConstant) {
462 if (Lex.getKind() == lltok::kw_constant)
464 else if (Lex.getKind() == lltok::kw_global)
468 return TokError("expected 'global' or 'constant'");
474 bool LLParser::ParseOptionalUnnamedAddr(
475 GlobalVariable::UnnamedAddr &UnnamedAddr) {
476 if (EatIfPresent(lltok::kw_unnamed_addr))
477 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
478 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
479 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
481 UnnamedAddr = GlobalValue::UnnamedAddr::None;
485 /// ParseUnnamedGlobal:
486 /// OptionalVisibility (ALIAS | IFUNC) ...
487 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
488 /// OptionalDLLStorageClass
489 /// ... -> global variable
490 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
491 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
492 /// OptionalDLLStorageClass
493 /// ... -> global variable
494 bool LLParser::ParseUnnamedGlobal() {
495 unsigned VarID = NumberedVals.size();
497 LocTy NameLoc = Lex.getLoc();
499 // Handle the GlobalID form.
500 if (Lex.getKind() == lltok::GlobalID) {
501 if (Lex.getUIntVal() != VarID)
502 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
504 Lex.Lex(); // eat GlobalID;
506 if (ParseToken(lltok::equal, "expected '=' after name"))
511 unsigned Linkage, Visibility, DLLStorageClass;
513 GlobalVariable::ThreadLocalMode TLM;
514 GlobalVariable::UnnamedAddr UnnamedAddr;
515 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
517 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
520 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
521 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
522 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
524 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
525 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
528 /// ParseNamedGlobal:
529 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
530 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
531 /// OptionalVisibility OptionalDLLStorageClass
532 /// ... -> global variable
533 bool LLParser::ParseNamedGlobal() {
534 assert(Lex.getKind() == lltok::GlobalVar);
535 LocTy NameLoc = Lex.getLoc();
536 std::string Name = Lex.getStrVal();
540 unsigned Linkage, Visibility, DLLStorageClass;
542 GlobalVariable::ThreadLocalMode TLM;
543 GlobalVariable::UnnamedAddr UnnamedAddr;
544 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
545 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
547 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
550 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
551 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
552 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
554 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
555 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
558 bool LLParser::parseComdat() {
559 assert(Lex.getKind() == lltok::ComdatVar);
560 std::string Name = Lex.getStrVal();
561 LocTy NameLoc = Lex.getLoc();
564 if (ParseToken(lltok::equal, "expected '=' here"))
567 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
568 return TokError("expected comdat type");
570 Comdat::SelectionKind SK;
571 switch (Lex.getKind()) {
573 return TokError("unknown selection kind");
577 case lltok::kw_exactmatch:
578 SK = Comdat::ExactMatch;
580 case lltok::kw_largest:
581 SK = Comdat::Largest;
583 case lltok::kw_noduplicates:
584 SK = Comdat::NoDuplicates;
586 case lltok::kw_samesize:
587 SK = Comdat::SameSize;
592 // See if the comdat was forward referenced, if so, use the comdat.
593 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
594 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
595 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
596 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
599 if (I != ComdatSymTab.end())
602 C = M->getOrInsertComdat(Name);
603 C->setSelectionKind(SK);
609 // ::= '!' STRINGCONSTANT
610 bool LLParser::ParseMDString(MDString *&Result) {
612 if (ParseStringConstant(Str)) return true;
613 Result = MDString::get(Context, Str);
618 // ::= '!' MDNodeNumber
619 bool LLParser::ParseMDNodeID(MDNode *&Result) {
620 // !{ ..., !42, ... }
621 LocTy IDLoc = Lex.getLoc();
623 if (ParseUInt32(MID))
626 // If not a forward reference, just return it now.
627 if (NumberedMetadata.count(MID)) {
628 Result = NumberedMetadata[MID];
632 // Otherwise, create MDNode forward reference.
633 auto &FwdRef = ForwardRefMDNodes[MID];
634 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
636 Result = FwdRef.first.get();
637 NumberedMetadata[MID].reset(Result);
641 /// ParseNamedMetadata:
642 /// !foo = !{ !1, !2 }
643 bool LLParser::ParseNamedMetadata() {
644 assert(Lex.getKind() == lltok::MetadataVar);
645 std::string Name = Lex.getStrVal();
648 if (ParseToken(lltok::equal, "expected '=' here") ||
649 ParseToken(lltok::exclaim, "Expected '!' here") ||
650 ParseToken(lltok::lbrace, "Expected '{' here"))
653 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
654 if (Lex.getKind() != lltok::rbrace)
657 // Parse DIExpressions inline as a special case. They are still MDNodes,
658 // so they can still appear in named metadata. Remove this logic if they
659 // become plain Metadata.
660 if (Lex.getKind() == lltok::MetadataVar &&
661 Lex.getStrVal() == "DIExpression") {
662 if (ParseDIExpression(N, /*IsDistinct=*/false))
664 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
669 } while (EatIfPresent(lltok::comma));
671 return ParseToken(lltok::rbrace, "expected end of metadata node");
674 /// ParseStandaloneMetadata:
676 bool LLParser::ParseStandaloneMetadata() {
677 assert(Lex.getKind() == lltok::exclaim);
679 unsigned MetadataID = 0;
682 if (ParseUInt32(MetadataID) ||
683 ParseToken(lltok::equal, "expected '=' here"))
686 // Detect common error, from old metadata syntax.
687 if (Lex.getKind() == lltok::Type)
688 return TokError("unexpected type in metadata definition");
690 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
691 if (Lex.getKind() == lltok::MetadataVar) {
692 if (ParseSpecializedMDNode(Init, IsDistinct))
694 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
695 ParseMDTuple(Init, IsDistinct))
698 // See if this was forward referenced, if so, handle it.
699 auto FI = ForwardRefMDNodes.find(MetadataID);
700 if (FI != ForwardRefMDNodes.end()) {
701 FI->second.first->replaceAllUsesWith(Init);
702 ForwardRefMDNodes.erase(FI);
704 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
706 if (NumberedMetadata.count(MetadataID))
707 return TokError("Metadata id is already used");
708 NumberedMetadata[MetadataID].reset(Init);
714 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
715 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
716 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
719 // If there was an explicit dso_local, update GV. In the absence of an explicit
720 // dso_local we keep the default value.
721 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
723 GV.setDSOLocal(true);
726 /// parseIndirectSymbol:
727 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
728 /// OptionalVisibility OptionalDLLStorageClass
729 /// OptionalThreadLocal OptionalUnnamedAddr
730 // 'alias|ifunc' IndirectSymbol
735 /// Everything through OptionalUnnamedAddr has already been parsed.
737 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
738 unsigned L, unsigned Visibility,
739 unsigned DLLStorageClass, bool DSOLocal,
740 GlobalVariable::ThreadLocalMode TLM,
741 GlobalVariable::UnnamedAddr UnnamedAddr) {
743 if (Lex.getKind() == lltok::kw_alias)
745 else if (Lex.getKind() == lltok::kw_ifunc)
748 llvm_unreachable("Not an alias or ifunc!");
751 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
753 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
754 return Error(NameLoc, "invalid linkage type for alias");
756 if (!isValidVisibilityForLinkage(Visibility, L))
757 return Error(NameLoc,
758 "symbol with local linkage must have default visibility");
761 LocTy ExplicitTypeLoc = Lex.getLoc();
763 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
767 LocTy AliaseeLoc = Lex.getLoc();
768 if (Lex.getKind() != lltok::kw_bitcast &&
769 Lex.getKind() != lltok::kw_getelementptr &&
770 Lex.getKind() != lltok::kw_addrspacecast &&
771 Lex.getKind() != lltok::kw_inttoptr) {
772 if (ParseGlobalTypeAndValue(Aliasee))
775 // The bitcast dest type is not present, it is implied by the dest type.
779 if (ID.Kind != ValID::t_Constant)
780 return Error(AliaseeLoc, "invalid aliasee");
781 Aliasee = ID.ConstantVal;
784 Type *AliaseeType = Aliasee->getType();
785 auto *PTy = dyn_cast<PointerType>(AliaseeType);
787 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
788 unsigned AddrSpace = PTy->getAddressSpace();
790 if (IsAlias && Ty != PTy->getElementType())
793 "explicit pointee type doesn't match operand's pointee type");
795 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
798 "explicit pointee type should be a function type");
800 GlobalValue *GVal = nullptr;
802 // See if the alias was forward referenced, if so, prepare to replace the
803 // forward reference.
805 GVal = M->getNamedValue(Name);
807 if (!ForwardRefVals.erase(Name))
808 return Error(NameLoc, "redefinition of global '@" + Name + "'");
811 auto I = ForwardRefValIDs.find(NumberedVals.size());
812 if (I != ForwardRefValIDs.end()) {
813 GVal = I->second.first;
814 ForwardRefValIDs.erase(I);
818 // Okay, create the alias but do not insert it into the module yet.
819 std::unique_ptr<GlobalIndirectSymbol> GA;
821 GA.reset(GlobalAlias::create(Ty, AddrSpace,
822 (GlobalValue::LinkageTypes)Linkage, Name,
823 Aliasee, /*Parent*/ nullptr));
825 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
826 (GlobalValue::LinkageTypes)Linkage, Name,
827 Aliasee, /*Parent*/ nullptr));
828 GA->setThreadLocalMode(TLM);
829 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
830 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
831 GA->setUnnamedAddr(UnnamedAddr);
832 maybeSetDSOLocal(DSOLocal, *GA);
835 NumberedVals.push_back(GA.get());
838 // Verify that types agree.
839 if (GVal->getType() != GA->getType())
842 "forward reference and definition of alias have different types");
844 // If they agree, just RAUW the old value with the alias and remove the
846 GVal->replaceAllUsesWith(GA.get());
847 GVal->eraseFromParent();
850 // Insert into the module, we know its name won't collide now.
852 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
854 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
855 assert(GA->getName() == Name && "Should not be a name conflict!");
857 // The module owns this now
864 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
865 /// OptionalVisibility OptionalDLLStorageClass
866 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
867 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
868 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
869 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
870 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
871 /// Const OptionalAttrs
873 /// Everything up to and including OptionalUnnamedAddr has been parsed
876 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
877 unsigned Linkage, bool HasLinkage,
878 unsigned Visibility, unsigned DLLStorageClass,
879 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
880 GlobalVariable::UnnamedAddr UnnamedAddr) {
881 if (!isValidVisibilityForLinkage(Visibility, Linkage))
882 return Error(NameLoc,
883 "symbol with local linkage must have default visibility");
886 bool IsConstant, IsExternallyInitialized;
887 LocTy IsExternallyInitializedLoc;
891 if (ParseOptionalAddrSpace(AddrSpace) ||
892 ParseOptionalToken(lltok::kw_externally_initialized,
893 IsExternallyInitialized,
894 &IsExternallyInitializedLoc) ||
895 ParseGlobalType(IsConstant) ||
896 ParseType(Ty, TyLoc))
899 // If the linkage is specified and is external, then no initializer is
901 Constant *Init = nullptr;
903 !GlobalValue::isValidDeclarationLinkage(
904 (GlobalValue::LinkageTypes)Linkage)) {
905 if (ParseGlobalValue(Ty, Init))
909 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
910 return Error(TyLoc, "invalid type for global variable");
912 GlobalValue *GVal = nullptr;
914 // See if the global was forward referenced, if so, use the global.
916 GVal = M->getNamedValue(Name);
918 if (!ForwardRefVals.erase(Name))
919 return Error(NameLoc, "redefinition of global '@" + Name + "'");
922 auto I = ForwardRefValIDs.find(NumberedVals.size());
923 if (I != ForwardRefValIDs.end()) {
924 GVal = I->second.first;
925 ForwardRefValIDs.erase(I);
931 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
932 Name, nullptr, GlobalVariable::NotThreadLocal,
935 if (GVal->getValueType() != Ty)
937 "forward reference and definition of global have different types");
939 GV = cast<GlobalVariable>(GVal);
941 // Move the forward-reference to the correct spot in the module.
942 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
946 NumberedVals.push_back(GV);
948 // Set the parsed properties on the global.
950 GV->setInitializer(Init);
951 GV->setConstant(IsConstant);
952 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
953 maybeSetDSOLocal(DSOLocal, *GV);
954 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
955 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
956 GV->setExternallyInitialized(IsExternallyInitialized);
957 GV->setThreadLocalMode(TLM);
958 GV->setUnnamedAddr(UnnamedAddr);
960 // Parse attributes on the global.
961 while (Lex.getKind() == lltok::comma) {
964 if (Lex.getKind() == lltok::kw_section) {
966 GV->setSection(Lex.getStrVal());
967 if (ParseToken(lltok::StringConstant, "expected global section string"))
969 } else if (Lex.getKind() == lltok::kw_align) {
971 if (ParseOptionalAlignment(Alignment)) return true;
972 GV->setAlignment(Alignment);
973 } else if (Lex.getKind() == lltok::MetadataVar) {
974 if (ParseGlobalObjectMetadataAttachment(*GV))
978 if (parseOptionalComdat(Name, C))
983 return TokError("unknown global variable property!");
989 std::vector<unsigned> FwdRefAttrGrps;
990 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
992 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
993 GV->setAttributes(AttributeSet::get(Context, Attrs));
994 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1000 /// ParseUnnamedAttrGrp
1001 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1002 bool LLParser::ParseUnnamedAttrGrp() {
1003 assert(Lex.getKind() == lltok::kw_attributes);
1004 LocTy AttrGrpLoc = Lex.getLoc();
1007 if (Lex.getKind() != lltok::AttrGrpID)
1008 return TokError("expected attribute group id");
1010 unsigned VarID = Lex.getUIntVal();
1011 std::vector<unsigned> unused;
1015 if (ParseToken(lltok::equal, "expected '=' here") ||
1016 ParseToken(lltok::lbrace, "expected '{' here") ||
1017 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1019 ParseToken(lltok::rbrace, "expected end of attribute group"))
1022 if (!NumberedAttrBuilders[VarID].hasAttributes())
1023 return Error(AttrGrpLoc, "attribute group has no attributes");
1028 /// ParseFnAttributeValuePairs
1029 /// ::= <attr> | <attr> '=' <value>
1030 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1031 std::vector<unsigned> &FwdRefAttrGrps,
1032 bool inAttrGrp, LocTy &BuiltinLoc) {
1033 bool HaveError = false;
1038 lltok::Kind Token = Lex.getKind();
1039 if (Token == lltok::kw_builtin)
1040 BuiltinLoc = Lex.getLoc();
1043 if (!inAttrGrp) return HaveError;
1044 return Error(Lex.getLoc(), "unterminated attribute group");
1049 case lltok::AttrGrpID: {
1050 // Allow a function to reference an attribute group:
1052 // define void @foo() #1 { ... }
1056 "cannot have an attribute group reference in an attribute group");
1058 unsigned AttrGrpNum = Lex.getUIntVal();
1059 if (inAttrGrp) break;
1061 // Save the reference to the attribute group. We'll fill it in later.
1062 FwdRefAttrGrps.push_back(AttrGrpNum);
1065 // Target-dependent attributes:
1066 case lltok::StringConstant: {
1067 if (ParseStringAttribute(B))
1072 // Target-independent attributes:
1073 case lltok::kw_align: {
1074 // As a hack, we allow function alignment to be initially parsed as an
1075 // attribute on a function declaration/definition or added to an attribute
1076 // group and later moved to the alignment field.
1080 if (ParseToken(lltok::equal, "expected '=' here") ||
1081 ParseUInt32(Alignment))
1084 if (ParseOptionalAlignment(Alignment))
1087 B.addAlignmentAttr(Alignment);
1090 case lltok::kw_alignstack: {
1094 if (ParseToken(lltok::equal, "expected '=' here") ||
1095 ParseUInt32(Alignment))
1098 if (ParseOptionalStackAlignment(Alignment))
1101 B.addStackAlignmentAttr(Alignment);
1104 case lltok::kw_allocsize: {
1105 unsigned ElemSizeArg;
1106 Optional<unsigned> NumElemsArg;
1107 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1108 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1110 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1113 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1114 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1115 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1116 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1117 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1118 case lltok::kw_inaccessiblememonly:
1119 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1120 case lltok::kw_inaccessiblemem_or_argmemonly:
1121 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1122 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1123 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1124 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1125 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1126 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1127 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1128 case lltok::kw_noimplicitfloat:
1129 B.addAttribute(Attribute::NoImplicitFloat); break;
1130 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1131 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1132 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1133 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1134 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1135 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1136 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1137 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1138 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1139 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1140 case lltok::kw_returns_twice:
1141 B.addAttribute(Attribute::ReturnsTwice); break;
1142 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1143 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1144 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1145 case lltok::kw_sspstrong:
1146 B.addAttribute(Attribute::StackProtectStrong); break;
1147 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1148 case lltok::kw_sanitize_address:
1149 B.addAttribute(Attribute::SanitizeAddress); break;
1150 case lltok::kw_sanitize_hwaddress:
1151 B.addAttribute(Attribute::SanitizeHWAddress); break;
1152 case lltok::kw_sanitize_thread:
1153 B.addAttribute(Attribute::SanitizeThread); break;
1154 case lltok::kw_sanitize_memory:
1155 B.addAttribute(Attribute::SanitizeMemory); break;
1156 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1157 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1158 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1161 case lltok::kw_inreg:
1162 case lltok::kw_signext:
1163 case lltok::kw_zeroext:
1166 "invalid use of attribute on a function");
1168 case lltok::kw_byval:
1169 case lltok::kw_dereferenceable:
1170 case lltok::kw_dereferenceable_or_null:
1171 case lltok::kw_inalloca:
1172 case lltok::kw_nest:
1173 case lltok::kw_noalias:
1174 case lltok::kw_nocapture:
1175 case lltok::kw_nonnull:
1176 case lltok::kw_returned:
1177 case lltok::kw_sret:
1178 case lltok::kw_swifterror:
1179 case lltok::kw_swiftself:
1182 "invalid use of parameter-only attribute on a function");
1190 //===----------------------------------------------------------------------===//
1191 // GlobalValue Reference/Resolution Routines.
1192 //===----------------------------------------------------------------------===//
1194 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1195 const std::string &Name) {
1196 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1197 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1199 return new GlobalVariable(*M, PTy->getElementType(), false,
1200 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1201 nullptr, GlobalVariable::NotThreadLocal,
1202 PTy->getAddressSpace());
1205 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1206 /// forward reference record if needed. This can return null if the value
1207 /// exists but does not have the right type.
1208 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1210 PointerType *PTy = dyn_cast<PointerType>(Ty);
1212 Error(Loc, "global variable reference must have pointer type");
1216 // Look this name up in the normal function symbol table.
1218 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1220 // If this is a forward reference for the value, see if we already created a
1221 // forward ref record.
1223 auto I = ForwardRefVals.find(Name);
1224 if (I != ForwardRefVals.end())
1225 Val = I->second.first;
1228 // If we have the value in the symbol table or fwd-ref table, return it.
1230 if (Val->getType() == Ty) return Val;
1231 Error(Loc, "'@" + Name + "' defined with type '" +
1232 getTypeString(Val->getType()) + "'");
1236 // Otherwise, create a new forward reference for this value and remember it.
1237 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1238 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1242 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1243 PointerType *PTy = dyn_cast<PointerType>(Ty);
1245 Error(Loc, "global variable reference must have pointer type");
1249 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1251 // If this is a forward reference for the value, see if we already created a
1252 // forward ref record.
1254 auto I = ForwardRefValIDs.find(ID);
1255 if (I != ForwardRefValIDs.end())
1256 Val = I->second.first;
1259 // If we have the value in the symbol table or fwd-ref table, return it.
1261 if (Val->getType() == Ty) return Val;
1262 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1263 getTypeString(Val->getType()) + "'");
1267 // Otherwise, create a new forward reference for this value and remember it.
1268 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1269 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1273 //===----------------------------------------------------------------------===//
1274 // Comdat Reference/Resolution Routines.
1275 //===----------------------------------------------------------------------===//
1277 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1278 // Look this name up in the comdat symbol table.
1279 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1280 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1281 if (I != ComdatSymTab.end())
1284 // Otherwise, create a new forward reference for this value and remember it.
1285 Comdat *C = M->getOrInsertComdat(Name);
1286 ForwardRefComdats[Name] = Loc;
1290 //===----------------------------------------------------------------------===//
1292 //===----------------------------------------------------------------------===//
1294 /// ParseToken - If the current token has the specified kind, eat it and return
1295 /// success. Otherwise, emit the specified error and return failure.
1296 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1297 if (Lex.getKind() != T)
1298 return TokError(ErrMsg);
1303 /// ParseStringConstant
1304 /// ::= StringConstant
1305 bool LLParser::ParseStringConstant(std::string &Result) {
1306 if (Lex.getKind() != lltok::StringConstant)
1307 return TokError("expected string constant");
1308 Result = Lex.getStrVal();
1315 bool LLParser::ParseUInt32(uint32_t &Val) {
1316 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1317 return TokError("expected integer");
1318 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1319 if (Val64 != unsigned(Val64))
1320 return TokError("expected 32-bit integer (too large)");
1328 bool LLParser::ParseUInt64(uint64_t &Val) {
1329 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1330 return TokError("expected integer");
1331 Val = Lex.getAPSIntVal().getLimitedValue();
1337 /// := 'localdynamic'
1338 /// := 'initialexec'
1340 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1341 switch (Lex.getKind()) {
1343 return TokError("expected localdynamic, initialexec or localexec");
1344 case lltok::kw_localdynamic:
1345 TLM = GlobalVariable::LocalDynamicTLSModel;
1347 case lltok::kw_initialexec:
1348 TLM = GlobalVariable::InitialExecTLSModel;
1350 case lltok::kw_localexec:
1351 TLM = GlobalVariable::LocalExecTLSModel;
1359 /// ParseOptionalThreadLocal
1361 /// := 'thread_local'
1362 /// := 'thread_local' '(' tlsmodel ')'
1363 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1364 TLM = GlobalVariable::NotThreadLocal;
1365 if (!EatIfPresent(lltok::kw_thread_local))
1368 TLM = GlobalVariable::GeneralDynamicTLSModel;
1369 if (Lex.getKind() == lltok::lparen) {
1371 return ParseTLSModel(TLM) ||
1372 ParseToken(lltok::rparen, "expected ')' after thread local model");
1377 /// ParseOptionalAddrSpace
1379 /// := 'addrspace' '(' uint32 ')'
1380 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1382 if (!EatIfPresent(lltok::kw_addrspace))
1384 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1385 ParseUInt32(AddrSpace) ||
1386 ParseToken(lltok::rparen, "expected ')' in address space");
1389 /// ParseStringAttribute
1390 /// := StringConstant
1391 /// := StringConstant '=' StringConstant
1392 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1393 std::string Attr = Lex.getStrVal();
1396 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1398 B.addAttribute(Attr, Val);
1402 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1403 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1404 bool HaveError = false;
1409 lltok::Kind Token = Lex.getKind();
1411 default: // End of attributes.
1413 case lltok::StringConstant: {
1414 if (ParseStringAttribute(B))
1418 case lltok::kw_align: {
1420 if (ParseOptionalAlignment(Alignment))
1422 B.addAlignmentAttr(Alignment);
1425 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1426 case lltok::kw_dereferenceable: {
1428 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1430 B.addDereferenceableAttr(Bytes);
1433 case lltok::kw_dereferenceable_or_null: {
1435 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1437 B.addDereferenceableOrNullAttr(Bytes);
1440 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1441 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1442 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1443 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1444 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1445 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1446 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1447 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1448 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1449 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1450 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1451 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1452 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1453 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1454 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1456 case lltok::kw_alignstack:
1457 case lltok::kw_alwaysinline:
1458 case lltok::kw_argmemonly:
1459 case lltok::kw_builtin:
1460 case lltok::kw_inlinehint:
1461 case lltok::kw_jumptable:
1462 case lltok::kw_minsize:
1463 case lltok::kw_naked:
1464 case lltok::kw_nobuiltin:
1465 case lltok::kw_noduplicate:
1466 case lltok::kw_noimplicitfloat:
1467 case lltok::kw_noinline:
1468 case lltok::kw_nonlazybind:
1469 case lltok::kw_noredzone:
1470 case lltok::kw_noreturn:
1471 case lltok::kw_nounwind:
1472 case lltok::kw_optnone:
1473 case lltok::kw_optsize:
1474 case lltok::kw_returns_twice:
1475 case lltok::kw_sanitize_address:
1476 case lltok::kw_sanitize_hwaddress:
1477 case lltok::kw_sanitize_memory:
1478 case lltok::kw_sanitize_thread:
1480 case lltok::kw_sspreq:
1481 case lltok::kw_sspstrong:
1482 case lltok::kw_safestack:
1483 case lltok::kw_strictfp:
1484 case lltok::kw_uwtable:
1485 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1493 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1494 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1495 bool HaveError = false;
1500 lltok::Kind Token = Lex.getKind();
1502 default: // End of attributes.
1504 case lltok::StringConstant: {
1505 if (ParseStringAttribute(B))
1509 case lltok::kw_dereferenceable: {
1511 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1513 B.addDereferenceableAttr(Bytes);
1516 case lltok::kw_dereferenceable_or_null: {
1518 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1520 B.addDereferenceableOrNullAttr(Bytes);
1523 case lltok::kw_align: {
1525 if (ParseOptionalAlignment(Alignment))
1527 B.addAlignmentAttr(Alignment);
1530 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1531 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1532 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1533 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1534 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1537 case lltok::kw_byval:
1538 case lltok::kw_inalloca:
1539 case lltok::kw_nest:
1540 case lltok::kw_nocapture:
1541 case lltok::kw_returned:
1542 case lltok::kw_sret:
1543 case lltok::kw_swifterror:
1544 case lltok::kw_swiftself:
1545 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1548 case lltok::kw_alignstack:
1549 case lltok::kw_alwaysinline:
1550 case lltok::kw_argmemonly:
1551 case lltok::kw_builtin:
1552 case lltok::kw_cold:
1553 case lltok::kw_inlinehint:
1554 case lltok::kw_jumptable:
1555 case lltok::kw_minsize:
1556 case lltok::kw_naked:
1557 case lltok::kw_nobuiltin:
1558 case lltok::kw_noduplicate:
1559 case lltok::kw_noimplicitfloat:
1560 case lltok::kw_noinline:
1561 case lltok::kw_nonlazybind:
1562 case lltok::kw_noredzone:
1563 case lltok::kw_noreturn:
1564 case lltok::kw_nounwind:
1565 case lltok::kw_optnone:
1566 case lltok::kw_optsize:
1567 case lltok::kw_returns_twice:
1568 case lltok::kw_sanitize_address:
1569 case lltok::kw_sanitize_hwaddress:
1570 case lltok::kw_sanitize_memory:
1571 case lltok::kw_sanitize_thread:
1573 case lltok::kw_sspreq:
1574 case lltok::kw_sspstrong:
1575 case lltok::kw_safestack:
1576 case lltok::kw_strictfp:
1577 case lltok::kw_uwtable:
1578 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1581 case lltok::kw_readnone:
1582 case lltok::kw_readonly:
1583 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1590 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1595 return GlobalValue::ExternalLinkage;
1596 case lltok::kw_private:
1597 return GlobalValue::PrivateLinkage;
1598 case lltok::kw_internal:
1599 return GlobalValue::InternalLinkage;
1600 case lltok::kw_weak:
1601 return GlobalValue::WeakAnyLinkage;
1602 case lltok::kw_weak_odr:
1603 return GlobalValue::WeakODRLinkage;
1604 case lltok::kw_linkonce:
1605 return GlobalValue::LinkOnceAnyLinkage;
1606 case lltok::kw_linkonce_odr:
1607 return GlobalValue::LinkOnceODRLinkage;
1608 case lltok::kw_available_externally:
1609 return GlobalValue::AvailableExternallyLinkage;
1610 case lltok::kw_appending:
1611 return GlobalValue::AppendingLinkage;
1612 case lltok::kw_common:
1613 return GlobalValue::CommonLinkage;
1614 case lltok::kw_extern_weak:
1615 return GlobalValue::ExternalWeakLinkage;
1616 case lltok::kw_external:
1617 return GlobalValue::ExternalLinkage;
1621 /// ParseOptionalLinkage
1628 /// ::= 'linkonce_odr'
1629 /// ::= 'available_externally'
1632 /// ::= 'extern_weak'
1634 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1635 unsigned &Visibility,
1636 unsigned &DLLStorageClass,
1638 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1641 ParseOptionalDSOLocal(DSOLocal);
1642 ParseOptionalVisibility(Visibility);
1643 ParseOptionalDLLStorageClass(DLLStorageClass);
1645 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1646 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1652 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1653 switch (Lex.getKind()) {
1657 case lltok::kw_dso_local:
1661 case lltok::kw_dso_preemptable:
1668 /// ParseOptionalVisibility
1674 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1675 switch (Lex.getKind()) {
1677 Res = GlobalValue::DefaultVisibility;
1679 case lltok::kw_default:
1680 Res = GlobalValue::DefaultVisibility;
1682 case lltok::kw_hidden:
1683 Res = GlobalValue::HiddenVisibility;
1685 case lltok::kw_protected:
1686 Res = GlobalValue::ProtectedVisibility;
1692 /// ParseOptionalDLLStorageClass
1697 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1698 switch (Lex.getKind()) {
1700 Res = GlobalValue::DefaultStorageClass;
1702 case lltok::kw_dllimport:
1703 Res = GlobalValue::DLLImportStorageClass;
1705 case lltok::kw_dllexport:
1706 Res = GlobalValue::DLLExportStorageClass;
1712 /// ParseOptionalCallingConv
1716 /// ::= 'intel_ocl_bicc'
1718 /// ::= 'x86_stdcallcc'
1719 /// ::= 'x86_fastcallcc'
1720 /// ::= 'x86_thiscallcc'
1721 /// ::= 'x86_vectorcallcc'
1722 /// ::= 'arm_apcscc'
1723 /// ::= 'arm_aapcscc'
1724 /// ::= 'arm_aapcs_vfpcc'
1725 /// ::= 'msp430_intrcc'
1726 /// ::= 'avr_intrcc'
1727 /// ::= 'avr_signalcc'
1728 /// ::= 'ptx_kernel'
1729 /// ::= 'ptx_device'
1731 /// ::= 'spir_kernel'
1732 /// ::= 'x86_64_sysvcc'
1734 /// ::= 'webkit_jscc'
1736 /// ::= 'preserve_mostcc'
1737 /// ::= 'preserve_allcc'
1740 /// ::= 'x86_intrcc'
1743 /// ::= 'cxx_fast_tlscc'
1751 /// ::= 'amdgpu_kernel'
1754 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1755 switch (Lex.getKind()) {
1756 default: CC = CallingConv::C; return false;
1757 case lltok::kw_ccc: CC = CallingConv::C; break;
1758 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1759 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1760 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1761 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1762 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1763 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1764 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1765 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1766 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1767 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1768 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1769 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1770 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1771 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1772 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1773 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1774 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1775 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1776 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1777 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1778 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1779 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1780 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1781 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1782 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1783 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1784 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1785 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1786 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1787 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1788 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1789 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1790 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1791 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1792 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1793 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1794 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1795 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1796 case lltok::kw_cc: {
1798 return ParseUInt32(CC);
1806 /// ParseMetadataAttachment
1808 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1809 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1811 std::string Name = Lex.getStrVal();
1812 Kind = M->getMDKindID(Name);
1815 return ParseMDNode(MD);
1818 /// ParseInstructionMetadata
1819 /// ::= !dbg !42 (',' !dbg !57)*
1820 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1822 if (Lex.getKind() != lltok::MetadataVar)
1823 return TokError("expected metadata after comma");
1827 if (ParseMetadataAttachment(MDK, N))
1830 Inst.setMetadata(MDK, N);
1831 if (MDK == LLVMContext::MD_tbaa)
1832 InstsWithTBAATag.push_back(&Inst);
1834 // If this is the end of the list, we're done.
1835 } while (EatIfPresent(lltok::comma));
1839 /// ParseGlobalObjectMetadataAttachment
1841 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1844 if (ParseMetadataAttachment(MDK, N))
1847 GO.addMetadata(MDK, *N);
1851 /// ParseOptionalFunctionMetadata
1853 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1854 while (Lex.getKind() == lltok::MetadataVar)
1855 if (ParseGlobalObjectMetadataAttachment(F))
1860 /// ParseOptionalAlignment
1863 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1865 if (!EatIfPresent(lltok::kw_align))
1867 LocTy AlignLoc = Lex.getLoc();
1868 if (ParseUInt32(Alignment)) return true;
1869 if (!isPowerOf2_32(Alignment))
1870 return Error(AlignLoc, "alignment is not a power of two");
1871 if (Alignment > Value::MaximumAlignment)
1872 return Error(AlignLoc, "huge alignments are not supported yet");
1876 /// ParseOptionalDerefAttrBytes
1878 /// ::= AttrKind '(' 4 ')'
1880 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1881 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1883 assert((AttrKind == lltok::kw_dereferenceable ||
1884 AttrKind == lltok::kw_dereferenceable_or_null) &&
1888 if (!EatIfPresent(AttrKind))
1890 LocTy ParenLoc = Lex.getLoc();
1891 if (!EatIfPresent(lltok::lparen))
1892 return Error(ParenLoc, "expected '('");
1893 LocTy DerefLoc = Lex.getLoc();
1894 if (ParseUInt64(Bytes)) return true;
1895 ParenLoc = Lex.getLoc();
1896 if (!EatIfPresent(lltok::rparen))
1897 return Error(ParenLoc, "expected ')'");
1899 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1903 /// ParseOptionalCommaAlign
1907 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1909 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1910 bool &AteExtraComma) {
1911 AteExtraComma = false;
1912 while (EatIfPresent(lltok::comma)) {
1913 // Metadata at the end is an early exit.
1914 if (Lex.getKind() == lltok::MetadataVar) {
1915 AteExtraComma = true;
1919 if (Lex.getKind() != lltok::kw_align)
1920 return Error(Lex.getLoc(), "expected metadata or 'align'");
1922 if (ParseOptionalAlignment(Alignment)) return true;
1928 /// ParseOptionalCommaAddrSpace
1930 /// ::= ',' addrspace(1)
1932 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1934 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
1936 bool &AteExtraComma) {
1937 AteExtraComma = false;
1938 while (EatIfPresent(lltok::comma)) {
1939 // Metadata at the end is an early exit.
1940 if (Lex.getKind() == lltok::MetadataVar) {
1941 AteExtraComma = true;
1946 if (Lex.getKind() != lltok::kw_addrspace)
1947 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
1949 if (ParseOptionalAddrSpace(AddrSpace))
1956 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1957 Optional<unsigned> &HowManyArg) {
1960 auto StartParen = Lex.getLoc();
1961 if (!EatIfPresent(lltok::lparen))
1962 return Error(StartParen, "expected '('");
1964 if (ParseUInt32(BaseSizeArg))
1967 if (EatIfPresent(lltok::comma)) {
1968 auto HowManyAt = Lex.getLoc();
1970 if (ParseUInt32(HowMany))
1972 if (HowMany == BaseSizeArg)
1973 return Error(HowManyAt,
1974 "'allocsize' indices can't refer to the same parameter");
1975 HowManyArg = HowMany;
1979 auto EndParen = Lex.getLoc();
1980 if (!EatIfPresent(lltok::rparen))
1981 return Error(EndParen, "expected ')'");
1985 /// ParseScopeAndOrdering
1986 /// if isAtomic: ::= SyncScope? AtomicOrdering
1989 /// This sets Scope and Ordering to the parsed values.
1990 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
1991 AtomicOrdering &Ordering) {
1995 return ParseScope(SSID) || ParseOrdering(Ordering);
1999 /// ::= syncscope("singlethread" | "<target scope>")?
2001 /// This sets synchronization scope ID to the ID of the parsed value.
2002 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2003 SSID = SyncScope::System;
2004 if (EatIfPresent(lltok::kw_syncscope)) {
2005 auto StartParenAt = Lex.getLoc();
2006 if (!EatIfPresent(lltok::lparen))
2007 return Error(StartParenAt, "Expected '(' in syncscope");
2010 auto SSNAt = Lex.getLoc();
2011 if (ParseStringConstant(SSN))
2012 return Error(SSNAt, "Expected synchronization scope name");
2014 auto EndParenAt = Lex.getLoc();
2015 if (!EatIfPresent(lltok::rparen))
2016 return Error(EndParenAt, "Expected ')' in syncscope");
2018 SSID = Context.getOrInsertSyncScopeID(SSN);
2025 /// ::= AtomicOrdering
2027 /// This sets Ordering to the parsed value.
2028 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2029 switch (Lex.getKind()) {
2030 default: return TokError("Expected ordering on atomic instruction");
2031 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2032 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2033 // Not specified yet:
2034 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2035 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2036 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2037 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2038 case lltok::kw_seq_cst:
2039 Ordering = AtomicOrdering::SequentiallyConsistent;
2046 /// ParseOptionalStackAlignment
2048 /// ::= 'alignstack' '(' 4 ')'
2049 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2051 if (!EatIfPresent(lltok::kw_alignstack))
2053 LocTy ParenLoc = Lex.getLoc();
2054 if (!EatIfPresent(lltok::lparen))
2055 return Error(ParenLoc, "expected '('");
2056 LocTy AlignLoc = Lex.getLoc();
2057 if (ParseUInt32(Alignment)) return true;
2058 ParenLoc = Lex.getLoc();
2059 if (!EatIfPresent(lltok::rparen))
2060 return Error(ParenLoc, "expected ')'");
2061 if (!isPowerOf2_32(Alignment))
2062 return Error(AlignLoc, "stack alignment is not a power of two");
2066 /// ParseIndexList - This parses the index list for an insert/extractvalue
2067 /// instruction. This sets AteExtraComma in the case where we eat an extra
2068 /// comma at the end of the line and find that it is followed by metadata.
2069 /// Clients that don't allow metadata can call the version of this function that
2070 /// only takes one argument.
2073 /// ::= (',' uint32)+
2075 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2076 bool &AteExtraComma) {
2077 AteExtraComma = false;
2079 if (Lex.getKind() != lltok::comma)
2080 return TokError("expected ',' as start of index list");
2082 while (EatIfPresent(lltok::comma)) {
2083 if (Lex.getKind() == lltok::MetadataVar) {
2084 if (Indices.empty()) return TokError("expected index");
2085 AteExtraComma = true;
2089 if (ParseUInt32(Idx)) return true;
2090 Indices.push_back(Idx);
2096 //===----------------------------------------------------------------------===//
2098 //===----------------------------------------------------------------------===//
2100 /// ParseType - Parse a type.
2101 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2102 SMLoc TypeLoc = Lex.getLoc();
2103 switch (Lex.getKind()) {
2105 return TokError(Msg);
2107 // Type ::= 'float' | 'void' (etc)
2108 Result = Lex.getTyVal();
2112 // Type ::= StructType
2113 if (ParseAnonStructType(Result, false))
2116 case lltok::lsquare:
2117 // Type ::= '[' ... ']'
2118 Lex.Lex(); // eat the lsquare.
2119 if (ParseArrayVectorType(Result, false))
2122 case lltok::less: // Either vector or packed struct.
2123 // Type ::= '<' ... '>'
2125 if (Lex.getKind() == lltok::lbrace) {
2126 if (ParseAnonStructType(Result, true) ||
2127 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2129 } else if (ParseArrayVectorType(Result, true))
2132 case lltok::LocalVar: {
2134 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2136 // If the type hasn't been defined yet, create a forward definition and
2137 // remember where that forward def'n was seen (in case it never is defined).
2139 Entry.first = StructType::create(Context, Lex.getStrVal());
2140 Entry.second = Lex.getLoc();
2142 Result = Entry.first;
2147 case lltok::LocalVarID: {
2149 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2151 // If the type hasn't been defined yet, create a forward definition and
2152 // remember where that forward def'n was seen (in case it never is defined).
2154 Entry.first = StructType::create(Context);
2155 Entry.second = Lex.getLoc();
2157 Result = Entry.first;
2163 // Parse the type suffixes.
2165 switch (Lex.getKind()) {
2168 if (!AllowVoid && Result->isVoidTy())
2169 return Error(TypeLoc, "void type only allowed for function results");
2172 // Type ::= Type '*'
2174 if (Result->isLabelTy())
2175 return TokError("basic block pointers are invalid");
2176 if (Result->isVoidTy())
2177 return TokError("pointers to void are invalid - use i8* instead");
2178 if (!PointerType::isValidElementType(Result))
2179 return TokError("pointer to this type is invalid");
2180 Result = PointerType::getUnqual(Result);
2184 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2185 case lltok::kw_addrspace: {
2186 if (Result->isLabelTy())
2187 return TokError("basic block pointers are invalid");
2188 if (Result->isVoidTy())
2189 return TokError("pointers to void are invalid; use i8* instead");
2190 if (!PointerType::isValidElementType(Result))
2191 return TokError("pointer to this type is invalid");
2193 if (ParseOptionalAddrSpace(AddrSpace) ||
2194 ParseToken(lltok::star, "expected '*' in address space"))
2197 Result = PointerType::get(Result, AddrSpace);
2201 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2203 if (ParseFunctionType(Result))
2210 /// ParseParameterList
2212 /// ::= '(' Arg (',' Arg)* ')'
2214 /// ::= Type OptionalAttributes Value OptionalAttributes
2215 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2216 PerFunctionState &PFS, bool IsMustTailCall,
2217 bool InVarArgsFunc) {
2218 if (ParseToken(lltok::lparen, "expected '(' in call"))
2221 while (Lex.getKind() != lltok::rparen) {
2222 // If this isn't the first argument, we need a comma.
2223 if (!ArgList.empty() &&
2224 ParseToken(lltok::comma, "expected ',' in argument list"))
2227 // Parse an ellipsis if this is a musttail call in a variadic function.
2228 if (Lex.getKind() == lltok::dotdotdot) {
2229 const char *Msg = "unexpected ellipsis in argument list for ";
2230 if (!IsMustTailCall)
2231 return TokError(Twine(Msg) + "non-musttail call");
2233 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2234 Lex.Lex(); // Lex the '...', it is purely for readability.
2235 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2238 // Parse the argument.
2240 Type *ArgTy = nullptr;
2241 AttrBuilder ArgAttrs;
2243 if (ParseType(ArgTy, ArgLoc))
2246 if (ArgTy->isMetadataTy()) {
2247 if (ParseMetadataAsValue(V, PFS))
2250 // Otherwise, handle normal operands.
2251 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2254 ArgList.push_back(ParamInfo(
2255 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2258 if (IsMustTailCall && InVarArgsFunc)
2259 return TokError("expected '...' at end of argument list for musttail call "
2260 "in varargs function");
2262 Lex.Lex(); // Lex the ')'.
2266 /// ParseOptionalOperandBundles
2268 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2271 /// ::= bundle-tag '(' ')'
2272 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2274 /// bundle-tag ::= String Constant
2275 bool LLParser::ParseOptionalOperandBundles(
2276 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2277 LocTy BeginLoc = Lex.getLoc();
2278 if (!EatIfPresent(lltok::lsquare))
2281 while (Lex.getKind() != lltok::rsquare) {
2282 // If this isn't the first operand bundle, we need a comma.
2283 if (!BundleList.empty() &&
2284 ParseToken(lltok::comma, "expected ',' in input list"))
2288 if (ParseStringConstant(Tag))
2291 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2294 std::vector<Value *> Inputs;
2295 while (Lex.getKind() != lltok::rparen) {
2296 // If this isn't the first input, we need a comma.
2297 if (!Inputs.empty() &&
2298 ParseToken(lltok::comma, "expected ',' in input list"))
2302 Value *Input = nullptr;
2303 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2305 Inputs.push_back(Input);
2308 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2310 Lex.Lex(); // Lex the ')'.
2313 if (BundleList.empty())
2314 return Error(BeginLoc, "operand bundle set must not be empty");
2316 Lex.Lex(); // Lex the ']'.
2320 /// ParseArgumentList - Parse the argument list for a function type or function
2322 /// ::= '(' ArgTypeListI ')'
2326 /// ::= ArgTypeList ',' '...'
2327 /// ::= ArgType (',' ArgType)*
2329 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2332 assert(Lex.getKind() == lltok::lparen);
2333 Lex.Lex(); // eat the (.
2335 if (Lex.getKind() == lltok::rparen) {
2337 } else if (Lex.getKind() == lltok::dotdotdot) {
2341 LocTy TypeLoc = Lex.getLoc();
2342 Type *ArgTy = nullptr;
2346 if (ParseType(ArgTy) ||
2347 ParseOptionalParamAttrs(Attrs)) return true;
2349 if (ArgTy->isVoidTy())
2350 return Error(TypeLoc, "argument can not have void type");
2352 if (Lex.getKind() == lltok::LocalVar) {
2353 Name = Lex.getStrVal();
2357 if (!FunctionType::isValidArgumentType(ArgTy))
2358 return Error(TypeLoc, "invalid type for function argument");
2360 ArgList.emplace_back(TypeLoc, ArgTy,
2361 AttributeSet::get(ArgTy->getContext(), Attrs),
2364 while (EatIfPresent(lltok::comma)) {
2365 // Handle ... at end of arg list.
2366 if (EatIfPresent(lltok::dotdotdot)) {
2371 // Otherwise must be an argument type.
2372 TypeLoc = Lex.getLoc();
2373 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2375 if (ArgTy->isVoidTy())
2376 return Error(TypeLoc, "argument can not have void type");
2378 if (Lex.getKind() == lltok::LocalVar) {
2379 Name = Lex.getStrVal();
2385 if (!ArgTy->isFirstClassType())
2386 return Error(TypeLoc, "invalid type for function argument");
2388 ArgList.emplace_back(TypeLoc, ArgTy,
2389 AttributeSet::get(ArgTy->getContext(), Attrs),
2394 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2397 /// ParseFunctionType
2398 /// ::= Type ArgumentList OptionalAttrs
2399 bool LLParser::ParseFunctionType(Type *&Result) {
2400 assert(Lex.getKind() == lltok::lparen);
2402 if (!FunctionType::isValidReturnType(Result))
2403 return TokError("invalid function return type");
2405 SmallVector<ArgInfo, 8> ArgList;
2407 if (ParseArgumentList(ArgList, isVarArg))
2410 // Reject names on the arguments lists.
2411 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2412 if (!ArgList[i].Name.empty())
2413 return Error(ArgList[i].Loc, "argument name invalid in function type");
2414 if (ArgList[i].Attrs.hasAttributes())
2415 return Error(ArgList[i].Loc,
2416 "argument attributes invalid in function type");
2419 SmallVector<Type*, 16> ArgListTy;
2420 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2421 ArgListTy.push_back(ArgList[i].Ty);
2423 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2427 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2429 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2430 SmallVector<Type*, 8> Elts;
2431 if (ParseStructBody(Elts)) return true;
2433 Result = StructType::get(Context, Elts, Packed);
2437 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2438 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2439 std::pair<Type*, LocTy> &Entry,
2441 // If the type was already defined, diagnose the redefinition.
2442 if (Entry.first && !Entry.second.isValid())
2443 return Error(TypeLoc, "redefinition of type");
2445 // If we have opaque, just return without filling in the definition for the
2446 // struct. This counts as a definition as far as the .ll file goes.
2447 if (EatIfPresent(lltok::kw_opaque)) {
2448 // This type is being defined, so clear the location to indicate this.
2449 Entry.second = SMLoc();
2451 // If this type number has never been uttered, create it.
2453 Entry.first = StructType::create(Context, Name);
2454 ResultTy = Entry.first;
2458 // If the type starts with '<', then it is either a packed struct or a vector.
2459 bool isPacked = EatIfPresent(lltok::less);
2461 // If we don't have a struct, then we have a random type alias, which we
2462 // accept for compatibility with old files. These types are not allowed to be
2463 // forward referenced and not allowed to be recursive.
2464 if (Lex.getKind() != lltok::lbrace) {
2466 return Error(TypeLoc, "forward references to non-struct type");
2470 return ParseArrayVectorType(ResultTy, true);
2471 return ParseType(ResultTy);
2474 // This type is being defined, so clear the location to indicate this.
2475 Entry.second = SMLoc();
2477 // If this type number has never been uttered, create it.
2479 Entry.first = StructType::create(Context, Name);
2481 StructType *STy = cast<StructType>(Entry.first);
2483 SmallVector<Type*, 8> Body;
2484 if (ParseStructBody(Body) ||
2485 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2488 STy->setBody(Body, isPacked);
2493 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2496 /// ::= '{' Type (',' Type)* '}'
2497 /// ::= '<' '{' '}' '>'
2498 /// ::= '<' '{' Type (',' Type)* '}' '>'
2499 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2500 assert(Lex.getKind() == lltok::lbrace);
2501 Lex.Lex(); // Consume the '{'
2503 // Handle the empty struct.
2504 if (EatIfPresent(lltok::rbrace))
2507 LocTy EltTyLoc = Lex.getLoc();
2509 if (ParseType(Ty)) return true;
2512 if (!StructType::isValidElementType(Ty))
2513 return Error(EltTyLoc, "invalid element type for struct");
2515 while (EatIfPresent(lltok::comma)) {
2516 EltTyLoc = Lex.getLoc();
2517 if (ParseType(Ty)) return true;
2519 if (!StructType::isValidElementType(Ty))
2520 return Error(EltTyLoc, "invalid element type for struct");
2525 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2528 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2529 /// token has already been consumed.
2531 /// ::= '[' APSINTVAL 'x' Types ']'
2532 /// ::= '<' APSINTVAL 'x' Types '>'
2533 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2534 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2535 Lex.getAPSIntVal().getBitWidth() > 64)
2536 return TokError("expected number in address space");
2538 LocTy SizeLoc = Lex.getLoc();
2539 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2542 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2545 LocTy TypeLoc = Lex.getLoc();
2546 Type *EltTy = nullptr;
2547 if (ParseType(EltTy)) return true;
2549 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2550 "expected end of sequential type"))
2555 return Error(SizeLoc, "zero element vector is illegal");
2556 if ((unsigned)Size != Size)
2557 return Error(SizeLoc, "size too large for vector");
2558 if (!VectorType::isValidElementType(EltTy))
2559 return Error(TypeLoc, "invalid vector element type");
2560 Result = VectorType::get(EltTy, unsigned(Size));
2562 if (!ArrayType::isValidElementType(EltTy))
2563 return Error(TypeLoc, "invalid array element type");
2564 Result = ArrayType::get(EltTy, Size);
2569 //===----------------------------------------------------------------------===//
2570 // Function Semantic Analysis.
2571 //===----------------------------------------------------------------------===//
2573 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2575 : P(p), F(f), FunctionNumber(functionNumber) {
2577 // Insert unnamed arguments into the NumberedVals list.
2578 for (Argument &A : F.args())
2580 NumberedVals.push_back(&A);
2583 LLParser::PerFunctionState::~PerFunctionState() {
2584 // If there were any forward referenced non-basicblock values, delete them.
2586 for (const auto &P : ForwardRefVals) {
2587 if (isa<BasicBlock>(P.second.first))
2589 P.second.first->replaceAllUsesWith(
2590 UndefValue::get(P.second.first->getType()));
2591 P.second.first->deleteValue();
2594 for (const auto &P : ForwardRefValIDs) {
2595 if (isa<BasicBlock>(P.second.first))
2597 P.second.first->replaceAllUsesWith(
2598 UndefValue::get(P.second.first->getType()));
2599 P.second.first->deleteValue();
2603 bool LLParser::PerFunctionState::FinishFunction() {
2604 if (!ForwardRefVals.empty())
2605 return P.Error(ForwardRefVals.begin()->second.second,
2606 "use of undefined value '%" + ForwardRefVals.begin()->first +
2608 if (!ForwardRefValIDs.empty())
2609 return P.Error(ForwardRefValIDs.begin()->second.second,
2610 "use of undefined value '%" +
2611 Twine(ForwardRefValIDs.begin()->first) + "'");
2615 /// GetVal - Get a value with the specified name or ID, creating a
2616 /// forward reference record if needed. This can return null if the value
2617 /// exists but does not have the right type.
2618 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2620 // Look this name up in the normal function symbol table.
2621 Value *Val = F.getValueSymbolTable()->lookup(Name);
2623 // If this is a forward reference for the value, see if we already created a
2624 // forward ref record.
2626 auto I = ForwardRefVals.find(Name);
2627 if (I != ForwardRefVals.end())
2628 Val = I->second.first;
2631 // If we have the value in the symbol table or fwd-ref table, return it.
2633 if (Val->getType() == Ty) return Val;
2634 if (Ty->isLabelTy())
2635 P.Error(Loc, "'%" + Name + "' is not a basic block");
2637 P.Error(Loc, "'%" + Name + "' defined with type '" +
2638 getTypeString(Val->getType()) + "'");
2642 // Don't make placeholders with invalid type.
2643 if (!Ty->isFirstClassType()) {
2644 P.Error(Loc, "invalid use of a non-first-class type");
2648 // Otherwise, create a new forward reference for this value and remember it.
2650 if (Ty->isLabelTy()) {
2651 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2653 FwdVal = new Argument(Ty, Name);
2656 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2660 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2661 // Look this name up in the normal function symbol table.
2662 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2664 // If this is a forward reference for the value, see if we already created a
2665 // forward ref record.
2667 auto I = ForwardRefValIDs.find(ID);
2668 if (I != ForwardRefValIDs.end())
2669 Val = I->second.first;
2672 // If we have the value in the symbol table or fwd-ref table, return it.
2674 if (Val->getType() == Ty) return Val;
2675 if (Ty->isLabelTy())
2676 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2678 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2679 getTypeString(Val->getType()) + "'");
2683 if (!Ty->isFirstClassType()) {
2684 P.Error(Loc, "invalid use of a non-first-class type");
2688 // Otherwise, create a new forward reference for this value and remember it.
2690 if (Ty->isLabelTy()) {
2691 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2693 FwdVal = new Argument(Ty);
2696 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2700 /// SetInstName - After an instruction is parsed and inserted into its
2701 /// basic block, this installs its name.
2702 bool LLParser::PerFunctionState::SetInstName(int NameID,
2703 const std::string &NameStr,
2704 LocTy NameLoc, Instruction *Inst) {
2705 // If this instruction has void type, it cannot have a name or ID specified.
2706 if (Inst->getType()->isVoidTy()) {
2707 if (NameID != -1 || !NameStr.empty())
2708 return P.Error(NameLoc, "instructions returning void cannot have a name");
2712 // If this was a numbered instruction, verify that the instruction is the
2713 // expected value and resolve any forward references.
2714 if (NameStr.empty()) {
2715 // If neither a name nor an ID was specified, just use the next ID.
2717 NameID = NumberedVals.size();
2719 if (unsigned(NameID) != NumberedVals.size())
2720 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2721 Twine(NumberedVals.size()) + "'");
2723 auto FI = ForwardRefValIDs.find(NameID);
2724 if (FI != ForwardRefValIDs.end()) {
2725 Value *Sentinel = FI->second.first;
2726 if (Sentinel->getType() != Inst->getType())
2727 return P.Error(NameLoc, "instruction forward referenced with type '" +
2728 getTypeString(FI->second.first->getType()) + "'");
2730 Sentinel->replaceAllUsesWith(Inst);
2731 Sentinel->deleteValue();
2732 ForwardRefValIDs.erase(FI);
2735 NumberedVals.push_back(Inst);
2739 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2740 auto FI = ForwardRefVals.find(NameStr);
2741 if (FI != ForwardRefVals.end()) {
2742 Value *Sentinel = FI->second.first;
2743 if (Sentinel->getType() != Inst->getType())
2744 return P.Error(NameLoc, "instruction forward referenced with type '" +
2745 getTypeString(FI->second.first->getType()) + "'");
2747 Sentinel->replaceAllUsesWith(Inst);
2748 Sentinel->deleteValue();
2749 ForwardRefVals.erase(FI);
2752 // Set the name on the instruction.
2753 Inst->setName(NameStr);
2755 if (Inst->getName() != NameStr)
2756 return P.Error(NameLoc, "multiple definition of local value named '" +
2761 /// GetBB - Get a basic block with the specified name or ID, creating a
2762 /// forward reference record if needed.
2763 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2765 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2766 Type::getLabelTy(F.getContext()), Loc));
2769 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2770 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2771 Type::getLabelTy(F.getContext()), Loc));
2774 /// DefineBB - Define the specified basic block, which is either named or
2775 /// unnamed. If there is an error, this returns null otherwise it returns
2776 /// the block being defined.
2777 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2781 BB = GetBB(NumberedVals.size(), Loc);
2783 BB = GetBB(Name, Loc);
2784 if (!BB) return nullptr; // Already diagnosed error.
2786 // Move the block to the end of the function. Forward ref'd blocks are
2787 // inserted wherever they happen to be referenced.
2788 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2790 // Remove the block from forward ref sets.
2792 ForwardRefValIDs.erase(NumberedVals.size());
2793 NumberedVals.push_back(BB);
2795 // BB forward references are already in the function symbol table.
2796 ForwardRefVals.erase(Name);
2802 //===----------------------------------------------------------------------===//
2804 //===----------------------------------------------------------------------===//
2806 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2807 /// type implied. For example, if we parse "4" we don't know what integer type
2808 /// it has. The value will later be combined with its type and checked for
2809 /// sanity. PFS is used to convert function-local operands of metadata (since
2810 /// metadata operands are not just parsed here but also converted to values).
2811 /// PFS can be null when we are not parsing metadata values inside a function.
2812 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2813 ID.Loc = Lex.getLoc();
2814 switch (Lex.getKind()) {
2815 default: return TokError("expected value token");
2816 case lltok::GlobalID: // @42
2817 ID.UIntVal = Lex.getUIntVal();
2818 ID.Kind = ValID::t_GlobalID;
2820 case lltok::GlobalVar: // @foo
2821 ID.StrVal = Lex.getStrVal();
2822 ID.Kind = ValID::t_GlobalName;
2824 case lltok::LocalVarID: // %42
2825 ID.UIntVal = Lex.getUIntVal();
2826 ID.Kind = ValID::t_LocalID;
2828 case lltok::LocalVar: // %foo
2829 ID.StrVal = Lex.getStrVal();
2830 ID.Kind = ValID::t_LocalName;
2833 ID.APSIntVal = Lex.getAPSIntVal();
2834 ID.Kind = ValID::t_APSInt;
2836 case lltok::APFloat:
2837 ID.APFloatVal = Lex.getAPFloatVal();
2838 ID.Kind = ValID::t_APFloat;
2840 case lltok::kw_true:
2841 ID.ConstantVal = ConstantInt::getTrue(Context);
2842 ID.Kind = ValID::t_Constant;
2844 case lltok::kw_false:
2845 ID.ConstantVal = ConstantInt::getFalse(Context);
2846 ID.Kind = ValID::t_Constant;
2848 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2849 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2850 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2851 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2853 case lltok::lbrace: {
2854 // ValID ::= '{' ConstVector '}'
2856 SmallVector<Constant*, 16> Elts;
2857 if (ParseGlobalValueVector(Elts) ||
2858 ParseToken(lltok::rbrace, "expected end of struct constant"))
2861 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2862 ID.UIntVal = Elts.size();
2863 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2864 Elts.size() * sizeof(Elts[0]));
2865 ID.Kind = ValID::t_ConstantStruct;
2869 // ValID ::= '<' ConstVector '>' --> Vector.
2870 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2872 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2874 SmallVector<Constant*, 16> Elts;
2875 LocTy FirstEltLoc = Lex.getLoc();
2876 if (ParseGlobalValueVector(Elts) ||
2878 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2879 ParseToken(lltok::greater, "expected end of constant"))
2882 if (isPackedStruct) {
2883 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2884 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2885 Elts.size() * sizeof(Elts[0]));
2886 ID.UIntVal = Elts.size();
2887 ID.Kind = ValID::t_PackedConstantStruct;
2892 return Error(ID.Loc, "constant vector must not be empty");
2894 if (!Elts[0]->getType()->isIntegerTy() &&
2895 !Elts[0]->getType()->isFloatingPointTy() &&
2896 !Elts[0]->getType()->isPointerTy())
2897 return Error(FirstEltLoc,
2898 "vector elements must have integer, pointer or floating point type");
2900 // Verify that all the vector elements have the same type.
2901 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2902 if (Elts[i]->getType() != Elts[0]->getType())
2903 return Error(FirstEltLoc,
2904 "vector element #" + Twine(i) +
2905 " is not of type '" + getTypeString(Elts[0]->getType()));
2907 ID.ConstantVal = ConstantVector::get(Elts);
2908 ID.Kind = ValID::t_Constant;
2911 case lltok::lsquare: { // Array Constant
2913 SmallVector<Constant*, 16> Elts;
2914 LocTy FirstEltLoc = Lex.getLoc();
2915 if (ParseGlobalValueVector(Elts) ||
2916 ParseToken(lltok::rsquare, "expected end of array constant"))
2919 // Handle empty element.
2921 // Use undef instead of an array because it's inconvenient to determine
2922 // the element type at this point, there being no elements to examine.
2923 ID.Kind = ValID::t_EmptyArray;
2927 if (!Elts[0]->getType()->isFirstClassType())
2928 return Error(FirstEltLoc, "invalid array element type: " +
2929 getTypeString(Elts[0]->getType()));
2931 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2933 // Verify all elements are correct type!
2934 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2935 if (Elts[i]->getType() != Elts[0]->getType())
2936 return Error(FirstEltLoc,
2937 "array element #" + Twine(i) +
2938 " is not of type '" + getTypeString(Elts[0]->getType()));
2941 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2942 ID.Kind = ValID::t_Constant;
2945 case lltok::kw_c: // c "foo"
2947 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2949 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2950 ID.Kind = ValID::t_Constant;
2953 case lltok::kw_asm: {
2954 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2956 bool HasSideEffect, AlignStack, AsmDialect;
2958 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2959 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2960 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2961 ParseStringConstant(ID.StrVal) ||
2962 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2963 ParseToken(lltok::StringConstant, "expected constraint string"))
2965 ID.StrVal2 = Lex.getStrVal();
2966 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2967 (unsigned(AsmDialect)<<2);
2968 ID.Kind = ValID::t_InlineAsm;
2972 case lltok::kw_blockaddress: {
2973 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2978 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2980 ParseToken(lltok::comma, "expected comma in block address expression")||
2981 ParseValID(Label) ||
2982 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2985 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2986 return Error(Fn.Loc, "expected function name in blockaddress");
2987 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2988 return Error(Label.Loc, "expected basic block name in blockaddress");
2990 // Try to find the function (but skip it if it's forward-referenced).
2991 GlobalValue *GV = nullptr;
2992 if (Fn.Kind == ValID::t_GlobalID) {
2993 if (Fn.UIntVal < NumberedVals.size())
2994 GV = NumberedVals[Fn.UIntVal];
2995 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2996 GV = M->getNamedValue(Fn.StrVal);
2998 Function *F = nullptr;
3000 // Confirm that it's actually a function with a definition.
3001 if (!isa<Function>(GV))
3002 return Error(Fn.Loc, "expected function name in blockaddress");
3003 F = cast<Function>(GV);
3004 if (F->isDeclaration())
3005 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3009 // Make a global variable as a placeholder for this reference.
3010 GlobalValue *&FwdRef =
3011 ForwardRefBlockAddresses.insert(std::make_pair(
3013 std::map<ValID, GlobalValue *>()))
3014 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3017 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3018 GlobalValue::InternalLinkage, nullptr, "");
3019 ID.ConstantVal = FwdRef;
3020 ID.Kind = ValID::t_Constant;
3024 // We found the function; now find the basic block. Don't use PFS, since we
3025 // might be inside a constant expression.
3027 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3028 if (Label.Kind == ValID::t_LocalID)
3029 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3031 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3033 return Error(Label.Loc, "referenced value is not a basic block");
3035 if (Label.Kind == ValID::t_LocalID)
3036 return Error(Label.Loc, "cannot take address of numeric label after "
3037 "the function is defined");
3038 BB = dyn_cast_or_null<BasicBlock>(
3039 F->getValueSymbolTable()->lookup(Label.StrVal));
3041 return Error(Label.Loc, "referenced value is not a basic block");
3044 ID.ConstantVal = BlockAddress::get(F, BB);
3045 ID.Kind = ValID::t_Constant;
3049 case lltok::kw_trunc:
3050 case lltok::kw_zext:
3051 case lltok::kw_sext:
3052 case lltok::kw_fptrunc:
3053 case lltok::kw_fpext:
3054 case lltok::kw_bitcast:
3055 case lltok::kw_addrspacecast:
3056 case lltok::kw_uitofp:
3057 case lltok::kw_sitofp:
3058 case lltok::kw_fptoui:
3059 case lltok::kw_fptosi:
3060 case lltok::kw_inttoptr:
3061 case lltok::kw_ptrtoint: {
3062 unsigned Opc = Lex.getUIntVal();
3063 Type *DestTy = nullptr;
3066 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3067 ParseGlobalTypeAndValue(SrcVal) ||
3068 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3069 ParseType(DestTy) ||
3070 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3072 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3073 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3074 getTypeString(SrcVal->getType()) + "' to '" +
3075 getTypeString(DestTy) + "'");
3076 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3078 ID.Kind = ValID::t_Constant;
3081 case lltok::kw_extractvalue: {
3084 SmallVector<unsigned, 4> Indices;
3085 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3086 ParseGlobalTypeAndValue(Val) ||
3087 ParseIndexList(Indices) ||
3088 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3091 if (!Val->getType()->isAggregateType())
3092 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3093 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3094 return Error(ID.Loc, "invalid indices for extractvalue");
3095 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3096 ID.Kind = ValID::t_Constant;
3099 case lltok::kw_insertvalue: {
3101 Constant *Val0, *Val1;
3102 SmallVector<unsigned, 4> Indices;
3103 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3104 ParseGlobalTypeAndValue(Val0) ||
3105 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3106 ParseGlobalTypeAndValue(Val1) ||
3107 ParseIndexList(Indices) ||
3108 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3110 if (!Val0->getType()->isAggregateType())
3111 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3113 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3115 return Error(ID.Loc, "invalid indices for insertvalue");
3116 if (IndexedType != Val1->getType())
3117 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3118 getTypeString(Val1->getType()) +
3119 "' instead of '" + getTypeString(IndexedType) +
3121 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3122 ID.Kind = ValID::t_Constant;
3125 case lltok::kw_icmp:
3126 case lltok::kw_fcmp: {
3127 unsigned PredVal, Opc = Lex.getUIntVal();
3128 Constant *Val0, *Val1;
3130 if (ParseCmpPredicate(PredVal, Opc) ||
3131 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3132 ParseGlobalTypeAndValue(Val0) ||
3133 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3134 ParseGlobalTypeAndValue(Val1) ||
3135 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3138 if (Val0->getType() != Val1->getType())
3139 return Error(ID.Loc, "compare operands must have the same type");
3141 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3143 if (Opc == Instruction::FCmp) {
3144 if (!Val0->getType()->isFPOrFPVectorTy())
3145 return Error(ID.Loc, "fcmp requires floating point operands");
3146 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3148 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3149 if (!Val0->getType()->isIntOrIntVectorTy() &&
3150 !Val0->getType()->isPtrOrPtrVectorTy())
3151 return Error(ID.Loc, "icmp requires pointer or integer operands");
3152 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3154 ID.Kind = ValID::t_Constant;
3158 // Binary Operators.
3160 case lltok::kw_fadd:
3162 case lltok::kw_fsub:
3164 case lltok::kw_fmul:
3165 case lltok::kw_udiv:
3166 case lltok::kw_sdiv:
3167 case lltok::kw_fdiv:
3168 case lltok::kw_urem:
3169 case lltok::kw_srem:
3170 case lltok::kw_frem:
3172 case lltok::kw_lshr:
3173 case lltok::kw_ashr: {
3177 unsigned Opc = Lex.getUIntVal();
3178 Constant *Val0, *Val1;
3180 LocTy ModifierLoc = Lex.getLoc();
3181 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3182 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3183 if (EatIfPresent(lltok::kw_nuw))
3185 if (EatIfPresent(lltok::kw_nsw)) {
3187 if (EatIfPresent(lltok::kw_nuw))
3190 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3191 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3192 if (EatIfPresent(lltok::kw_exact))
3195 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3196 ParseGlobalTypeAndValue(Val0) ||
3197 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3198 ParseGlobalTypeAndValue(Val1) ||
3199 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3201 if (Val0->getType() != Val1->getType())
3202 return Error(ID.Loc, "operands of constexpr must have same type");
3203 if (!Val0->getType()->isIntOrIntVectorTy()) {
3205 return Error(ModifierLoc, "nuw only applies to integer operations");
3207 return Error(ModifierLoc, "nsw only applies to integer operations");
3209 // Check that the type is valid for the operator.
3211 case Instruction::Add:
3212 case Instruction::Sub:
3213 case Instruction::Mul:
3214 case Instruction::UDiv:
3215 case Instruction::SDiv:
3216 case Instruction::URem:
3217 case Instruction::SRem:
3218 case Instruction::Shl:
3219 case Instruction::AShr:
3220 case Instruction::LShr:
3221 if (!Val0->getType()->isIntOrIntVectorTy())
3222 return Error(ID.Loc, "constexpr requires integer operands");
3224 case Instruction::FAdd:
3225 case Instruction::FSub:
3226 case Instruction::FMul:
3227 case Instruction::FDiv:
3228 case Instruction::FRem:
3229 if (!Val0->getType()->isFPOrFPVectorTy())
3230 return Error(ID.Loc, "constexpr requires fp operands");
3232 default: llvm_unreachable("Unknown binary operator!");
3235 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3236 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3237 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3238 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3240 ID.Kind = ValID::t_Constant;
3244 // Logical Operations
3247 case lltok::kw_xor: {
3248 unsigned Opc = Lex.getUIntVal();
3249 Constant *Val0, *Val1;
3251 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3252 ParseGlobalTypeAndValue(Val0) ||
3253 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3254 ParseGlobalTypeAndValue(Val1) ||
3255 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3257 if (Val0->getType() != Val1->getType())
3258 return Error(ID.Loc, "operands of constexpr must have same type");
3259 if (!Val0->getType()->isIntOrIntVectorTy())
3260 return Error(ID.Loc,
3261 "constexpr requires integer or integer vector operands");
3262 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3263 ID.Kind = ValID::t_Constant;
3267 case lltok::kw_getelementptr:
3268 case lltok::kw_shufflevector:
3269 case lltok::kw_insertelement:
3270 case lltok::kw_extractelement:
3271 case lltok::kw_select: {
3272 unsigned Opc = Lex.getUIntVal();
3273 SmallVector<Constant*, 16> Elts;
3274 bool InBounds = false;
3278 if (Opc == Instruction::GetElementPtr)
3279 InBounds = EatIfPresent(lltok::kw_inbounds);
3281 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3284 LocTy ExplicitTypeLoc = Lex.getLoc();
3285 if (Opc == Instruction::GetElementPtr) {
3286 if (ParseType(Ty) ||
3287 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3291 Optional<unsigned> InRangeOp;
3292 if (ParseGlobalValueVector(
3293 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3294 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3297 if (Opc == Instruction::GetElementPtr) {
3298 if (Elts.size() == 0 ||
3299 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3300 return Error(ID.Loc, "base of getelementptr must be a pointer");
3302 Type *BaseType = Elts[0]->getType();
3303 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3304 if (Ty != BasePointerType->getElementType())
3307 "explicit pointee type doesn't match operand's pointee type");
3310 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3312 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3313 for (Constant *Val : Indices) {
3314 Type *ValTy = Val->getType();
3315 if (!ValTy->isIntOrIntVectorTy())
3316 return Error(ID.Loc, "getelementptr index must be an integer");
3317 if (ValTy->isVectorTy()) {
3318 unsigned ValNumEl = ValTy->getVectorNumElements();
3319 if (GEPWidth && (ValNumEl != GEPWidth))
3322 "getelementptr vector index has a wrong number of elements");
3323 // GEPWidth may have been unknown because the base is a scalar,
3324 // but it is known now.
3325 GEPWidth = ValNumEl;
3329 SmallPtrSet<Type*, 4> Visited;
3330 if (!Indices.empty() && !Ty->isSized(&Visited))
3331 return Error(ID.Loc, "base element of getelementptr must be sized");
3333 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3334 return Error(ID.Loc, "invalid getelementptr indices");
3337 if (*InRangeOp == 0)
3338 return Error(ID.Loc,
3339 "inrange keyword may not appear on pointer operand");
3343 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3344 InBounds, InRangeOp);
3345 } else if (Opc == Instruction::Select) {
3346 if (Elts.size() != 3)
3347 return Error(ID.Loc, "expected three operands to select");
3348 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3350 return Error(ID.Loc, Reason);
3351 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3352 } else if (Opc == Instruction::ShuffleVector) {
3353 if (Elts.size() != 3)
3354 return Error(ID.Loc, "expected three operands to shufflevector");
3355 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3356 return Error(ID.Loc, "invalid operands to shufflevector");
3358 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3359 } else if (Opc == Instruction::ExtractElement) {
3360 if (Elts.size() != 2)
3361 return Error(ID.Loc, "expected two operands to extractelement");
3362 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3363 return Error(ID.Loc, "invalid extractelement operands");
3364 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3366 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3367 if (Elts.size() != 3)
3368 return Error(ID.Loc, "expected three operands to insertelement");
3369 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3370 return Error(ID.Loc, "invalid insertelement operands");
3372 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3375 ID.Kind = ValID::t_Constant;
3384 /// ParseGlobalValue - Parse a global value with the specified type.
3385 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3389 bool Parsed = ParseValID(ID) ||
3390 ConvertValIDToValue(Ty, ID, V, nullptr);
3391 if (V && !(C = dyn_cast<Constant>(V)))
3392 return Error(ID.Loc, "global values must be constants");
3396 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3398 return ParseType(Ty) ||
3399 ParseGlobalValue(Ty, V);
3402 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3405 LocTy KwLoc = Lex.getLoc();
3406 if (!EatIfPresent(lltok::kw_comdat))
3409 if (EatIfPresent(lltok::lparen)) {
3410 if (Lex.getKind() != lltok::ComdatVar)
3411 return TokError("expected comdat variable");
3412 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3414 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3417 if (GlobalName.empty())
3418 return TokError("comdat cannot be unnamed");
3419 C = getComdat(GlobalName, KwLoc);
3425 /// ParseGlobalValueVector
3427 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3428 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3429 Optional<unsigned> *InRangeOp) {
3431 if (Lex.getKind() == lltok::rbrace ||
3432 Lex.getKind() == lltok::rsquare ||
3433 Lex.getKind() == lltok::greater ||
3434 Lex.getKind() == lltok::rparen)
3438 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3439 *InRangeOp = Elts.size();
3442 if (ParseGlobalTypeAndValue(C)) return true;
3444 } while (EatIfPresent(lltok::comma));
3449 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3450 SmallVector<Metadata *, 16> Elts;
3451 if (ParseMDNodeVector(Elts))
3454 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3461 /// ::= !DILocation(...)
3462 bool LLParser::ParseMDNode(MDNode *&N) {
3463 if (Lex.getKind() == lltok::MetadataVar)
3464 return ParseSpecializedMDNode(N);
3466 return ParseToken(lltok::exclaim, "expected '!' here") ||
3470 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3472 if (Lex.getKind() == lltok::lbrace)
3473 return ParseMDTuple(N);
3476 return ParseMDNodeID(N);
3481 /// Structure to represent an optional metadata field.
3482 template <class FieldTy> struct MDFieldImpl {
3483 typedef MDFieldImpl ImplTy;
3487 void assign(FieldTy Val) {
3489 this->Val = std::move(Val);
3492 explicit MDFieldImpl(FieldTy Default)
3493 : Val(std::move(Default)), Seen(false) {}
3496 /// Structure to represent an optional metadata field that
3497 /// can be of either type (A or B) and encapsulates the
3498 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3499 /// to reimplement the specifics for representing each Field.
3500 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3501 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3512 void assign(FieldTypeA A) {
3514 this->A = std::move(A);
3518 void assign(FieldTypeB B) {
3520 this->B = std::move(B);
3524 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3525 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3526 WhatIs(IsInvalid) {}
3529 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3532 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3533 : ImplTy(Default), Max(Max) {}
3536 struct LineField : public MDUnsignedField {
3537 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3540 struct ColumnField : public MDUnsignedField {
3541 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3544 struct DwarfTagField : public MDUnsignedField {
3545 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3546 DwarfTagField(dwarf::Tag DefaultTag)
3547 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3550 struct DwarfMacinfoTypeField : public MDUnsignedField {
3551 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3552 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3553 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3556 struct DwarfAttEncodingField : public MDUnsignedField {
3557 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3560 struct DwarfVirtualityField : public MDUnsignedField {
3561 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3564 struct DwarfLangField : public MDUnsignedField {
3565 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3568 struct DwarfCCField : public MDUnsignedField {
3569 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3572 struct EmissionKindField : public MDUnsignedField {
3573 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3576 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3577 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3580 struct MDSignedField : public MDFieldImpl<int64_t> {
3584 MDSignedField(int64_t Default = 0)
3585 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3586 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3587 : ImplTy(Default), Min(Min), Max(Max) {}
3590 struct MDBoolField : public MDFieldImpl<bool> {
3591 MDBoolField(bool Default = false) : ImplTy(Default) {}
3594 struct MDField : public MDFieldImpl<Metadata *> {
3597 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3600 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3601 MDConstant() : ImplTy(nullptr) {}
3604 struct MDStringField : public MDFieldImpl<MDString *> {
3606 MDStringField(bool AllowEmpty = true)
3607 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3610 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3611 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3614 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3615 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3616 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3619 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3620 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3621 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3623 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3624 bool AllowNull = true)
3625 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3627 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3628 bool isMDField() const { return WhatIs == IsTypeB; }
3629 int64_t getMDSignedValue() const {
3630 assert(isMDSignedField() && "Wrong field type");
3633 Metadata *getMDFieldValue() const {
3634 assert(isMDField() && "Wrong field type");
3639 } // end anonymous namespace
3644 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3645 MDUnsignedField &Result) {
3646 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3647 return TokError("expected unsigned integer");
3649 auto &U = Lex.getAPSIntVal();
3650 if (U.ugt(Result.Max))
3651 return TokError("value for '" + Name + "' too large, limit is " +
3653 Result.assign(U.getZExtValue());
3654 assert(Result.Val <= Result.Max && "Expected value in range");
3660 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3661 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3664 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3665 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3669 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3670 if (Lex.getKind() == lltok::APSInt)
3671 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3673 if (Lex.getKind() != lltok::DwarfTag)
3674 return TokError("expected DWARF tag");
3676 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3677 if (Tag == dwarf::DW_TAG_invalid)
3678 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3679 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3687 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3688 DwarfMacinfoTypeField &Result) {
3689 if (Lex.getKind() == lltok::APSInt)
3690 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3692 if (Lex.getKind() != lltok::DwarfMacinfo)
3693 return TokError("expected DWARF macinfo type");
3695 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3696 if (Macinfo == dwarf::DW_MACINFO_invalid)
3698 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3699 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3701 Result.assign(Macinfo);
3707 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3708 DwarfVirtualityField &Result) {
3709 if (Lex.getKind() == lltok::APSInt)
3710 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3712 if (Lex.getKind() != lltok::DwarfVirtuality)
3713 return TokError("expected DWARF virtuality code");
3715 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3716 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3717 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3718 Lex.getStrVal() + "'");
3719 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3720 Result.assign(Virtuality);
3726 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3727 if (Lex.getKind() == lltok::APSInt)
3728 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3730 if (Lex.getKind() != lltok::DwarfLang)
3731 return TokError("expected DWARF language");
3733 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3735 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3737 assert(Lang <= Result.Max && "Expected valid DWARF language");
3738 Result.assign(Lang);
3744 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3745 if (Lex.getKind() == lltok::APSInt)
3746 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3748 if (Lex.getKind() != lltok::DwarfCC)
3749 return TokError("expected DWARF calling convention");
3751 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3753 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3755 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3762 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3763 if (Lex.getKind() == lltok::APSInt)
3764 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3766 if (Lex.getKind() != lltok::EmissionKind)
3767 return TokError("expected emission kind");
3769 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3771 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3773 assert(*Kind <= Result.Max && "Expected valid emission kind");
3774 Result.assign(*Kind);
3780 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3781 DwarfAttEncodingField &Result) {
3782 if (Lex.getKind() == lltok::APSInt)
3783 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3785 if (Lex.getKind() != lltok::DwarfAttEncoding)
3786 return TokError("expected DWARF type attribute encoding");
3788 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3790 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3791 Lex.getStrVal() + "'");
3792 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3793 Result.assign(Encoding);
3800 /// ::= DIFlagVector
3801 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3803 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3805 // Parser for a single flag.
3806 auto parseFlag = [&](DINode::DIFlags &Val) {
3807 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3808 uint32_t TempVal = static_cast<uint32_t>(Val);
3809 bool Res = ParseUInt32(TempVal);
3810 Val = static_cast<DINode::DIFlags>(TempVal);
3814 if (Lex.getKind() != lltok::DIFlag)
3815 return TokError("expected debug info flag");
3817 Val = DINode::getFlag(Lex.getStrVal());
3819 return TokError(Twine("invalid debug info flag flag '") +
3820 Lex.getStrVal() + "'");
3825 // Parse the flags and combine them together.
3826 DINode::DIFlags Combined = DINode::FlagZero;
3828 DINode::DIFlags Val;
3832 } while (EatIfPresent(lltok::bar));
3834 Result.assign(Combined);
3839 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3840 MDSignedField &Result) {
3841 if (Lex.getKind() != lltok::APSInt)
3842 return TokError("expected signed integer");
3844 auto &S = Lex.getAPSIntVal();
3846 return TokError("value for '" + Name + "' too small, limit is " +
3849 return TokError("value for '" + Name + "' too large, limit is " +
3851 Result.assign(S.getExtValue());
3852 assert(Result.Val >= Result.Min && "Expected value in range");
3853 assert(Result.Val <= Result.Max && "Expected value in range");
3859 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3860 switch (Lex.getKind()) {
3862 return TokError("expected 'true' or 'false'");
3863 case lltok::kw_true:
3864 Result.assign(true);
3866 case lltok::kw_false:
3867 Result.assign(false);
3875 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3876 if (Lex.getKind() == lltok::kw_null) {
3877 if (!Result.AllowNull)
3878 return TokError("'" + Name + "' cannot be null");
3880 Result.assign(nullptr);
3885 if (ParseMetadata(MD, nullptr))
3893 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3894 MDSignedOrMDField &Result) {
3895 // Try to parse a signed int.
3896 if (Lex.getKind() == lltok::APSInt) {
3897 MDSignedField Res = Result.A;
3898 if (!ParseMDField(Loc, Name, Res)) {
3905 // Otherwise, try to parse as an MDField.
3906 MDField Res = Result.B;
3907 if (!ParseMDField(Loc, Name, Res)) {
3916 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3917 LocTy ValueLoc = Lex.getLoc();
3919 if (ParseStringConstant(S))
3922 if (!Result.AllowEmpty && S.empty())
3923 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3925 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3930 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3931 SmallVector<Metadata *, 4> MDs;
3932 if (ParseMDNodeVector(MDs))
3935 Result.assign(std::move(MDs));
3940 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3941 ChecksumKindField &Result) {
3942 if (Lex.getKind() != lltok::ChecksumKind)
3944 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3946 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3948 Result.assign(CSKind);
3953 } // end namespace llvm
3955 template <class ParserTy>
3956 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3958 if (Lex.getKind() != lltok::LabelStr)
3959 return TokError("expected field label here");
3963 } while (EatIfPresent(lltok::comma));
3968 template <class ParserTy>
3969 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3970 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3973 if (ParseToken(lltok::lparen, "expected '(' here"))
3975 if (Lex.getKind() != lltok::rparen)
3976 if (ParseMDFieldsImplBody(parseField))
3979 ClosingLoc = Lex.getLoc();
3980 return ParseToken(lltok::rparen, "expected ')' here");
3983 template <class FieldTy>
3984 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3986 return TokError("field '" + Name + "' cannot be specified more than once");
3988 LocTy Loc = Lex.getLoc();
3990 return ParseMDField(Loc, Name, Result);
3993 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3994 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3996 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3997 if (Lex.getStrVal() == #CLASS) \
3998 return Parse##CLASS(N, IsDistinct);
3999 #include "llvm/IR/Metadata.def"
4001 return TokError("expected metadata type");
4004 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4005 #define NOP_FIELD(NAME, TYPE, INIT)
4006 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4008 return Error(ClosingLoc, "missing required field '" #NAME "'");
4009 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4010 if (Lex.getStrVal() == #NAME) \
4011 return ParseMDField(#NAME, NAME);
4012 #define PARSE_MD_FIELDS() \
4013 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4016 if (ParseMDFieldsImpl([&]() -> bool { \
4017 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4018 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4021 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4023 #define GET_OR_DISTINCT(CLASS, ARGS) \
4024 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4026 /// ParseDILocationFields:
4027 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
4028 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4029 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4030 OPTIONAL(line, LineField, ); \
4031 OPTIONAL(column, ColumnField, ); \
4032 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4033 OPTIONAL(inlinedAt, MDField, );
4035 #undef VISIT_MD_FIELDS
4037 Result = GET_OR_DISTINCT(
4038 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
4042 /// ParseGenericDINode:
4043 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4044 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4045 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4046 REQUIRED(tag, DwarfTagField, ); \
4047 OPTIONAL(header, MDStringField, ); \
4048 OPTIONAL(operands, MDFieldList, );
4050 #undef VISIT_MD_FIELDS
4052 Result = GET_OR_DISTINCT(GenericDINode,
4053 (Context, tag.Val, header.Val, operands.Val));
4057 /// ParseDISubrange:
4058 /// ::= !DISubrange(count: 30, lowerBound: 2)
4059 /// ::= !DISubrange(count: !node, lowerBound: 2)
4060 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4061 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4062 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4063 OPTIONAL(lowerBound, MDSignedField, );
4065 #undef VISIT_MD_FIELDS
4067 if (count.isMDSignedField())
4068 Result = GET_OR_DISTINCT(
4069 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4070 else if (count.isMDField())
4071 Result = GET_OR_DISTINCT(
4072 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4079 /// ParseDIEnumerator:
4080 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
4081 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4082 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4083 REQUIRED(name, MDStringField, ); \
4084 REQUIRED(value, MDSignedField, );
4086 #undef VISIT_MD_FIELDS
4088 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
4092 /// ParseDIBasicType:
4093 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
4094 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4095 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4096 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4097 OPTIONAL(name, MDStringField, ); \
4098 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4099 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4100 OPTIONAL(encoding, DwarfAttEncodingField, );
4102 #undef VISIT_MD_FIELDS
4104 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4105 align.Val, encoding.Val));
4109 /// ParseDIDerivedType:
4110 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4111 /// line: 7, scope: !1, baseType: !2, size: 32,
4112 /// align: 32, offset: 0, flags: 0, extraData: !3,
4113 /// dwarfAddressSpace: 3)
4114 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4115 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4116 REQUIRED(tag, DwarfTagField, ); \
4117 OPTIONAL(name, MDStringField, ); \
4118 OPTIONAL(file, MDField, ); \
4119 OPTIONAL(line, LineField, ); \
4120 OPTIONAL(scope, MDField, ); \
4121 REQUIRED(baseType, MDField, ); \
4122 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4123 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4124 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4125 OPTIONAL(flags, DIFlagField, ); \
4126 OPTIONAL(extraData, MDField, ); \
4127 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4129 #undef VISIT_MD_FIELDS
4131 Optional<unsigned> DWARFAddressSpace;
4132 if (dwarfAddressSpace.Val != UINT32_MAX)
4133 DWARFAddressSpace = dwarfAddressSpace.Val;
4135 Result = GET_OR_DISTINCT(DIDerivedType,
4136 (Context, tag.Val, name.Val, file.Val, line.Val,
4137 scope.Val, baseType.Val, size.Val, align.Val,
4138 offset.Val, DWARFAddressSpace, flags.Val,
4143 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4144 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4145 REQUIRED(tag, DwarfTagField, ); \
4146 OPTIONAL(name, MDStringField, ); \
4147 OPTIONAL(file, MDField, ); \
4148 OPTIONAL(line, LineField, ); \
4149 OPTIONAL(scope, MDField, ); \
4150 OPTIONAL(baseType, MDField, ); \
4151 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4152 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4153 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4154 OPTIONAL(flags, DIFlagField, ); \
4155 OPTIONAL(elements, MDField, ); \
4156 OPTIONAL(runtimeLang, DwarfLangField, ); \
4157 OPTIONAL(vtableHolder, MDField, ); \
4158 OPTIONAL(templateParams, MDField, ); \
4159 OPTIONAL(identifier, MDStringField, ); \
4160 OPTIONAL(discriminator, MDField, );
4162 #undef VISIT_MD_FIELDS
4164 // If this has an identifier try to build an ODR type.
4166 if (auto *CT = DICompositeType::buildODRType(
4167 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4168 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4169 elements.Val, runtimeLang.Val, vtableHolder.Val,
4170 templateParams.Val, discriminator.Val)) {
4175 // Create a new node, and save it in the context if it belongs in the type
4177 Result = GET_OR_DISTINCT(
4179 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4180 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4181 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4182 discriminator.Val));
4186 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4187 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4188 OPTIONAL(flags, DIFlagField, ); \
4189 OPTIONAL(cc, DwarfCCField, ); \
4190 REQUIRED(types, MDField, );
4192 #undef VISIT_MD_FIELDS
4194 Result = GET_OR_DISTINCT(DISubroutineType,
4195 (Context, flags.Val, cc.Val, types.Val));
4199 /// ParseDIFileType:
4200 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
4201 /// checksumkind: CSK_MD5,
4202 /// checksum: "000102030405060708090a0b0c0d0e0f")
4203 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4204 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4205 REQUIRED(filename, MDStringField, ); \
4206 REQUIRED(directory, MDStringField, ); \
4207 OPTIONAL(checksumkind, ChecksumKindField, ); \
4208 OPTIONAL(checksum, MDStringField, );
4210 #undef VISIT_MD_FIELDS
4212 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4213 checksumkind.Val, checksum.Val));
4217 /// ParseDICompileUnit:
4218 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4219 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4220 /// splitDebugFilename: "abc.debug",
4221 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4222 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4223 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4225 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4227 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4228 REQUIRED(language, DwarfLangField, ); \
4229 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4230 OPTIONAL(producer, MDStringField, ); \
4231 OPTIONAL(isOptimized, MDBoolField, ); \
4232 OPTIONAL(flags, MDStringField, ); \
4233 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4234 OPTIONAL(splitDebugFilename, MDStringField, ); \
4235 OPTIONAL(emissionKind, EmissionKindField, ); \
4236 OPTIONAL(enums, MDField, ); \
4237 OPTIONAL(retainedTypes, MDField, ); \
4238 OPTIONAL(globals, MDField, ); \
4239 OPTIONAL(imports, MDField, ); \
4240 OPTIONAL(macros, MDField, ); \
4241 OPTIONAL(dwoId, MDUnsignedField, ); \
4242 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4243 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4244 OPTIONAL(gnuPubnames, MDBoolField, = false);
4246 #undef VISIT_MD_FIELDS
4248 Result = DICompileUnit::getDistinct(
4249 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4250 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4251 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4252 splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
4256 /// ParseDISubprogram:
4257 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4258 /// file: !1, line: 7, type: !2, isLocal: false,
4259 /// isDefinition: true, scopeLine: 8, containingType: !3,
4260 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4261 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4262 /// isOptimized: false, templateParams: !4, declaration: !5,
4263 /// variables: !6, thrownTypes: !7)
4264 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4265 auto Loc = Lex.getLoc();
4266 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4267 OPTIONAL(scope, MDField, ); \
4268 OPTIONAL(name, MDStringField, ); \
4269 OPTIONAL(linkageName, MDStringField, ); \
4270 OPTIONAL(file, MDField, ); \
4271 OPTIONAL(line, LineField, ); \
4272 OPTIONAL(type, MDField, ); \
4273 OPTIONAL(isLocal, MDBoolField, ); \
4274 OPTIONAL(isDefinition, MDBoolField, (true)); \
4275 OPTIONAL(scopeLine, LineField, ); \
4276 OPTIONAL(containingType, MDField, ); \
4277 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4278 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4279 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4280 OPTIONAL(flags, DIFlagField, ); \
4281 OPTIONAL(isOptimized, MDBoolField, ); \
4282 OPTIONAL(unit, MDField, ); \
4283 OPTIONAL(templateParams, MDField, ); \
4284 OPTIONAL(declaration, MDField, ); \
4285 OPTIONAL(variables, MDField, ); \
4286 OPTIONAL(thrownTypes, MDField, );
4288 #undef VISIT_MD_FIELDS
4290 if (isDefinition.Val && !IsDistinct)
4293 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4295 Result = GET_OR_DISTINCT(
4297 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4298 type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
4299 containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
4300 flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
4301 declaration.Val, variables.Val, thrownTypes.Val));
4305 /// ParseDILexicalBlock:
4306 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4307 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4308 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4309 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4310 OPTIONAL(file, MDField, ); \
4311 OPTIONAL(line, LineField, ); \
4312 OPTIONAL(column, ColumnField, );
4314 #undef VISIT_MD_FIELDS
4316 Result = GET_OR_DISTINCT(
4317 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4321 /// ParseDILexicalBlockFile:
4322 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4323 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4324 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4325 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4326 OPTIONAL(file, MDField, ); \
4327 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4329 #undef VISIT_MD_FIELDS
4331 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4332 (Context, scope.Val, file.Val, discriminator.Val));
4336 /// ParseDINamespace:
4337 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4338 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4339 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4340 REQUIRED(scope, MDField, ); \
4341 OPTIONAL(name, MDStringField, ); \
4342 OPTIONAL(exportSymbols, MDBoolField, );
4344 #undef VISIT_MD_FIELDS
4346 Result = GET_OR_DISTINCT(DINamespace,
4347 (Context, scope.Val, name.Val, exportSymbols.Val));
4352 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4353 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4354 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4355 REQUIRED(type, DwarfMacinfoTypeField, ); \
4356 OPTIONAL(line, LineField, ); \
4357 REQUIRED(name, MDStringField, ); \
4358 OPTIONAL(value, MDStringField, );
4360 #undef VISIT_MD_FIELDS
4362 Result = GET_OR_DISTINCT(DIMacro,
4363 (Context, type.Val, line.Val, name.Val, value.Val));
4367 /// ParseDIMacroFile:
4368 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4369 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4370 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4371 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4372 OPTIONAL(line, LineField, ); \
4373 REQUIRED(file, MDField, ); \
4374 OPTIONAL(nodes, MDField, );
4376 #undef VISIT_MD_FIELDS
4378 Result = GET_OR_DISTINCT(DIMacroFile,
4379 (Context, type.Val, line.Val, file.Val, nodes.Val));
4384 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4385 /// includePath: "/usr/include", isysroot: "/")
4386 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4387 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4388 REQUIRED(scope, MDField, ); \
4389 REQUIRED(name, MDStringField, ); \
4390 OPTIONAL(configMacros, MDStringField, ); \
4391 OPTIONAL(includePath, MDStringField, ); \
4392 OPTIONAL(isysroot, MDStringField, );
4394 #undef VISIT_MD_FIELDS
4396 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4397 configMacros.Val, includePath.Val, isysroot.Val));
4401 /// ParseDITemplateTypeParameter:
4402 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4403 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4404 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4405 OPTIONAL(name, MDStringField, ); \
4406 REQUIRED(type, MDField, );
4408 #undef VISIT_MD_FIELDS
4411 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4415 /// ParseDITemplateValueParameter:
4416 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4417 /// name: "V", type: !1, value: i32 7)
4418 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4419 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4420 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4421 OPTIONAL(name, MDStringField, ); \
4422 OPTIONAL(type, MDField, ); \
4423 REQUIRED(value, MDField, );
4425 #undef VISIT_MD_FIELDS
4427 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4428 (Context, tag.Val, name.Val, type.Val, value.Val));
4432 /// ParseDIGlobalVariable:
4433 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4434 /// file: !1, line: 7, type: !2, isLocal: false,
4435 /// isDefinition: true, declaration: !3, align: 8)
4436 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4437 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4438 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4439 OPTIONAL(scope, MDField, ); \
4440 OPTIONAL(linkageName, MDStringField, ); \
4441 OPTIONAL(file, MDField, ); \
4442 OPTIONAL(line, LineField, ); \
4443 OPTIONAL(type, MDField, ); \
4444 OPTIONAL(isLocal, MDBoolField, ); \
4445 OPTIONAL(isDefinition, MDBoolField, (true)); \
4446 OPTIONAL(declaration, MDField, ); \
4447 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4449 #undef VISIT_MD_FIELDS
4451 Result = GET_OR_DISTINCT(DIGlobalVariable,
4452 (Context, scope.Val, name.Val, linkageName.Val,
4453 file.Val, line.Val, type.Val, isLocal.Val,
4454 isDefinition.Val, declaration.Val, align.Val));
4458 /// ParseDILocalVariable:
4459 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4460 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4462 /// ::= !DILocalVariable(scope: !0, name: "foo",
4463 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4465 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4466 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4467 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4468 OPTIONAL(name, MDStringField, ); \
4469 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4470 OPTIONAL(file, MDField, ); \
4471 OPTIONAL(line, LineField, ); \
4472 OPTIONAL(type, MDField, ); \
4473 OPTIONAL(flags, DIFlagField, ); \
4474 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4476 #undef VISIT_MD_FIELDS
4478 Result = GET_OR_DISTINCT(DILocalVariable,
4479 (Context, scope.Val, name.Val, file.Val, line.Val,
4480 type.Val, arg.Val, flags.Val, align.Val));
4484 /// ParseDIExpression:
4485 /// ::= !DIExpression(0, 7, -1)
4486 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4487 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4490 if (ParseToken(lltok::lparen, "expected '(' here"))
4493 SmallVector<uint64_t, 8> Elements;
4494 if (Lex.getKind() != lltok::rparen)
4496 if (Lex.getKind() == lltok::DwarfOp) {
4497 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4499 Elements.push_back(Op);
4502 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4505 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4506 return TokError("expected unsigned integer");
4508 auto &U = Lex.getAPSIntVal();
4509 if (U.ugt(UINT64_MAX))
4510 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4511 Elements.push_back(U.getZExtValue());
4513 } while (EatIfPresent(lltok::comma));
4515 if (ParseToken(lltok::rparen, "expected ')' here"))
4518 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4522 /// ParseDIGlobalVariableExpression:
4523 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4524 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4526 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4527 REQUIRED(var, MDField, ); \
4528 REQUIRED(expr, MDField, );
4530 #undef VISIT_MD_FIELDS
4533 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4537 /// ParseDIObjCProperty:
4538 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4539 /// getter: "getFoo", attributes: 7, type: !2)
4540 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4541 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4542 OPTIONAL(name, MDStringField, ); \
4543 OPTIONAL(file, MDField, ); \
4544 OPTIONAL(line, LineField, ); \
4545 OPTIONAL(setter, MDStringField, ); \
4546 OPTIONAL(getter, MDStringField, ); \
4547 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4548 OPTIONAL(type, MDField, );
4550 #undef VISIT_MD_FIELDS
4552 Result = GET_OR_DISTINCT(DIObjCProperty,
4553 (Context, name.Val, file.Val, line.Val, setter.Val,
4554 getter.Val, attributes.Val, type.Val));
4558 /// ParseDIImportedEntity:
4559 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4560 /// line: 7, name: "foo")
4561 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4562 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4563 REQUIRED(tag, DwarfTagField, ); \
4564 REQUIRED(scope, MDField, ); \
4565 OPTIONAL(entity, MDField, ); \
4566 OPTIONAL(file, MDField, ); \
4567 OPTIONAL(line, LineField, ); \
4568 OPTIONAL(name, MDStringField, );
4570 #undef VISIT_MD_FIELDS
4572 Result = GET_OR_DISTINCT(
4574 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
4578 #undef PARSE_MD_FIELD
4580 #undef REQUIRE_FIELD
4581 #undef DECLARE_FIELD
4583 /// ParseMetadataAsValue
4584 /// ::= metadata i32 %local
4585 /// ::= metadata i32 @global
4586 /// ::= metadata i32 7
4588 /// ::= metadata !{...}
4589 /// ::= metadata !"string"
4590 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4591 // Note: the type 'metadata' has already been parsed.
4593 if (ParseMetadata(MD, &PFS))
4596 V = MetadataAsValue::get(Context, MD);
4600 /// ParseValueAsMetadata
4604 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4605 PerFunctionState *PFS) {
4608 if (ParseType(Ty, TypeMsg, Loc))
4610 if (Ty->isMetadataTy())
4611 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4614 if (ParseValue(Ty, V, PFS))
4617 MD = ValueAsMetadata::get(V);
4628 /// ::= !DILocation(...)
4629 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4630 if (Lex.getKind() == lltok::MetadataVar) {
4632 if (ParseSpecializedMDNode(N))
4640 if (Lex.getKind() != lltok::exclaim)
4641 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4644 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4648 // ::= '!' STRINGCONSTANT
4649 if (Lex.getKind() == lltok::StringConstant) {
4651 if (ParseMDString(S))
4661 if (ParseMDNodeTail(N))
4667 //===----------------------------------------------------------------------===//
4668 // Function Parsing.
4669 //===----------------------------------------------------------------------===//
4671 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4672 PerFunctionState *PFS) {
4673 if (Ty->isFunctionTy())
4674 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4677 case ValID::t_LocalID:
4678 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4679 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4680 return V == nullptr;
4681 case ValID::t_LocalName:
4682 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4683 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4684 return V == nullptr;
4685 case ValID::t_InlineAsm: {
4686 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4687 return Error(ID.Loc, "invalid type for inline asm constraint string");
4688 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4689 (ID.UIntVal >> 1) & 1,
4690 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4693 case ValID::t_GlobalName:
4694 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4695 return V == nullptr;
4696 case ValID::t_GlobalID:
4697 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4698 return V == nullptr;
4699 case ValID::t_APSInt:
4700 if (!Ty->isIntegerTy())
4701 return Error(ID.Loc, "integer constant must have integer type");
4702 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4703 V = ConstantInt::get(Context, ID.APSIntVal);
4705 case ValID::t_APFloat:
4706 if (!Ty->isFloatingPointTy() ||
4707 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4708 return Error(ID.Loc, "floating point constant invalid for type");
4710 // The lexer has no type info, so builds all half, float, and double FP
4711 // constants as double. Fix this here. Long double does not need this.
4712 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
4715 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
4717 else if (Ty->isFloatTy())
4718 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
4721 V = ConstantFP::get(Context, ID.APFloatVal);
4723 if (V->getType() != Ty)
4724 return Error(ID.Loc, "floating point constant does not have type '" +
4725 getTypeString(Ty) + "'");
4729 if (!Ty->isPointerTy())
4730 return Error(ID.Loc, "null must be a pointer type");
4731 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4733 case ValID::t_Undef:
4734 // FIXME: LabelTy should not be a first-class type.
4735 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4736 return Error(ID.Loc, "invalid type for undef constant");
4737 V = UndefValue::get(Ty);
4739 case ValID::t_EmptyArray:
4740 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4741 return Error(ID.Loc, "invalid empty array initializer");
4742 V = UndefValue::get(Ty);
4745 // FIXME: LabelTy should not be a first-class type.
4746 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4747 return Error(ID.Loc, "invalid type for null constant");
4748 V = Constant::getNullValue(Ty);
4751 if (!Ty->isTokenTy())
4752 return Error(ID.Loc, "invalid type for none constant");
4753 V = Constant::getNullValue(Ty);
4755 case ValID::t_Constant:
4756 if (ID.ConstantVal->getType() != Ty)
4757 return Error(ID.Loc, "constant expression type mismatch");
4761 case ValID::t_ConstantStruct:
4762 case ValID::t_PackedConstantStruct:
4763 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4764 if (ST->getNumElements() != ID.UIntVal)
4765 return Error(ID.Loc,
4766 "initializer with struct type has wrong # elements");
4767 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4768 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4770 // Verify that the elements are compatible with the structtype.
4771 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4772 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4773 return Error(ID.Loc, "element " + Twine(i) +
4774 " of struct initializer doesn't match struct element type");
4776 V = ConstantStruct::get(
4777 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4779 return Error(ID.Loc, "constant expression type mismatch");
4782 llvm_unreachable("Invalid ValID");
4785 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4788 auto Loc = Lex.getLoc();
4789 if (ParseValID(ID, /*PFS=*/nullptr))
4792 case ValID::t_APSInt:
4793 case ValID::t_APFloat:
4794 case ValID::t_Undef:
4795 case ValID::t_Constant:
4796 case ValID::t_ConstantStruct:
4797 case ValID::t_PackedConstantStruct: {
4799 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4801 assert(isa<Constant>(V) && "Expected a constant value");
4802 C = cast<Constant>(V);
4806 C = Constant::getNullValue(Ty);
4809 return Error(Loc, "expected a constant value");
4813 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4816 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4819 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4821 return ParseType(Ty) ||
4822 ParseValue(Ty, V, PFS);
4825 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4826 PerFunctionState &PFS) {
4829 if (ParseTypeAndValue(V, PFS)) return true;
4830 if (!isa<BasicBlock>(V))
4831 return Error(Loc, "expected a basic block");
4832 BB = cast<BasicBlock>(V);
4837 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
4838 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
4839 /// '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
4840 /// OptionalPrefix OptionalPrologue OptPersonalityFn
4841 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4842 // Parse the linkage.
4843 LocTy LinkageLoc = Lex.getLoc();
4845 unsigned Visibility;
4846 unsigned DLLStorageClass;
4848 AttrBuilder RetAttrs;
4851 Type *RetType = nullptr;
4852 LocTy RetTypeLoc = Lex.getLoc();
4853 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
4855 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4856 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4859 // Verify that the linkage is ok.
4860 switch ((GlobalValue::LinkageTypes)Linkage) {
4861 case GlobalValue::ExternalLinkage:
4862 break; // always ok.
4863 case GlobalValue::ExternalWeakLinkage:
4865 return Error(LinkageLoc, "invalid linkage for function definition");
4867 case GlobalValue::PrivateLinkage:
4868 case GlobalValue::InternalLinkage:
4869 case GlobalValue::AvailableExternallyLinkage:
4870 case GlobalValue::LinkOnceAnyLinkage:
4871 case GlobalValue::LinkOnceODRLinkage:
4872 case GlobalValue::WeakAnyLinkage:
4873 case GlobalValue::WeakODRLinkage:
4875 return Error(LinkageLoc, "invalid linkage for function declaration");
4877 case GlobalValue::AppendingLinkage:
4878 case GlobalValue::CommonLinkage:
4879 return Error(LinkageLoc, "invalid function linkage type");
4882 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4883 return Error(LinkageLoc,
4884 "symbol with local linkage must have default visibility");
4886 if (!FunctionType::isValidReturnType(RetType))
4887 return Error(RetTypeLoc, "invalid function return type");
4889 LocTy NameLoc = Lex.getLoc();
4891 std::string FunctionName;
4892 if (Lex.getKind() == lltok::GlobalVar) {
4893 FunctionName = Lex.getStrVal();
4894 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4895 unsigned NameID = Lex.getUIntVal();
4897 if (NameID != NumberedVals.size())
4898 return TokError("function expected to be numbered '%" +
4899 Twine(NumberedVals.size()) + "'");
4901 return TokError("expected function name");
4906 if (Lex.getKind() != lltok::lparen)
4907 return TokError("expected '(' in function argument list");
4909 SmallVector<ArgInfo, 8> ArgList;
4911 AttrBuilder FuncAttrs;
4912 std::vector<unsigned> FwdRefAttrGrps;
4914 std::string Section;
4917 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4918 Constant *Prefix = nullptr;
4919 Constant *Prologue = nullptr;
4920 Constant *PersonalityFn = nullptr;
4923 if (ParseArgumentList(ArgList, isVarArg) ||
4924 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4925 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4927 (EatIfPresent(lltok::kw_section) &&
4928 ParseStringConstant(Section)) ||
4929 parseOptionalComdat(FunctionName, C) ||
4930 ParseOptionalAlignment(Alignment) ||
4931 (EatIfPresent(lltok::kw_gc) &&
4932 ParseStringConstant(GC)) ||
4933 (EatIfPresent(lltok::kw_prefix) &&
4934 ParseGlobalTypeAndValue(Prefix)) ||
4935 (EatIfPresent(lltok::kw_prologue) &&
4936 ParseGlobalTypeAndValue(Prologue)) ||
4937 (EatIfPresent(lltok::kw_personality) &&
4938 ParseGlobalTypeAndValue(PersonalityFn)))
4941 if (FuncAttrs.contains(Attribute::Builtin))
4942 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4944 // If the alignment was parsed as an attribute, move to the alignment field.
4945 if (FuncAttrs.hasAlignmentAttr()) {
4946 Alignment = FuncAttrs.getAlignment();
4947 FuncAttrs.removeAttribute(Attribute::Alignment);
4950 // Okay, if we got here, the function is syntactically valid. Convert types
4951 // and do semantic checks.
4952 std::vector<Type*> ParamTypeList;
4953 SmallVector<AttributeSet, 8> Attrs;
4955 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4956 ParamTypeList.push_back(ArgList[i].Ty);
4957 Attrs.push_back(ArgList[i].Attrs);
4961 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
4962 AttributeSet::get(Context, RetAttrs), Attrs);
4964 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4965 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4968 FunctionType::get(RetType, ParamTypeList, isVarArg);
4969 PointerType *PFT = PointerType::getUnqual(FT);
4972 if (!FunctionName.empty()) {
4973 // If this was a definition of a forward reference, remove the definition
4974 // from the forward reference table and fill in the forward ref.
4975 auto FRVI = ForwardRefVals.find(FunctionName);
4976 if (FRVI != ForwardRefVals.end()) {
4977 Fn = M->getFunction(FunctionName);
4979 return Error(FRVI->second.second, "invalid forward reference to "
4980 "function as global value!");
4981 if (Fn->getType() != PFT)
4982 return Error(FRVI->second.second, "invalid forward reference to "
4983 "function '" + FunctionName + "' with wrong type!");
4985 ForwardRefVals.erase(FRVI);
4986 } else if ((Fn = M->getFunction(FunctionName))) {
4987 // Reject redefinitions.
4988 return Error(NameLoc, "invalid redefinition of function '" +
4989 FunctionName + "'");
4990 } else if (M->getNamedValue(FunctionName)) {
4991 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4995 // If this is a definition of a forward referenced function, make sure the
4997 auto I = ForwardRefValIDs.find(NumberedVals.size());
4998 if (I != ForwardRefValIDs.end()) {
4999 Fn = cast<Function>(I->second.first);
5000 if (Fn->getType() != PFT)
5001 return Error(NameLoc, "type of definition and forward reference of '@" +
5002 Twine(NumberedVals.size()) + "' disagree");
5003 ForwardRefValIDs.erase(I);
5008 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
5009 else // Move the forward-reference to the correct spot in the module.
5010 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5012 if (FunctionName.empty())
5013 NumberedVals.push_back(Fn);
5015 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5016 maybeSetDSOLocal(DSOLocal, *Fn);
5017 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5018 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5019 Fn->setCallingConv(CC);
5020 Fn->setAttributes(PAL);
5021 Fn->setUnnamedAddr(UnnamedAddr);
5022 Fn->setAlignment(Alignment);
5023 Fn->setSection(Section);
5025 Fn->setPersonalityFn(PersonalityFn);
5026 if (!GC.empty()) Fn->setGC(GC);
5027 Fn->setPrefixData(Prefix);
5028 Fn->setPrologueData(Prologue);
5029 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5031 // Add all of the arguments we parsed to the function.
5032 Function::arg_iterator ArgIt = Fn->arg_begin();
5033 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5034 // If the argument has a name, insert it into the argument symbol table.
5035 if (ArgList[i].Name.empty()) continue;
5037 // Set the name, if it conflicted, it will be auto-renamed.
5038 ArgIt->setName(ArgList[i].Name);
5040 if (ArgIt->getName() != ArgList[i].Name)
5041 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5042 ArgList[i].Name + "'");
5048 // Check the declaration has no block address forward references.
5050 if (FunctionName.empty()) {
5051 ID.Kind = ValID::t_GlobalID;
5052 ID.UIntVal = NumberedVals.size() - 1;
5054 ID.Kind = ValID::t_GlobalName;
5055 ID.StrVal = FunctionName;
5057 auto Blocks = ForwardRefBlockAddresses.find(ID);
5058 if (Blocks != ForwardRefBlockAddresses.end())
5059 return Error(Blocks->first.Loc,
5060 "cannot take blockaddress inside a declaration");
5064 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5066 if (FunctionNumber == -1) {
5067 ID.Kind = ValID::t_GlobalName;
5068 ID.StrVal = F.getName();
5070 ID.Kind = ValID::t_GlobalID;
5071 ID.UIntVal = FunctionNumber;
5074 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5075 if (Blocks == P.ForwardRefBlockAddresses.end())
5078 for (const auto &I : Blocks->second) {
5079 const ValID &BBID = I.first;
5080 GlobalValue *GV = I.second;
5082 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5083 "Expected local id or name");
5085 if (BBID.Kind == ValID::t_LocalName)
5086 BB = GetBB(BBID.StrVal, BBID.Loc);
5088 BB = GetBB(BBID.UIntVal, BBID.Loc);
5090 return P.Error(BBID.Loc, "referenced value is not a basic block");
5092 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5093 GV->eraseFromParent();
5096 P.ForwardRefBlockAddresses.erase(Blocks);
5100 /// ParseFunctionBody
5101 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5102 bool LLParser::ParseFunctionBody(Function &Fn) {
5103 if (Lex.getKind() != lltok::lbrace)
5104 return TokError("expected '{' in function body");
5105 Lex.Lex(); // eat the {.
5107 int FunctionNumber = -1;
5108 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5110 PerFunctionState PFS(*this, Fn, FunctionNumber);
5112 // Resolve block addresses and allow basic blocks to be forward-declared
5113 // within this function.
5114 if (PFS.resolveForwardRefBlockAddresses())
5116 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5118 // We need at least one basic block.
5119 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5120 return TokError("function body requires at least one basic block");
5122 while (Lex.getKind() != lltok::rbrace &&
5123 Lex.getKind() != lltok::kw_uselistorder)
5124 if (ParseBasicBlock(PFS)) return true;
5126 while (Lex.getKind() != lltok::rbrace)
5127 if (ParseUseListOrder(&PFS))
5133 // Verify function is ok.
5134 return PFS.FinishFunction();
5138 /// ::= LabelStr? Instruction*
5139 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5140 // If this basic block starts out with a name, remember it.
5142 LocTy NameLoc = Lex.getLoc();
5143 if (Lex.getKind() == lltok::LabelStr) {
5144 Name = Lex.getStrVal();
5148 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
5150 return Error(NameLoc,
5151 "unable to create block named '" + Name + "'");
5153 std::string NameStr;
5155 // Parse the instructions in this block until we get a terminator.
5158 // This instruction may have three possibilities for a name: a) none
5159 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5160 LocTy NameLoc = Lex.getLoc();
5164 if (Lex.getKind() == lltok::LocalVarID) {
5165 NameID = Lex.getUIntVal();
5167 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5169 } else if (Lex.getKind() == lltok::LocalVar) {
5170 NameStr = Lex.getStrVal();
5172 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5176 switch (ParseInstruction(Inst, BB, PFS)) {
5177 default: llvm_unreachable("Unknown ParseInstruction result!");
5178 case InstError: return true;
5180 BB->getInstList().push_back(Inst);
5182 // With a normal result, we check to see if the instruction is followed by
5183 // a comma and metadata.
5184 if (EatIfPresent(lltok::comma))
5185 if (ParseInstructionMetadata(*Inst))
5188 case InstExtraComma:
5189 BB->getInstList().push_back(Inst);
5191 // If the instruction parser ate an extra comma at the end of it, it
5192 // *must* be followed by metadata.
5193 if (ParseInstructionMetadata(*Inst))
5198 // Set the name on the instruction.
5199 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5200 } while (!isa<TerminatorInst>(Inst));
5205 //===----------------------------------------------------------------------===//
5206 // Instruction Parsing.
5207 //===----------------------------------------------------------------------===//
5209 /// ParseInstruction - Parse one of the many different instructions.
5211 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5212 PerFunctionState &PFS) {
5213 lltok::Kind Token = Lex.getKind();
5214 if (Token == lltok::Eof)
5215 return TokError("found end of file when expecting more instructions");
5216 LocTy Loc = Lex.getLoc();
5217 unsigned KeywordVal = Lex.getUIntVal();
5218 Lex.Lex(); // Eat the keyword.
5221 default: return Error(Loc, "expected instruction opcode");
5222 // Terminator Instructions.
5223 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5224 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5225 case lltok::kw_br: return ParseBr(Inst, PFS);
5226 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5227 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5228 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5229 case lltok::kw_resume: return ParseResume(Inst, PFS);
5230 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5231 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5232 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5233 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5234 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5235 // Binary Operators.
5239 case lltok::kw_shl: {
5240 bool NUW = EatIfPresent(lltok::kw_nuw);
5241 bool NSW = EatIfPresent(lltok::kw_nsw);
5242 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5244 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5246 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5247 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5250 case lltok::kw_fadd:
5251 case lltok::kw_fsub:
5252 case lltok::kw_fmul:
5253 case lltok::kw_fdiv:
5254 case lltok::kw_frem: {
5255 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5256 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5260 Inst->setFastMathFlags(FMF);
5264 case lltok::kw_sdiv:
5265 case lltok::kw_udiv:
5266 case lltok::kw_lshr:
5267 case lltok::kw_ashr: {
5268 bool Exact = EatIfPresent(lltok::kw_exact);
5270 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5271 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5275 case lltok::kw_urem:
5276 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5279 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5280 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5281 case lltok::kw_fcmp: {
5282 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5283 int Res = ParseCompare(Inst, PFS, KeywordVal);
5287 Inst->setFastMathFlags(FMF);
5292 case lltok::kw_trunc:
5293 case lltok::kw_zext:
5294 case lltok::kw_sext:
5295 case lltok::kw_fptrunc:
5296 case lltok::kw_fpext:
5297 case lltok::kw_bitcast:
5298 case lltok::kw_addrspacecast:
5299 case lltok::kw_uitofp:
5300 case lltok::kw_sitofp:
5301 case lltok::kw_fptoui:
5302 case lltok::kw_fptosi:
5303 case lltok::kw_inttoptr:
5304 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5306 case lltok::kw_select: return ParseSelect(Inst, PFS);
5307 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5308 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5309 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5310 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5311 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5312 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5314 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5315 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5316 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5317 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5319 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5320 case lltok::kw_load: return ParseLoad(Inst, PFS);
5321 case lltok::kw_store: return ParseStore(Inst, PFS);
5322 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5323 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5324 case lltok::kw_fence: return ParseFence(Inst, PFS);
5325 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5326 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5327 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5331 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5332 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5333 if (Opc == Instruction::FCmp) {
5334 switch (Lex.getKind()) {
5335 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5336 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5337 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5338 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5339 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5340 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5341 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5342 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5343 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5344 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5345 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5346 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5347 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5348 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5349 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5350 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5351 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5354 switch (Lex.getKind()) {
5355 default: return TokError("expected icmp predicate (e.g. 'eq')");
5356 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5357 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5358 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5359 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5360 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5361 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5362 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5363 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5364 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5365 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5372 //===----------------------------------------------------------------------===//
5373 // Terminator Instructions.
5374 //===----------------------------------------------------------------------===//
5376 /// ParseRet - Parse a return instruction.
5377 /// ::= 'ret' void (',' !dbg, !1)*
5378 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5379 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5380 PerFunctionState &PFS) {
5381 SMLoc TypeLoc = Lex.getLoc();
5383 if (ParseType(Ty, true /*void allowed*/)) return true;
5385 Type *ResType = PFS.getFunction().getReturnType();
5387 if (Ty->isVoidTy()) {
5388 if (!ResType->isVoidTy())
5389 return Error(TypeLoc, "value doesn't match function result type '" +
5390 getTypeString(ResType) + "'");
5392 Inst = ReturnInst::Create(Context);
5397 if (ParseValue(Ty, RV, PFS)) return true;
5399 if (ResType != RV->getType())
5400 return Error(TypeLoc, "value doesn't match function result type '" +
5401 getTypeString(ResType) + "'");
5403 Inst = ReturnInst::Create(Context, RV);
5408 /// ::= 'br' TypeAndValue
5409 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5410 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5413 BasicBlock *Op1, *Op2;
5414 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5416 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5417 Inst = BranchInst::Create(BB);
5421 if (Op0->getType() != Type::getInt1Ty(Context))
5422 return Error(Loc, "branch condition must have 'i1' type");
5424 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5425 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5426 ParseToken(lltok::comma, "expected ',' after true destination") ||
5427 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5430 Inst = BranchInst::Create(Op1, Op2, Op0);
5436 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5438 /// ::= (TypeAndValue ',' TypeAndValue)*
5439 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5440 LocTy CondLoc, BBLoc;
5442 BasicBlock *DefaultBB;
5443 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5444 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5445 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5446 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5449 if (!Cond->getType()->isIntegerTy())
5450 return Error(CondLoc, "switch condition must have integer type");
5452 // Parse the jump table pairs.
5453 SmallPtrSet<Value*, 32> SeenCases;
5454 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5455 while (Lex.getKind() != lltok::rsquare) {
5459 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5460 ParseToken(lltok::comma, "expected ',' after case value") ||
5461 ParseTypeAndBasicBlock(DestBB, PFS))
5464 if (!SeenCases.insert(Constant).second)
5465 return Error(CondLoc, "duplicate case value in switch");
5466 if (!isa<ConstantInt>(Constant))
5467 return Error(CondLoc, "case value is not a constant integer");
5469 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5472 Lex.Lex(); // Eat the ']'.
5474 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5475 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5476 SI->addCase(Table[i].first, Table[i].second);
5483 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5484 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5487 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5488 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5489 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5492 if (!Address->getType()->isPointerTy())
5493 return Error(AddrLoc, "indirectbr address must have pointer type");
5495 // Parse the destination list.
5496 SmallVector<BasicBlock*, 16> DestList;
5498 if (Lex.getKind() != lltok::rsquare) {
5500 if (ParseTypeAndBasicBlock(DestBB, PFS))
5502 DestList.push_back(DestBB);
5504 while (EatIfPresent(lltok::comma)) {
5505 if (ParseTypeAndBasicBlock(DestBB, PFS))
5507 DestList.push_back(DestBB);
5511 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5514 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5515 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5516 IBI->addDestination(DestList[i]);
5522 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5523 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5524 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5525 LocTy CallLoc = Lex.getLoc();
5526 AttrBuilder RetAttrs, FnAttrs;
5527 std::vector<unsigned> FwdRefAttrGrps;
5530 Type *RetType = nullptr;
5533 SmallVector<ParamInfo, 16> ArgList;
5534 SmallVector<OperandBundleDef, 2> BundleList;
5536 BasicBlock *NormalBB, *UnwindBB;
5537 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5538 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5539 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5540 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5542 ParseOptionalOperandBundles(BundleList, PFS) ||
5543 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5544 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5545 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5546 ParseTypeAndBasicBlock(UnwindBB, PFS))
5549 // If RetType is a non-function pointer type, then this is the short syntax
5550 // for the call, which means that RetType is just the return type. Infer the
5551 // rest of the function argument types from the arguments that are present.
5552 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5554 // Pull out the types of all of the arguments...
5555 std::vector<Type*> ParamTypes;
5556 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5557 ParamTypes.push_back(ArgList[i].V->getType());
5559 if (!FunctionType::isValidReturnType(RetType))
5560 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5562 Ty = FunctionType::get(RetType, ParamTypes, false);
5567 // Look up the callee.
5569 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5572 // Set up the Attribute for the function.
5573 SmallVector<Value *, 8> Args;
5574 SmallVector<AttributeSet, 8> ArgAttrs;
5576 // Loop through FunctionType's arguments and ensure they are specified
5577 // correctly. Also, gather any parameter attributes.
5578 FunctionType::param_iterator I = Ty->param_begin();
5579 FunctionType::param_iterator E = Ty->param_end();
5580 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5581 Type *ExpectedTy = nullptr;
5584 } else if (!Ty->isVarArg()) {
5585 return Error(ArgList[i].Loc, "too many arguments specified");
5588 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5589 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5590 getTypeString(ExpectedTy) + "'");
5591 Args.push_back(ArgList[i].V);
5592 ArgAttrs.push_back(ArgList[i].Attrs);
5596 return Error(CallLoc, "not enough parameters specified for call");
5598 if (FnAttrs.hasAlignmentAttr())
5599 return Error(CallLoc, "invoke instructions may not have an alignment");
5601 // Finish off the Attribute and check them
5603 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5604 AttributeSet::get(Context, RetAttrs), ArgAttrs);
5607 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5608 II->setCallingConv(CC);
5609 II->setAttributes(PAL);
5610 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5616 /// ::= 'resume' TypeAndValue
5617 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5618 Value *Exn; LocTy ExnLoc;
5619 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5622 ResumeInst *RI = ResumeInst::Create(Exn);
5627 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5628 PerFunctionState &PFS) {
5629 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5632 while (Lex.getKind() != lltok::rsquare) {
5633 // If this isn't the first argument, we need a comma.
5634 if (!Args.empty() &&
5635 ParseToken(lltok::comma, "expected ',' in argument list"))
5638 // Parse the argument.
5640 Type *ArgTy = nullptr;
5641 if (ParseType(ArgTy, ArgLoc))
5645 if (ArgTy->isMetadataTy()) {
5646 if (ParseMetadataAsValue(V, PFS))
5649 if (ParseValue(ArgTy, V, PFS))
5655 Lex.Lex(); // Lex the ']'.
5660 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5661 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5662 Value *CleanupPad = nullptr;
5664 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5667 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5670 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5673 BasicBlock *UnwindBB = nullptr;
5674 if (Lex.getKind() == lltok::kw_to) {
5676 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5679 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5684 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5689 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
5690 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5691 Value *CatchPad = nullptr;
5693 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5696 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5700 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5701 ParseTypeAndBasicBlock(BB, PFS))
5704 Inst = CatchReturnInst::Create(CatchPad, BB);
5708 /// ParseCatchSwitch
5709 /// ::= 'catchswitch' within Parent
5710 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5713 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5716 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5717 Lex.getKind() != lltok::LocalVarID)
5718 return TokError("expected scope value for catchswitch");
5720 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5723 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5726 SmallVector<BasicBlock *, 32> Table;
5729 if (ParseTypeAndBasicBlock(DestBB, PFS))
5731 Table.push_back(DestBB);
5732 } while (EatIfPresent(lltok::comma));
5734 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5737 if (ParseToken(lltok::kw_unwind,
5738 "expected 'unwind' after catchswitch scope"))
5741 BasicBlock *UnwindBB = nullptr;
5742 if (EatIfPresent(lltok::kw_to)) {
5743 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5746 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5751 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5752 for (BasicBlock *DestBB : Table)
5753 CatchSwitch->addHandler(DestBB);
5759 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5760 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5761 Value *CatchSwitch = nullptr;
5763 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5766 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5767 return TokError("expected scope value for catchpad");
5769 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5772 SmallVector<Value *, 8> Args;
5773 if (ParseExceptionArgs(Args, PFS))
5776 Inst = CatchPadInst::Create(CatchSwitch, Args);
5781 /// ::= 'cleanuppad' within Parent ParamList
5782 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5783 Value *ParentPad = nullptr;
5785 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5788 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5789 Lex.getKind() != lltok::LocalVarID)
5790 return TokError("expected scope value for cleanuppad");
5792 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5795 SmallVector<Value *, 8> Args;
5796 if (ParseExceptionArgs(Args, PFS))
5799 Inst = CleanupPadInst::Create(ParentPad, Args);
5803 //===----------------------------------------------------------------------===//
5804 // Binary Operators.
5805 //===----------------------------------------------------------------------===//
5808 /// ::= ArithmeticOps TypeAndValue ',' Value
5810 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5811 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5812 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5813 unsigned Opc, unsigned OperandType) {
5814 LocTy Loc; Value *LHS, *RHS;
5815 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5816 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5817 ParseValue(LHS->getType(), RHS, PFS))
5821 switch (OperandType) {
5822 default: llvm_unreachable("Unknown operand type!");
5823 case 0: // int or FP.
5824 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5825 LHS->getType()->isFPOrFPVectorTy();
5827 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5828 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5832 return Error(Loc, "invalid operand type for instruction");
5834 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5839 /// ::= ArithmeticOps TypeAndValue ',' Value {
5840 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5842 LocTy Loc; Value *LHS, *RHS;
5843 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5844 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5845 ParseValue(LHS->getType(), RHS, PFS))
5848 if (!LHS->getType()->isIntOrIntVectorTy())
5849 return Error(Loc,"instruction requires integer or integer vector operands");
5851 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5856 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5857 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5858 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5860 // Parse the integer/fp comparison predicate.
5864 if (ParseCmpPredicate(Pred, Opc) ||
5865 ParseTypeAndValue(LHS, Loc, PFS) ||
5866 ParseToken(lltok::comma, "expected ',' after compare value") ||
5867 ParseValue(LHS->getType(), RHS, PFS))
5870 if (Opc == Instruction::FCmp) {
5871 if (!LHS->getType()->isFPOrFPVectorTy())
5872 return Error(Loc, "fcmp requires floating point operands");
5873 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5875 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5876 if (!LHS->getType()->isIntOrIntVectorTy() &&
5877 !LHS->getType()->isPtrOrPtrVectorTy())
5878 return Error(Loc, "icmp requires integer operands");
5879 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5884 //===----------------------------------------------------------------------===//
5885 // Other Instructions.
5886 //===----------------------------------------------------------------------===//
5890 /// ::= CastOpc TypeAndValue 'to' Type
5891 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5895 Type *DestTy = nullptr;
5896 if (ParseTypeAndValue(Op, Loc, PFS) ||
5897 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5901 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5902 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5903 return Error(Loc, "invalid cast opcode for cast from '" +
5904 getTypeString(Op->getType()) + "' to '" +
5905 getTypeString(DestTy) + "'");
5907 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5912 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5913 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5915 Value *Op0, *Op1, *Op2;
5916 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5917 ParseToken(lltok::comma, "expected ',' after select condition") ||
5918 ParseTypeAndValue(Op1, PFS) ||
5919 ParseToken(lltok::comma, "expected ',' after select value") ||
5920 ParseTypeAndValue(Op2, PFS))
5923 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5924 return Error(Loc, Reason);
5926 Inst = SelectInst::Create(Op0, Op1, Op2);
5931 /// ::= 'va_arg' TypeAndValue ',' Type
5932 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5934 Type *EltTy = nullptr;
5936 if (ParseTypeAndValue(Op, PFS) ||
5937 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5938 ParseType(EltTy, TypeLoc))
5941 if (!EltTy->isFirstClassType())
5942 return Error(TypeLoc, "va_arg requires operand with first class type");
5944 Inst = new VAArgInst(Op, EltTy);
5948 /// ParseExtractElement
5949 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5950 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5953 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5954 ParseToken(lltok::comma, "expected ',' after extract value") ||
5955 ParseTypeAndValue(Op1, PFS))
5958 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5959 return Error(Loc, "invalid extractelement operands");
5961 Inst = ExtractElementInst::Create(Op0, Op1);
5965 /// ParseInsertElement
5966 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5967 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5969 Value *Op0, *Op1, *Op2;
5970 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5971 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5972 ParseTypeAndValue(Op1, PFS) ||
5973 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5974 ParseTypeAndValue(Op2, PFS))
5977 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5978 return Error(Loc, "invalid insertelement operands");
5980 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5984 /// ParseShuffleVector
5985 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5986 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5988 Value *Op0, *Op1, *Op2;
5989 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5990 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5991 ParseTypeAndValue(Op1, PFS) ||
5992 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5993 ParseTypeAndValue(Op2, PFS))
5996 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5997 return Error(Loc, "invalid shufflevector operands");
5999 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6004 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6005 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6006 Type *Ty = nullptr; LocTy TypeLoc;
6009 if (ParseType(Ty, TypeLoc) ||
6010 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6011 ParseValue(Ty, Op0, PFS) ||
6012 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6013 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6014 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6017 bool AteExtraComma = false;
6018 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6021 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6023 if (!EatIfPresent(lltok::comma))
6026 if (Lex.getKind() == lltok::MetadataVar) {
6027 AteExtraComma = true;
6031 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6032 ParseValue(Ty, Op0, PFS) ||
6033 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6034 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6035 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6039 if (!Ty->isFirstClassType())
6040 return Error(TypeLoc, "phi node must have first class type");
6042 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6043 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6044 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6046 return AteExtraComma ? InstExtraComma : InstNormal;
6050 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6052 /// ::= 'catch' TypeAndValue
6054 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6055 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6056 Type *Ty = nullptr; LocTy TyLoc;
6058 if (ParseType(Ty, TyLoc))
6061 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6062 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6064 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6065 LandingPadInst::ClauseType CT;
6066 if (EatIfPresent(lltok::kw_catch))
6067 CT = LandingPadInst::Catch;
6068 else if (EatIfPresent(lltok::kw_filter))
6069 CT = LandingPadInst::Filter;
6071 return TokError("expected 'catch' or 'filter' clause type");
6075 if (ParseTypeAndValue(V, VLoc, PFS))
6078 // A 'catch' type expects a non-array constant. A filter clause expects an
6080 if (CT == LandingPadInst::Catch) {
6081 if (isa<ArrayType>(V->getType()))
6082 Error(VLoc, "'catch' clause has an invalid type");
6084 if (!isa<ArrayType>(V->getType()))
6085 Error(VLoc, "'filter' clause has an invalid type");
6088 Constant *CV = dyn_cast<Constant>(V);
6090 return Error(VLoc, "clause argument must be a constant");
6094 Inst = LP.release();
6099 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6100 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6101 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6102 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6103 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6104 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6105 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6106 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6107 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6108 CallInst::TailCallKind TCK) {
6109 AttrBuilder RetAttrs, FnAttrs;
6110 std::vector<unsigned> FwdRefAttrGrps;
6113 Type *RetType = nullptr;
6116 SmallVector<ParamInfo, 16> ArgList;
6117 SmallVector<OperandBundleDef, 2> BundleList;
6118 LocTy CallLoc = Lex.getLoc();
6120 if (TCK != CallInst::TCK_None &&
6121 ParseToken(lltok::kw_call,
6122 "expected 'tail call', 'musttail call', or 'notail call'"))
6125 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6127 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6128 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6129 ParseValID(CalleeID) ||
6130 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6131 PFS.getFunction().isVarArg()) ||
6132 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6133 ParseOptionalOperandBundles(BundleList, PFS))
6136 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6137 return Error(CallLoc, "fast-math-flags specified for call without "
6138 "floating-point scalar or vector return type");
6140 // If RetType is a non-function pointer type, then this is the short syntax
6141 // for the call, which means that RetType is just the return type. Infer the
6142 // rest of the function argument types from the arguments that are present.
6143 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6145 // Pull out the types of all of the arguments...
6146 std::vector<Type*> ParamTypes;
6147 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6148 ParamTypes.push_back(ArgList[i].V->getType());
6150 if (!FunctionType::isValidReturnType(RetType))
6151 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6153 Ty = FunctionType::get(RetType, ParamTypes, false);
6158 // Look up the callee.
6160 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6163 // Set up the Attribute for the function.
6164 SmallVector<AttributeSet, 8> Attrs;
6166 SmallVector<Value*, 8> Args;
6168 // Loop through FunctionType's arguments and ensure they are specified
6169 // correctly. Also, gather any parameter attributes.
6170 FunctionType::param_iterator I = Ty->param_begin();
6171 FunctionType::param_iterator E = Ty->param_end();
6172 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6173 Type *ExpectedTy = nullptr;
6176 } else if (!Ty->isVarArg()) {
6177 return Error(ArgList[i].Loc, "too many arguments specified");
6180 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6181 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6182 getTypeString(ExpectedTy) + "'");
6183 Args.push_back(ArgList[i].V);
6184 Attrs.push_back(ArgList[i].Attrs);
6188 return Error(CallLoc, "not enough parameters specified for call");
6190 if (FnAttrs.hasAlignmentAttr())
6191 return Error(CallLoc, "call instructions may not have an alignment");
6193 // Finish off the Attribute and check them
6195 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6196 AttributeSet::get(Context, RetAttrs), Attrs);
6198 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6199 CI->setTailCallKind(TCK);
6200 CI->setCallingConv(CC);
6202 CI->setFastMathFlags(FMF);
6203 CI->setAttributes(PAL);
6204 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6209 //===----------------------------------------------------------------------===//
6210 // Memory Instructions.
6211 //===----------------------------------------------------------------------===//
6214 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6215 /// (',' 'align' i32)? (',', 'addrspace(n))?
6216 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6217 Value *Size = nullptr;
6218 LocTy SizeLoc, TyLoc, ASLoc;
6219 unsigned Alignment = 0;
6220 unsigned AddrSpace = 0;
6223 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6224 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6226 if (ParseType(Ty, TyLoc)) return true;
6228 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6229 return Error(TyLoc, "invalid type for alloca");
6231 bool AteExtraComma = false;
6232 if (EatIfPresent(lltok::comma)) {
6233 if (Lex.getKind() == lltok::kw_align) {
6234 if (ParseOptionalAlignment(Alignment))
6236 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6238 } else if (Lex.getKind() == lltok::kw_addrspace) {
6239 ASLoc = Lex.getLoc();
6240 if (ParseOptionalAddrSpace(AddrSpace))
6242 } else if (Lex.getKind() == lltok::MetadataVar) {
6243 AteExtraComma = true;
6245 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6247 if (EatIfPresent(lltok::comma)) {
6248 if (Lex.getKind() == lltok::kw_align) {
6249 if (ParseOptionalAlignment(Alignment))
6251 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6253 } else if (Lex.getKind() == lltok::kw_addrspace) {
6254 ASLoc = Lex.getLoc();
6255 if (ParseOptionalAddrSpace(AddrSpace))
6257 } else if (Lex.getKind() == lltok::MetadataVar) {
6258 AteExtraComma = true;
6264 if (Size && !Size->getType()->isIntegerTy())
6265 return Error(SizeLoc, "element count must have integer type");
6267 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
6268 AI->setUsedWithInAlloca(IsInAlloca);
6269 AI->setSwiftError(IsSwiftError);
6271 return AteExtraComma ? InstExtraComma : InstNormal;
6275 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6276 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6277 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6278 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6279 Value *Val; LocTy Loc;
6280 unsigned Alignment = 0;
6281 bool AteExtraComma = false;
6282 bool isAtomic = false;
6283 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6284 SyncScope::ID SSID = SyncScope::System;
6286 if (Lex.getKind() == lltok::kw_atomic) {
6291 bool isVolatile = false;
6292 if (Lex.getKind() == lltok::kw_volatile) {
6298 LocTy ExplicitTypeLoc = Lex.getLoc();
6299 if (ParseType(Ty) ||
6300 ParseToken(lltok::comma, "expected comma after load's type") ||
6301 ParseTypeAndValue(Val, Loc, PFS) ||
6302 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6303 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6306 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6307 return Error(Loc, "load operand must be a pointer to a first class type");
6308 if (isAtomic && !Alignment)
6309 return Error(Loc, "atomic load must have explicit non-zero alignment");
6310 if (Ordering == AtomicOrdering::Release ||
6311 Ordering == AtomicOrdering::AcquireRelease)
6312 return Error(Loc, "atomic load cannot use Release ordering");
6314 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6315 return Error(ExplicitTypeLoc,
6316 "explicit pointee type doesn't match operand's pointee type");
6318 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6319 return AteExtraComma ? InstExtraComma : InstNormal;
6324 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6325 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6326 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6327 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6328 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6329 unsigned Alignment = 0;
6330 bool AteExtraComma = false;
6331 bool isAtomic = false;
6332 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6333 SyncScope::ID SSID = SyncScope::System;
6335 if (Lex.getKind() == lltok::kw_atomic) {
6340 bool isVolatile = false;
6341 if (Lex.getKind() == lltok::kw_volatile) {
6346 if (ParseTypeAndValue(Val, Loc, PFS) ||
6347 ParseToken(lltok::comma, "expected ',' after store operand") ||
6348 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6349 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6350 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6353 if (!Ptr->getType()->isPointerTy())
6354 return Error(PtrLoc, "store operand must be a pointer");
6355 if (!Val->getType()->isFirstClassType())
6356 return Error(Loc, "store operand must be a first class value");
6357 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6358 return Error(Loc, "stored value and pointer type do not match");
6359 if (isAtomic && !Alignment)
6360 return Error(Loc, "atomic store must have explicit non-zero alignment");
6361 if (Ordering == AtomicOrdering::Acquire ||
6362 Ordering == AtomicOrdering::AcquireRelease)
6363 return Error(Loc, "atomic store cannot use Acquire ordering");
6365 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6366 return AteExtraComma ? InstExtraComma : InstNormal;
6370 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6371 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6372 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6373 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6374 bool AteExtraComma = false;
6375 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6376 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6377 SyncScope::ID SSID = SyncScope::System;
6378 bool isVolatile = false;
6379 bool isWeak = false;
6381 if (EatIfPresent(lltok::kw_weak))
6384 if (EatIfPresent(lltok::kw_volatile))
6387 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6388 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6389 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6390 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6391 ParseTypeAndValue(New, NewLoc, PFS) ||
6392 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
6393 ParseOrdering(FailureOrdering))
6396 if (SuccessOrdering == AtomicOrdering::Unordered ||
6397 FailureOrdering == AtomicOrdering::Unordered)
6398 return TokError("cmpxchg cannot be unordered");
6399 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6400 return TokError("cmpxchg failure argument shall be no stronger than the "
6401 "success argument");
6402 if (FailureOrdering == AtomicOrdering::Release ||
6403 FailureOrdering == AtomicOrdering::AcquireRelease)
6405 "cmpxchg failure ordering cannot include release semantics");
6406 if (!Ptr->getType()->isPointerTy())
6407 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6408 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6409 return Error(CmpLoc, "compare value and pointer type do not match");
6410 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6411 return Error(NewLoc, "new value and pointer type do not match");
6412 if (!New->getType()->isFirstClassType())
6413 return Error(NewLoc, "cmpxchg operand must be a first class value");
6414 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6415 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
6416 CXI->setVolatile(isVolatile);
6417 CXI->setWeak(isWeak);
6419 return AteExtraComma ? InstExtraComma : InstNormal;
6423 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6424 /// 'singlethread'? AtomicOrdering
6425 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6426 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6427 bool AteExtraComma = false;
6428 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6429 SyncScope::ID SSID = SyncScope::System;
6430 bool isVolatile = false;
6431 AtomicRMWInst::BinOp Operation;
6433 if (EatIfPresent(lltok::kw_volatile))
6436 switch (Lex.getKind()) {
6437 default: return TokError("expected binary operation in atomicrmw");
6438 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6439 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6440 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6441 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6442 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6443 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6444 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6445 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6446 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6447 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6448 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6450 Lex.Lex(); // Eat the operation.
6452 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6453 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6454 ParseTypeAndValue(Val, ValLoc, PFS) ||
6455 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6458 if (Ordering == AtomicOrdering::Unordered)
6459 return TokError("atomicrmw cannot be unordered");
6460 if (!Ptr->getType()->isPointerTy())
6461 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6462 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6463 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6464 if (!Val->getType()->isIntegerTy())
6465 return Error(ValLoc, "atomicrmw operand must be an integer");
6466 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6467 if (Size < 8 || (Size & (Size - 1)))
6468 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6471 AtomicRMWInst *RMWI =
6472 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
6473 RMWI->setVolatile(isVolatile);
6475 return AteExtraComma ? InstExtraComma : InstNormal;
6479 /// ::= 'fence' 'singlethread'? AtomicOrdering
6480 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6481 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6482 SyncScope::ID SSID = SyncScope::System;
6483 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6486 if (Ordering == AtomicOrdering::Unordered)
6487 return TokError("fence cannot be unordered");
6488 if (Ordering == AtomicOrdering::Monotonic)
6489 return TokError("fence cannot be monotonic");
6491 Inst = new FenceInst(Context, Ordering, SSID);
6495 /// ParseGetElementPtr
6496 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6497 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6498 Value *Ptr = nullptr;
6499 Value *Val = nullptr;
6502 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6505 LocTy ExplicitTypeLoc = Lex.getLoc();
6506 if (ParseType(Ty) ||
6507 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6508 ParseTypeAndValue(Ptr, Loc, PFS))
6511 Type *BaseType = Ptr->getType();
6512 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6513 if (!BasePointerType)
6514 return Error(Loc, "base of getelementptr must be a pointer");
6516 if (Ty != BasePointerType->getElementType())
6517 return Error(ExplicitTypeLoc,
6518 "explicit pointee type doesn't match operand's pointee type");
6520 SmallVector<Value*, 16> Indices;
6521 bool AteExtraComma = false;
6522 // GEP returns a vector of pointers if at least one of parameters is a vector.
6523 // All vector parameters should have the same vector width.
6524 unsigned GEPWidth = BaseType->isVectorTy() ?
6525 BaseType->getVectorNumElements() : 0;
6527 while (EatIfPresent(lltok::comma)) {
6528 if (Lex.getKind() == lltok::MetadataVar) {
6529 AteExtraComma = true;
6532 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6533 if (!Val->getType()->isIntOrIntVectorTy())
6534 return Error(EltLoc, "getelementptr index must be an integer");
6536 if (Val->getType()->isVectorTy()) {
6537 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6538 if (GEPWidth && GEPWidth != ValNumEl)
6539 return Error(EltLoc,
6540 "getelementptr vector index has a wrong number of elements");
6541 GEPWidth = ValNumEl;
6543 Indices.push_back(Val);
6546 SmallPtrSet<Type*, 4> Visited;
6547 if (!Indices.empty() && !Ty->isSized(&Visited))
6548 return Error(Loc, "base element of getelementptr must be sized");
6550 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6551 return Error(Loc, "invalid getelementptr indices");
6552 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6554 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6555 return AteExtraComma ? InstExtraComma : InstNormal;
6558 /// ParseExtractValue
6559 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6560 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6561 Value *Val; LocTy Loc;
6562 SmallVector<unsigned, 4> Indices;
6564 if (ParseTypeAndValue(Val, Loc, PFS) ||
6565 ParseIndexList(Indices, AteExtraComma))
6568 if (!Val->getType()->isAggregateType())
6569 return Error(Loc, "extractvalue operand must be aggregate type");
6571 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6572 return Error(Loc, "invalid indices for extractvalue");
6573 Inst = ExtractValueInst::Create(Val, Indices);
6574 return AteExtraComma ? InstExtraComma : InstNormal;
6577 /// ParseInsertValue
6578 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6579 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6580 Value *Val0, *Val1; LocTy Loc0, Loc1;
6581 SmallVector<unsigned, 4> Indices;
6583 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6584 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6585 ParseTypeAndValue(Val1, Loc1, PFS) ||
6586 ParseIndexList(Indices, AteExtraComma))
6589 if (!Val0->getType()->isAggregateType())
6590 return Error(Loc0, "insertvalue operand must be aggregate type");
6592 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6594 return Error(Loc0, "invalid indices for insertvalue");
6595 if (IndexedType != Val1->getType())
6596 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6597 getTypeString(Val1->getType()) + "' instead of '" +
6598 getTypeString(IndexedType) + "'");
6599 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6600 return AteExtraComma ? InstExtraComma : InstNormal;
6603 //===----------------------------------------------------------------------===//
6604 // Embedded metadata.
6605 //===----------------------------------------------------------------------===//
6607 /// ParseMDNodeVector
6608 /// ::= { Element (',' Element)* }
6610 /// ::= 'null' | TypeAndValue
6611 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6612 if (ParseToken(lltok::lbrace, "expected '{' here"))
6615 // Check for an empty list.
6616 if (EatIfPresent(lltok::rbrace))
6620 // Null is a special case since it is typeless.
6621 if (EatIfPresent(lltok::kw_null)) {
6622 Elts.push_back(nullptr);
6627 if (ParseMetadata(MD, nullptr))
6630 } while (EatIfPresent(lltok::comma));
6632 return ParseToken(lltok::rbrace, "expected end of metadata node");
6635 //===----------------------------------------------------------------------===//
6636 // Use-list order directives.
6637 //===----------------------------------------------------------------------===//
6638 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6641 return Error(Loc, "value has no uses");
6643 unsigned NumUses = 0;
6644 SmallDenseMap<const Use *, unsigned, 16> Order;
6645 for (const Use &U : V->uses()) {
6646 if (++NumUses > Indexes.size())
6648 Order[&U] = Indexes[NumUses - 1];
6651 return Error(Loc, "value only has one use");
6652 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6653 return Error(Loc, "wrong number of indexes, expected " +
6654 Twine(std::distance(V->use_begin(), V->use_end())));
6656 V->sortUseList([&](const Use &L, const Use &R) {
6657 return Order.lookup(&L) < Order.lookup(&R);
6662 /// ParseUseListOrderIndexes
6663 /// ::= '{' uint32 (',' uint32)+ '}'
6664 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6665 SMLoc Loc = Lex.getLoc();
6666 if (ParseToken(lltok::lbrace, "expected '{' here"))
6668 if (Lex.getKind() == lltok::rbrace)
6669 return Lex.Error("expected non-empty list of uselistorder indexes");
6671 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6672 // indexes should be distinct numbers in the range [0, size-1], and should
6674 unsigned Offset = 0;
6676 bool IsOrdered = true;
6677 assert(Indexes.empty() && "Expected empty order vector");
6680 if (ParseUInt32(Index))
6683 // Update consistency checks.
6684 Offset += Index - Indexes.size();
6685 Max = std::max(Max, Index);
6686 IsOrdered &= Index == Indexes.size();
6688 Indexes.push_back(Index);
6689 } while (EatIfPresent(lltok::comma));
6691 if (ParseToken(lltok::rbrace, "expected '}' here"))
6694 if (Indexes.size() < 2)
6695 return Error(Loc, "expected >= 2 uselistorder indexes");
6696 if (Offset != 0 || Max >= Indexes.size())
6697 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6699 return Error(Loc, "expected uselistorder indexes to change the order");
6704 /// ParseUseListOrder
6705 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6706 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6707 SMLoc Loc = Lex.getLoc();
6708 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6712 SmallVector<unsigned, 16> Indexes;
6713 if (ParseTypeAndValue(V, PFS) ||
6714 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6715 ParseUseListOrderIndexes(Indexes))
6718 return sortUseListOrder(V, Indexes, Loc);
6721 /// ParseUseListOrderBB
6722 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6723 bool LLParser::ParseUseListOrderBB() {
6724 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6725 SMLoc Loc = Lex.getLoc();
6729 SmallVector<unsigned, 16> Indexes;
6730 if (ParseValID(Fn) ||
6731 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6732 ParseValID(Label) ||
6733 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6734 ParseUseListOrderIndexes(Indexes))
6737 // Check the function.
6739 if (Fn.Kind == ValID::t_GlobalName)
6740 GV = M->getNamedValue(Fn.StrVal);
6741 else if (Fn.Kind == ValID::t_GlobalID)
6742 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6744 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6746 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6747 auto *F = dyn_cast<Function>(GV);
6749 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6750 if (F->isDeclaration())
6751 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6753 // Check the basic block.
6754 if (Label.Kind == ValID::t_LocalID)
6755 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6756 if (Label.Kind != ValID::t_LocalName)
6757 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6758 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
6760 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6761 if (!isa<BasicBlock>(V))
6762 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6764 return sortUseListOrder(V, Indexes, Loc);