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/SmallPtrSet.h"
16 #include "llvm/AsmParser/SlotMapping.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/CallingConv.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/ValueSymbolTable.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.h"
35 static std::string getTypeString(Type *T) {
37 raw_string_ostream Tmp(Result);
42 /// Run: module ::= toplevelentity*
43 bool LLParser::Run() {
47 return ParseTopLevelEntities() ||
48 ValidateEndOfModule();
51 bool LLParser::parseStandaloneConstantValue(Constant *&C) {
55 if (ParseType(Ty) || parseConstantValue(Ty, C))
57 if (Lex.getKind() != lltok::Eof)
58 return Error(Lex.getLoc(), "expected end of string");
62 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64 bool LLParser::ValidateEndOfModule() {
65 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
66 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
68 // Handle any function attribute group forward references.
69 for (std::map<Value*, std::vector<unsigned> >::iterator
70 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
73 std::vector<unsigned> &Vec = I->second;
76 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
78 B.merge(NumberedAttrBuilders[*VI]);
80 if (Function *Fn = dyn_cast<Function>(V)) {
81 AttributeSet AS = Fn->getAttributes();
82 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84 AS.getFnAttributes());
88 // If the alignment was parsed as an attribute, move to the alignment
90 if (FnAttrs.hasAlignmentAttr()) {
91 Fn->setAlignment(FnAttrs.getAlignment());
92 FnAttrs.removeAttribute(Attribute::Alignment);
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
99 Fn->setAttributes(AS);
100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101 AttributeSet AS = CI->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
110 CI->setAttributes(AS);
111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112 AttributeSet AS = II->getAttributes();
113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115 AS.getFnAttributes());
117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118 AttributeSet::get(Context,
119 AttributeSet::FunctionIndex,
121 II->setAttributes(AS);
123 llvm_unreachable("invalid object with forward attribute group reference");
127 // If there are entries in ForwardRefBlockAddresses at this point, the
128 // function was never defined.
129 if (!ForwardRefBlockAddresses.empty())
130 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
131 "expected function name in blockaddress");
133 for (const auto &NT : NumberedTypes)
134 if (NT.second.second.isValid())
135 return Error(NT.second.second,
136 "use of undefined type '%" + Twine(NT.first) + "'");
138 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
139 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
140 if (I->second.second.isValid())
141 return Error(I->second.second,
142 "use of undefined type named '" + I->getKey() + "'");
144 if (!ForwardRefComdats.empty())
145 return Error(ForwardRefComdats.begin()->second,
146 "use of undefined comdat '$" +
147 ForwardRefComdats.begin()->first + "'");
149 if (!ForwardRefVals.empty())
150 return Error(ForwardRefVals.begin()->second.second,
151 "use of undefined value '@" + ForwardRefVals.begin()->first +
154 if (!ForwardRefValIDs.empty())
155 return Error(ForwardRefValIDs.begin()->second.second,
156 "use of undefined value '@" +
157 Twine(ForwardRefValIDs.begin()->first) + "'");
159 if (!ForwardRefMDNodes.empty())
160 return Error(ForwardRefMDNodes.begin()->second.second,
161 "use of undefined metadata '!" +
162 Twine(ForwardRefMDNodes.begin()->first) + "'");
164 // Resolve metadata cycles.
165 for (auto &N : NumberedMetadata) {
166 if (N.second && !N.second->isResolved())
167 N.second->resolveCycles();
170 // Look for intrinsic functions and CallInst that need to be upgraded
171 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
172 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
174 UpgradeDebugInfo(*M);
178 // Initialize the slot mapping.
179 // Because by this point we've parsed and validated everything, we can "steal"
180 // the mapping from LLParser as it doesn't need it anymore.
181 Slots->GlobalValues = std::move(NumberedVals);
182 Slots->MetadataNodes = std::move(NumberedMetadata);
187 //===----------------------------------------------------------------------===//
188 // Top-Level Entities
189 //===----------------------------------------------------------------------===//
191 bool LLParser::ParseTopLevelEntities() {
193 switch (Lex.getKind()) {
194 default: return TokError("expected top-level entity");
195 case lltok::Eof: return false;
196 case lltok::kw_declare: if (ParseDeclare()) return true; break;
197 case lltok::kw_define: if (ParseDefine()) return true; break;
198 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
199 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
200 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
201 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
202 case lltok::LocalVar: if (ParseNamedType()) return true; break;
203 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
204 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
205 case lltok::ComdatVar: if (parseComdat()) return true; break;
206 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
207 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
209 // The Global variable production with no name can have many different
210 // optional leading prefixes, the production is:
211 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
212 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
213 // ('constant'|'global') ...
214 case lltok::kw_private: // OptionalLinkage
215 case lltok::kw_internal: // OptionalLinkage
216 case lltok::kw_weak: // OptionalLinkage
217 case lltok::kw_weak_odr: // OptionalLinkage
218 case lltok::kw_linkonce: // OptionalLinkage
219 case lltok::kw_linkonce_odr: // OptionalLinkage
220 case lltok::kw_appending: // OptionalLinkage
221 case lltok::kw_common: // OptionalLinkage
222 case lltok::kw_extern_weak: // OptionalLinkage
223 case lltok::kw_external: // OptionalLinkage
224 case lltok::kw_default: // OptionalVisibility
225 case lltok::kw_hidden: // OptionalVisibility
226 case lltok::kw_protected: // OptionalVisibility
227 case lltok::kw_dllimport: // OptionalDLLStorageClass
228 case lltok::kw_dllexport: // OptionalDLLStorageClass
229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: { // GlobalType
233 unsigned Linkage, Visibility, DLLStorageClass;
235 GlobalVariable::ThreadLocalMode TLM;
237 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
238 ParseOptionalVisibility(Visibility) ||
239 ParseOptionalDLLStorageClass(DLLStorageClass) ||
240 ParseOptionalThreadLocal(TLM) ||
241 parseOptionalUnnamedAddr(UnnamedAddr) ||
242 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
243 DLLStorageClass, TLM, UnnamedAddr))
248 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
249 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
250 case lltok::kw_uselistorder_bb:
251 if (ParseUseListOrderBB()) return true; break;
258 /// ::= 'module' 'asm' STRINGCONSTANT
259 bool LLParser::ParseModuleAsm() {
260 assert(Lex.getKind() == lltok::kw_module);
264 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
265 ParseStringConstant(AsmStr)) return true;
267 M->appendModuleInlineAsm(AsmStr);
272 /// ::= 'target' 'triple' '=' STRINGCONSTANT
273 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
274 bool LLParser::ParseTargetDefinition() {
275 assert(Lex.getKind() == lltok::kw_target);
278 default: return TokError("unknown target property");
279 case lltok::kw_triple:
281 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
282 ParseStringConstant(Str))
284 M->setTargetTriple(Str);
286 case lltok::kw_datalayout:
288 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
289 ParseStringConstant(Str))
291 M->setDataLayout(Str);
297 /// ::= 'deplibs' '=' '[' ']'
298 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
299 /// FIXME: Remove in 4.0. Currently parse, but ignore.
300 bool LLParser::ParseDepLibs() {
301 assert(Lex.getKind() == lltok::kw_deplibs);
303 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
304 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
307 if (EatIfPresent(lltok::rsquare))
312 if (ParseStringConstant(Str)) return true;
313 } while (EatIfPresent(lltok::comma));
315 return ParseToken(lltok::rsquare, "expected ']' at end of list");
318 /// ParseUnnamedType:
319 /// ::= LocalVarID '=' 'type' type
320 bool LLParser::ParseUnnamedType() {
321 LocTy TypeLoc = Lex.getLoc();
322 unsigned TypeID = Lex.getUIntVal();
323 Lex.Lex(); // eat LocalVarID;
325 if (ParseToken(lltok::equal, "expected '=' after name") ||
326 ParseToken(lltok::kw_type, "expected 'type' after '='"))
329 Type *Result = nullptr;
330 if (ParseStructDefinition(TypeLoc, "",
331 NumberedTypes[TypeID], Result)) return true;
333 if (!isa<StructType>(Result)) {
334 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
336 return Error(TypeLoc, "non-struct types may not be recursive");
337 Entry.first = Result;
338 Entry.second = SMLoc();
346 /// ::= LocalVar '=' 'type' type
347 bool LLParser::ParseNamedType() {
348 std::string Name = Lex.getStrVal();
349 LocTy NameLoc = Lex.getLoc();
350 Lex.Lex(); // eat LocalVar.
352 if (ParseToken(lltok::equal, "expected '=' after name") ||
353 ParseToken(lltok::kw_type, "expected 'type' after name"))
356 Type *Result = nullptr;
357 if (ParseStructDefinition(NameLoc, Name,
358 NamedTypes[Name], Result)) return true;
360 if (!isa<StructType>(Result)) {
361 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
363 return Error(NameLoc, "non-struct types may not be recursive");
364 Entry.first = Result;
365 Entry.second = SMLoc();
373 /// ::= 'declare' FunctionHeader
374 bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
379 return ParseFunctionHeader(F, false);
383 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
384 bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
389 return ParseFunctionHeader(F, true) ||
390 ParseOptionalFunctionMetadata(*F) ||
391 ParseFunctionBody(*F);
397 bool LLParser::ParseGlobalType(bool &IsConstant) {
398 if (Lex.getKind() == lltok::kw_constant)
400 else if (Lex.getKind() == lltok::kw_global)
404 return TokError("expected 'global' or 'constant'");
410 /// ParseUnnamedGlobal:
411 /// OptionalVisibility ALIAS ...
412 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
413 /// ... -> global variable
414 /// GlobalID '=' OptionalVisibility ALIAS ...
415 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
416 /// ... -> global variable
417 bool LLParser::ParseUnnamedGlobal() {
418 unsigned VarID = NumberedVals.size();
420 LocTy NameLoc = Lex.getLoc();
422 // Handle the GlobalID form.
423 if (Lex.getKind() == lltok::GlobalID) {
424 if (Lex.getUIntVal() != VarID)
425 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
427 Lex.Lex(); // eat GlobalID;
429 if (ParseToken(lltok::equal, "expected '=' after name"))
434 unsigned Linkage, Visibility, DLLStorageClass;
435 GlobalVariable::ThreadLocalMode TLM;
437 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
438 ParseOptionalVisibility(Visibility) ||
439 ParseOptionalDLLStorageClass(DLLStorageClass) ||
440 ParseOptionalThreadLocal(TLM) ||
441 parseOptionalUnnamedAddr(UnnamedAddr))
444 if (Lex.getKind() != lltok::kw_alias)
445 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
446 DLLStorageClass, TLM, UnnamedAddr);
447 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
451 /// ParseNamedGlobal:
452 /// GlobalVar '=' OptionalVisibility ALIAS ...
453 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454 /// ... -> global variable
455 bool LLParser::ParseNamedGlobal() {
456 assert(Lex.getKind() == lltok::GlobalVar);
457 LocTy NameLoc = Lex.getLoc();
458 std::string Name = Lex.getStrVal();
462 unsigned Linkage, Visibility, DLLStorageClass;
463 GlobalVariable::ThreadLocalMode TLM;
465 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
466 ParseOptionalLinkage(Linkage, HasLinkage) ||
467 ParseOptionalVisibility(Visibility) ||
468 ParseOptionalDLLStorageClass(DLLStorageClass) ||
469 ParseOptionalThreadLocal(TLM) ||
470 parseOptionalUnnamedAddr(UnnamedAddr))
473 if (Lex.getKind() != lltok::kw_alias)
474 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
475 DLLStorageClass, TLM, UnnamedAddr);
477 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
481 bool LLParser::parseComdat() {
482 assert(Lex.getKind() == lltok::ComdatVar);
483 std::string Name = Lex.getStrVal();
484 LocTy NameLoc = Lex.getLoc();
487 if (ParseToken(lltok::equal, "expected '=' here"))
490 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
491 return TokError("expected comdat type");
493 Comdat::SelectionKind SK;
494 switch (Lex.getKind()) {
496 return TokError("unknown selection kind");
500 case lltok::kw_exactmatch:
501 SK = Comdat::ExactMatch;
503 case lltok::kw_largest:
504 SK = Comdat::Largest;
506 case lltok::kw_noduplicates:
507 SK = Comdat::NoDuplicates;
509 case lltok::kw_samesize:
510 SK = Comdat::SameSize;
515 // See if the comdat was forward referenced, if so, use the comdat.
516 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
517 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
518 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
519 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
522 if (I != ComdatSymTab.end())
525 C = M->getOrInsertComdat(Name);
526 C->setSelectionKind(SK);
532 // ::= '!' STRINGCONSTANT
533 bool LLParser::ParseMDString(MDString *&Result) {
535 if (ParseStringConstant(Str)) return true;
536 llvm::UpgradeMDStringConstant(Str);
537 Result = MDString::get(Context, Str);
542 // ::= '!' MDNodeNumber
543 bool LLParser::ParseMDNodeID(MDNode *&Result) {
544 // !{ ..., !42, ... }
546 if (ParseUInt32(MID))
549 // If not a forward reference, just return it now.
550 if (NumberedMetadata.count(MID)) {
551 Result = NumberedMetadata[MID];
555 // Otherwise, create MDNode forward reference.
556 auto &FwdRef = ForwardRefMDNodes[MID];
557 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
559 Result = FwdRef.first.get();
560 NumberedMetadata[MID].reset(Result);
564 /// ParseNamedMetadata:
565 /// !foo = !{ !1, !2 }
566 bool LLParser::ParseNamedMetadata() {
567 assert(Lex.getKind() == lltok::MetadataVar);
568 std::string Name = Lex.getStrVal();
571 if (ParseToken(lltok::equal, "expected '=' here") ||
572 ParseToken(lltok::exclaim, "Expected '!' here") ||
573 ParseToken(lltok::lbrace, "Expected '{' here"))
576 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
577 if (Lex.getKind() != lltok::rbrace)
579 if (ParseToken(lltok::exclaim, "Expected '!' here"))
583 if (ParseMDNodeID(N)) return true;
585 } while (EatIfPresent(lltok::comma));
587 return ParseToken(lltok::rbrace, "expected end of metadata node");
590 /// ParseStandaloneMetadata:
592 bool LLParser::ParseStandaloneMetadata() {
593 assert(Lex.getKind() == lltok::exclaim);
595 unsigned MetadataID = 0;
598 if (ParseUInt32(MetadataID) ||
599 ParseToken(lltok::equal, "expected '=' here"))
602 // Detect common error, from old metadata syntax.
603 if (Lex.getKind() == lltok::Type)
604 return TokError("unexpected type in metadata definition");
606 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
607 if (Lex.getKind() == lltok::MetadataVar) {
608 if (ParseSpecializedMDNode(Init, IsDistinct))
610 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
611 ParseMDTuple(Init, IsDistinct))
614 // See if this was forward referenced, if so, handle it.
615 auto FI = ForwardRefMDNodes.find(MetadataID);
616 if (FI != ForwardRefMDNodes.end()) {
617 FI->second.first->replaceAllUsesWith(Init);
618 ForwardRefMDNodes.erase(FI);
620 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
622 if (NumberedMetadata.count(MetadataID))
623 return TokError("Metadata id is already used");
624 NumberedMetadata[MetadataID].reset(Init);
630 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
631 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
632 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
636 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
637 /// OptionalDLLStorageClass OptionalThreadLocal
638 /// OptionalUnnamedAddr 'alias' Aliasee
643 /// Everything through OptionalUnnamedAddr has already been parsed.
645 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
646 unsigned Visibility, unsigned DLLStorageClass,
647 GlobalVariable::ThreadLocalMode TLM,
649 assert(Lex.getKind() == lltok::kw_alias);
652 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
654 if(!GlobalAlias::isValidLinkage(Linkage))
655 return Error(NameLoc, "invalid linkage type for alias");
657 if (!isValidVisibilityForLinkage(Visibility, L))
658 return Error(NameLoc,
659 "symbol with local linkage must have default visibility");
662 LocTy AliaseeLoc = Lex.getLoc();
663 if (Lex.getKind() != lltok::kw_bitcast &&
664 Lex.getKind() != lltok::kw_getelementptr &&
665 Lex.getKind() != lltok::kw_addrspacecast &&
666 Lex.getKind() != lltok::kw_inttoptr) {
667 if (ParseGlobalTypeAndValue(Aliasee))
670 // The bitcast dest type is not present, it is implied by the dest type.
674 if (ID.Kind != ValID::t_Constant)
675 return Error(AliaseeLoc, "invalid aliasee");
676 Aliasee = ID.ConstantVal;
679 Type *AliaseeType = Aliasee->getType();
680 auto *PTy = dyn_cast<PointerType>(AliaseeType);
682 return Error(AliaseeLoc, "An alias must have pointer type");
684 // Okay, create the alias but do not insert it into the module yet.
685 std::unique_ptr<GlobalAlias> GA(
686 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
687 Aliasee, /*Parent*/ nullptr));
688 GA->setThreadLocalMode(TLM);
689 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
690 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
691 GA->setUnnamedAddr(UnnamedAddr);
694 NumberedVals.push_back(GA.get());
696 // See if this value already exists in the symbol table. If so, it is either
697 // a redefinition or a definition of a forward reference.
698 if (GlobalValue *Val = M->getNamedValue(Name)) {
699 // See if this was a redefinition. If so, there is no entry in
701 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
702 I = ForwardRefVals.find(Name);
703 if (I == ForwardRefVals.end())
704 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
706 // Otherwise, this was a definition of forward ref. Verify that types
708 if (Val->getType() != GA->getType())
709 return Error(NameLoc,
710 "forward reference and definition of alias have different types");
712 // If they agree, just RAUW the old value with the alias and remove the
714 Val->replaceAllUsesWith(GA.get());
715 Val->eraseFromParent();
716 ForwardRefVals.erase(I);
719 // Insert into the module, we know its name won't collide now.
720 M->getAliasList().push_back(GA.get());
721 assert(GA->getName() == Name && "Should not be a name conflict!");
723 // The module owns this now
730 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
731 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
732 /// OptionalExternallyInitialized GlobalType Type Const
733 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
734 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
735 /// OptionalExternallyInitialized GlobalType Type Const
737 /// Everything up to and including OptionalUnnamedAddr has been parsed
740 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
741 unsigned Linkage, bool HasLinkage,
742 unsigned Visibility, unsigned DLLStorageClass,
743 GlobalVariable::ThreadLocalMode TLM,
745 if (!isValidVisibilityForLinkage(Visibility, Linkage))
746 return Error(NameLoc,
747 "symbol with local linkage must have default visibility");
750 bool IsConstant, IsExternallyInitialized;
751 LocTy IsExternallyInitializedLoc;
755 if (ParseOptionalAddrSpace(AddrSpace) ||
756 ParseOptionalToken(lltok::kw_externally_initialized,
757 IsExternallyInitialized,
758 &IsExternallyInitializedLoc) ||
759 ParseGlobalType(IsConstant) ||
760 ParseType(Ty, TyLoc))
763 // If the linkage is specified and is external, then no initializer is
765 Constant *Init = nullptr;
766 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
767 Linkage != GlobalValue::ExternalLinkage)) {
768 if (ParseGlobalValue(Ty, Init))
772 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
773 return Error(TyLoc, "invalid type for global variable");
775 GlobalValue *GVal = nullptr;
777 // See if the global was forward referenced, if so, use the global.
779 GVal = M->getNamedValue(Name);
781 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
785 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
786 I = ForwardRefValIDs.find(NumberedVals.size());
787 if (I != ForwardRefValIDs.end()) {
788 GVal = I->second.first;
789 ForwardRefValIDs.erase(I);
795 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
796 Name, nullptr, GlobalVariable::NotThreadLocal,
799 if (GVal->getValueType() != Ty)
801 "forward reference and definition of global have different types");
803 GV = cast<GlobalVariable>(GVal);
805 // Move the forward-reference to the correct spot in the module.
806 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
810 NumberedVals.push_back(GV);
812 // Set the parsed properties on the global.
814 GV->setInitializer(Init);
815 GV->setConstant(IsConstant);
816 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
817 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
818 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
819 GV->setExternallyInitialized(IsExternallyInitialized);
820 GV->setThreadLocalMode(TLM);
821 GV->setUnnamedAddr(UnnamedAddr);
823 // Parse attributes on the global.
824 while (Lex.getKind() == lltok::comma) {
827 if (Lex.getKind() == lltok::kw_section) {
829 GV->setSection(Lex.getStrVal());
830 if (ParseToken(lltok::StringConstant, "expected global section string"))
832 } else if (Lex.getKind() == lltok::kw_align) {
834 if (ParseOptionalAlignment(Alignment)) return true;
835 GV->setAlignment(Alignment);
838 if (parseOptionalComdat(Name, C))
843 return TokError("unknown global variable property!");
850 /// ParseUnnamedAttrGrp
851 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
852 bool LLParser::ParseUnnamedAttrGrp() {
853 assert(Lex.getKind() == lltok::kw_attributes);
854 LocTy AttrGrpLoc = Lex.getLoc();
857 if (Lex.getKind() != lltok::AttrGrpID)
858 return TokError("expected attribute group id");
860 unsigned VarID = Lex.getUIntVal();
861 std::vector<unsigned> unused;
865 if (ParseToken(lltok::equal, "expected '=' here") ||
866 ParseToken(lltok::lbrace, "expected '{' here") ||
867 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
869 ParseToken(lltok::rbrace, "expected end of attribute group"))
872 if (!NumberedAttrBuilders[VarID].hasAttributes())
873 return Error(AttrGrpLoc, "attribute group has no attributes");
878 /// ParseFnAttributeValuePairs
879 /// ::= <attr> | <attr> '=' <value>
880 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
881 std::vector<unsigned> &FwdRefAttrGrps,
882 bool inAttrGrp, LocTy &BuiltinLoc) {
883 bool HaveError = false;
888 lltok::Kind Token = Lex.getKind();
889 if (Token == lltok::kw_builtin)
890 BuiltinLoc = Lex.getLoc();
893 if (!inAttrGrp) return HaveError;
894 return Error(Lex.getLoc(), "unterminated attribute group");
899 case lltok::AttrGrpID: {
900 // Allow a function to reference an attribute group:
902 // define void @foo() #1 { ... }
906 "cannot have an attribute group reference in an attribute group");
908 unsigned AttrGrpNum = Lex.getUIntVal();
909 if (inAttrGrp) break;
911 // Save the reference to the attribute group. We'll fill it in later.
912 FwdRefAttrGrps.push_back(AttrGrpNum);
915 // Target-dependent attributes:
916 case lltok::StringConstant: {
917 std::string Attr = Lex.getStrVal();
920 if (EatIfPresent(lltok::equal) &&
921 ParseStringConstant(Val))
924 B.addAttribute(Attr, Val);
928 // Target-independent attributes:
929 case lltok::kw_align: {
930 // As a hack, we allow function alignment to be initially parsed as an
931 // attribute on a function declaration/definition or added to an attribute
932 // group and later moved to the alignment field.
936 if (ParseToken(lltok::equal, "expected '=' here") ||
937 ParseUInt32(Alignment))
940 if (ParseOptionalAlignment(Alignment))
943 B.addAlignmentAttr(Alignment);
946 case lltok::kw_alignstack: {
950 if (ParseToken(lltok::equal, "expected '=' here") ||
951 ParseUInt32(Alignment))
954 if (ParseOptionalStackAlignment(Alignment))
957 B.addStackAlignmentAttr(Alignment);
960 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
961 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
962 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
963 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
964 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
965 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
966 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
967 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
968 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
969 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
970 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
971 case lltok::kw_noimplicitfloat:
972 B.addAttribute(Attribute::NoImplicitFloat); break;
973 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
974 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
975 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
976 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
977 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
978 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
979 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
980 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
981 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
982 case lltok::kw_returns_twice:
983 B.addAttribute(Attribute::ReturnsTwice); break;
984 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
985 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
986 case lltok::kw_sspstrong:
987 B.addAttribute(Attribute::StackProtectStrong); break;
988 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
989 case lltok::kw_sanitize_address:
990 B.addAttribute(Attribute::SanitizeAddress); break;
991 case lltok::kw_sanitize_thread:
992 B.addAttribute(Attribute::SanitizeThread); break;
993 case lltok::kw_sanitize_memory:
994 B.addAttribute(Attribute::SanitizeMemory); break;
995 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
998 case lltok::kw_inreg:
999 case lltok::kw_signext:
1000 case lltok::kw_zeroext:
1003 "invalid use of attribute on a function");
1005 case lltok::kw_byval:
1006 case lltok::kw_dereferenceable:
1007 case lltok::kw_dereferenceable_or_null:
1008 case lltok::kw_inalloca:
1009 case lltok::kw_nest:
1010 case lltok::kw_noalias:
1011 case lltok::kw_nocapture:
1012 case lltok::kw_nonnull:
1013 case lltok::kw_returned:
1014 case lltok::kw_sret:
1017 "invalid use of parameter-only attribute on a function");
1025 //===----------------------------------------------------------------------===//
1026 // GlobalValue Reference/Resolution Routines.
1027 //===----------------------------------------------------------------------===//
1029 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1030 /// forward reference record if needed. This can return null if the value
1031 /// exists but does not have the right type.
1032 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1034 PointerType *PTy = dyn_cast<PointerType>(Ty);
1036 Error(Loc, "global variable reference must have pointer type");
1040 // Look this name up in the normal function symbol table.
1042 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1044 // If this is a forward reference for the value, see if we already created a
1045 // forward ref record.
1047 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1048 I = ForwardRefVals.find(Name);
1049 if (I != ForwardRefVals.end())
1050 Val = I->second.first;
1053 // If we have the value in the symbol table or fwd-ref table, return it.
1055 if (Val->getType() == Ty) return Val;
1056 Error(Loc, "'@" + Name + "' defined with type '" +
1057 getTypeString(Val->getType()) + "'");
1061 // Otherwise, create a new forward reference for this value and remember it.
1062 GlobalValue *FwdVal;
1063 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1064 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1066 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1067 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1068 nullptr, GlobalVariable::NotThreadLocal,
1069 PTy->getAddressSpace());
1071 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1075 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1076 PointerType *PTy = dyn_cast<PointerType>(Ty);
1078 Error(Loc, "global variable reference must have pointer type");
1082 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1084 // If this is a forward reference for the value, see if we already created a
1085 // forward ref record.
1087 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1088 I = ForwardRefValIDs.find(ID);
1089 if (I != ForwardRefValIDs.end())
1090 Val = I->second.first;
1093 // If we have the value in the symbol table or fwd-ref table, return it.
1095 if (Val->getType() == Ty) return Val;
1096 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1097 getTypeString(Val->getType()) + "'");
1101 // Otherwise, create a new forward reference for this value and remember it.
1102 GlobalValue *FwdVal;
1103 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1104 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1106 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1107 GlobalValue::ExternalWeakLinkage, nullptr, "");
1109 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1114 //===----------------------------------------------------------------------===//
1115 // Comdat Reference/Resolution Routines.
1116 //===----------------------------------------------------------------------===//
1118 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1119 // Look this name up in the comdat symbol table.
1120 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1121 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1122 if (I != ComdatSymTab.end())
1125 // Otherwise, create a new forward reference for this value and remember it.
1126 Comdat *C = M->getOrInsertComdat(Name);
1127 ForwardRefComdats[Name] = Loc;
1132 //===----------------------------------------------------------------------===//
1134 //===----------------------------------------------------------------------===//
1136 /// ParseToken - If the current token has the specified kind, eat it and return
1137 /// success. Otherwise, emit the specified error and return failure.
1138 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1139 if (Lex.getKind() != T)
1140 return TokError(ErrMsg);
1145 /// ParseStringConstant
1146 /// ::= StringConstant
1147 bool LLParser::ParseStringConstant(std::string &Result) {
1148 if (Lex.getKind() != lltok::StringConstant)
1149 return TokError("expected string constant");
1150 Result = Lex.getStrVal();
1157 bool LLParser::ParseUInt32(unsigned &Val) {
1158 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1159 return TokError("expected integer");
1160 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1161 if (Val64 != unsigned(Val64))
1162 return TokError("expected 32-bit integer (too large)");
1170 bool LLParser::ParseUInt64(uint64_t &Val) {
1171 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1172 return TokError("expected integer");
1173 Val = Lex.getAPSIntVal().getLimitedValue();
1179 /// := 'localdynamic'
1180 /// := 'initialexec'
1182 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1183 switch (Lex.getKind()) {
1185 return TokError("expected localdynamic, initialexec or localexec");
1186 case lltok::kw_localdynamic:
1187 TLM = GlobalVariable::LocalDynamicTLSModel;
1189 case lltok::kw_initialexec:
1190 TLM = GlobalVariable::InitialExecTLSModel;
1192 case lltok::kw_localexec:
1193 TLM = GlobalVariable::LocalExecTLSModel;
1201 /// ParseOptionalThreadLocal
1203 /// := 'thread_local'
1204 /// := 'thread_local' '(' tlsmodel ')'
1205 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1206 TLM = GlobalVariable::NotThreadLocal;
1207 if (!EatIfPresent(lltok::kw_thread_local))
1210 TLM = GlobalVariable::GeneralDynamicTLSModel;
1211 if (Lex.getKind() == lltok::lparen) {
1213 return ParseTLSModel(TLM) ||
1214 ParseToken(lltok::rparen, "expected ')' after thread local model");
1219 /// ParseOptionalAddrSpace
1221 /// := 'addrspace' '(' uint32 ')'
1222 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1224 if (!EatIfPresent(lltok::kw_addrspace))
1226 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1227 ParseUInt32(AddrSpace) ||
1228 ParseToken(lltok::rparen, "expected ')' in address space");
1231 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1232 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1233 bool HaveError = false;
1238 lltok::Kind Token = Lex.getKind();
1240 default: // End of attributes.
1242 case lltok::kw_align: {
1244 if (ParseOptionalAlignment(Alignment))
1246 B.addAlignmentAttr(Alignment);
1249 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1250 case lltok::kw_dereferenceable: {
1252 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1254 B.addDereferenceableAttr(Bytes);
1257 case lltok::kw_dereferenceable_or_null: {
1259 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1261 B.addDereferenceableOrNullAttr(Bytes);
1264 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1265 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1266 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1267 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1268 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1269 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1270 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1271 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1272 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1273 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1274 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1275 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1277 case lltok::kw_alignstack:
1278 case lltok::kw_alwaysinline:
1279 case lltok::kw_argmemonly:
1280 case lltok::kw_builtin:
1281 case lltok::kw_inlinehint:
1282 case lltok::kw_jumptable:
1283 case lltok::kw_minsize:
1284 case lltok::kw_naked:
1285 case lltok::kw_nobuiltin:
1286 case lltok::kw_noduplicate:
1287 case lltok::kw_noimplicitfloat:
1288 case lltok::kw_noinline:
1289 case lltok::kw_nonlazybind:
1290 case lltok::kw_noredzone:
1291 case lltok::kw_noreturn:
1292 case lltok::kw_nounwind:
1293 case lltok::kw_optnone:
1294 case lltok::kw_optsize:
1295 case lltok::kw_returns_twice:
1296 case lltok::kw_sanitize_address:
1297 case lltok::kw_sanitize_memory:
1298 case lltok::kw_sanitize_thread:
1300 case lltok::kw_sspreq:
1301 case lltok::kw_sspstrong:
1302 case lltok::kw_safestack:
1303 case lltok::kw_uwtable:
1304 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1312 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1313 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1314 bool HaveError = false;
1319 lltok::Kind Token = Lex.getKind();
1321 default: // End of attributes.
1323 case lltok::kw_dereferenceable: {
1325 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1327 B.addDereferenceableAttr(Bytes);
1330 case lltok::kw_dereferenceable_or_null: {
1332 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1334 B.addDereferenceableOrNullAttr(Bytes);
1337 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1338 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1339 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1340 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1341 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1344 case lltok::kw_align:
1345 case lltok::kw_byval:
1346 case lltok::kw_inalloca:
1347 case lltok::kw_nest:
1348 case lltok::kw_nocapture:
1349 case lltok::kw_returned:
1350 case lltok::kw_sret:
1351 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1354 case lltok::kw_alignstack:
1355 case lltok::kw_alwaysinline:
1356 case lltok::kw_argmemonly:
1357 case lltok::kw_builtin:
1358 case lltok::kw_cold:
1359 case lltok::kw_inlinehint:
1360 case lltok::kw_jumptable:
1361 case lltok::kw_minsize:
1362 case lltok::kw_naked:
1363 case lltok::kw_nobuiltin:
1364 case lltok::kw_noduplicate:
1365 case lltok::kw_noimplicitfloat:
1366 case lltok::kw_noinline:
1367 case lltok::kw_nonlazybind:
1368 case lltok::kw_noredzone:
1369 case lltok::kw_noreturn:
1370 case lltok::kw_nounwind:
1371 case lltok::kw_optnone:
1372 case lltok::kw_optsize:
1373 case lltok::kw_returns_twice:
1374 case lltok::kw_sanitize_address:
1375 case lltok::kw_sanitize_memory:
1376 case lltok::kw_sanitize_thread:
1378 case lltok::kw_sspreq:
1379 case lltok::kw_sspstrong:
1380 case lltok::kw_safestack:
1381 case lltok::kw_uwtable:
1382 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1385 case lltok::kw_readnone:
1386 case lltok::kw_readonly:
1387 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1394 /// ParseOptionalLinkage
1401 /// ::= 'linkonce_odr'
1402 /// ::= 'available_externally'
1405 /// ::= 'extern_weak'
1407 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1409 switch (Lex.getKind()) {
1410 default: Res=GlobalValue::ExternalLinkage; return false;
1411 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1412 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1413 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1414 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1415 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1416 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1417 case lltok::kw_available_externally:
1418 Res = GlobalValue::AvailableExternallyLinkage;
1420 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1421 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1422 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1423 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1430 /// ParseOptionalVisibility
1436 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1437 switch (Lex.getKind()) {
1438 default: Res = GlobalValue::DefaultVisibility; return false;
1439 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1440 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1441 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1447 /// ParseOptionalDLLStorageClass
1452 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1453 switch (Lex.getKind()) {
1454 default: Res = GlobalValue::DefaultStorageClass; return false;
1455 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1456 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1462 /// ParseOptionalCallingConv
1466 /// ::= 'intel_ocl_bicc'
1468 /// ::= 'x86_stdcallcc'
1469 /// ::= 'x86_fastcallcc'
1470 /// ::= 'x86_thiscallcc'
1471 /// ::= 'x86_vectorcallcc'
1472 /// ::= 'arm_apcscc'
1473 /// ::= 'arm_aapcscc'
1474 /// ::= 'arm_aapcs_vfpcc'
1475 /// ::= 'msp430_intrcc'
1476 /// ::= 'ptx_kernel'
1477 /// ::= 'ptx_device'
1479 /// ::= 'spir_kernel'
1480 /// ::= 'x86_64_sysvcc'
1481 /// ::= 'x86_64_win64cc'
1482 /// ::= 'webkit_jscc'
1484 /// ::= 'preserve_mostcc'
1485 /// ::= 'preserve_allcc'
1489 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1490 switch (Lex.getKind()) {
1491 default: CC = CallingConv::C; return false;
1492 case lltok::kw_ccc: CC = CallingConv::C; break;
1493 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1494 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1495 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1496 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1497 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1498 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1499 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1500 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1501 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1502 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1503 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1504 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1505 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1506 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1507 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1508 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1509 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1510 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1511 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1512 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1513 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1514 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1515 case lltok::kw_cc: {
1517 return ParseUInt32(CC);
1525 /// ParseMetadataAttachment
1527 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1528 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1530 std::string Name = Lex.getStrVal();
1531 Kind = M->getMDKindID(Name);
1534 return ParseMDNode(MD);
1537 /// ParseInstructionMetadata
1538 /// ::= !dbg !42 (',' !dbg !57)*
1539 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1541 if (Lex.getKind() != lltok::MetadataVar)
1542 return TokError("expected metadata after comma");
1546 if (ParseMetadataAttachment(MDK, N))
1549 Inst.setMetadata(MDK, N);
1550 if (MDK == LLVMContext::MD_tbaa)
1551 InstsWithTBAATag.push_back(&Inst);
1553 // If this is the end of the list, we're done.
1554 } while (EatIfPresent(lltok::comma));
1558 /// ParseOptionalFunctionMetadata
1560 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1561 while (Lex.getKind() == lltok::MetadataVar) {
1564 if (ParseMetadataAttachment(MDK, N))
1567 F.setMetadata(MDK, N);
1572 /// ParseOptionalAlignment
1575 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1577 if (!EatIfPresent(lltok::kw_align))
1579 LocTy AlignLoc = Lex.getLoc();
1580 if (ParseUInt32(Alignment)) return true;
1581 if (!isPowerOf2_32(Alignment))
1582 return Error(AlignLoc, "alignment is not a power of two");
1583 if (Alignment > Value::MaximumAlignment)
1584 return Error(AlignLoc, "huge alignments are not supported yet");
1588 /// ParseOptionalDerefAttrBytes
1590 /// ::= AttrKind '(' 4 ')'
1592 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1593 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1595 assert((AttrKind == lltok::kw_dereferenceable ||
1596 AttrKind == lltok::kw_dereferenceable_or_null) &&
1600 if (!EatIfPresent(AttrKind))
1602 LocTy ParenLoc = Lex.getLoc();
1603 if (!EatIfPresent(lltok::lparen))
1604 return Error(ParenLoc, "expected '('");
1605 LocTy DerefLoc = Lex.getLoc();
1606 if (ParseUInt64(Bytes)) return true;
1607 ParenLoc = Lex.getLoc();
1608 if (!EatIfPresent(lltok::rparen))
1609 return Error(ParenLoc, "expected ')'");
1611 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1615 /// ParseOptionalCommaAlign
1619 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1621 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1622 bool &AteExtraComma) {
1623 AteExtraComma = false;
1624 while (EatIfPresent(lltok::comma)) {
1625 // Metadata at the end is an early exit.
1626 if (Lex.getKind() == lltok::MetadataVar) {
1627 AteExtraComma = true;
1631 if (Lex.getKind() != lltok::kw_align)
1632 return Error(Lex.getLoc(), "expected metadata or 'align'");
1634 if (ParseOptionalAlignment(Alignment)) return true;
1640 /// ParseScopeAndOrdering
1641 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1644 /// This sets Scope and Ordering to the parsed values.
1645 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1646 AtomicOrdering &Ordering) {
1650 Scope = CrossThread;
1651 if (EatIfPresent(lltok::kw_singlethread))
1652 Scope = SingleThread;
1654 return ParseOrdering(Ordering);
1658 /// ::= AtomicOrdering
1660 /// This sets Ordering to the parsed value.
1661 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1662 switch (Lex.getKind()) {
1663 default: return TokError("Expected ordering on atomic instruction");
1664 case lltok::kw_unordered: Ordering = Unordered; break;
1665 case lltok::kw_monotonic: Ordering = Monotonic; break;
1666 case lltok::kw_acquire: Ordering = Acquire; break;
1667 case lltok::kw_release: Ordering = Release; break;
1668 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1669 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1675 /// ParseOptionalStackAlignment
1677 /// ::= 'alignstack' '(' 4 ')'
1678 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1680 if (!EatIfPresent(lltok::kw_alignstack))
1682 LocTy ParenLoc = Lex.getLoc();
1683 if (!EatIfPresent(lltok::lparen))
1684 return Error(ParenLoc, "expected '('");
1685 LocTy AlignLoc = Lex.getLoc();
1686 if (ParseUInt32(Alignment)) return true;
1687 ParenLoc = Lex.getLoc();
1688 if (!EatIfPresent(lltok::rparen))
1689 return Error(ParenLoc, "expected ')'");
1690 if (!isPowerOf2_32(Alignment))
1691 return Error(AlignLoc, "stack alignment is not a power of two");
1695 /// ParseIndexList - This parses the index list for an insert/extractvalue
1696 /// instruction. This sets AteExtraComma in the case where we eat an extra
1697 /// comma at the end of the line and find that it is followed by metadata.
1698 /// Clients that don't allow metadata can call the version of this function that
1699 /// only takes one argument.
1702 /// ::= (',' uint32)+
1704 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1705 bool &AteExtraComma) {
1706 AteExtraComma = false;
1708 if (Lex.getKind() != lltok::comma)
1709 return TokError("expected ',' as start of index list");
1711 while (EatIfPresent(lltok::comma)) {
1712 if (Lex.getKind() == lltok::MetadataVar) {
1713 if (Indices.empty()) return TokError("expected index");
1714 AteExtraComma = true;
1718 if (ParseUInt32(Idx)) return true;
1719 Indices.push_back(Idx);
1725 //===----------------------------------------------------------------------===//
1727 //===----------------------------------------------------------------------===//
1729 /// ParseType - Parse a type.
1730 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1731 SMLoc TypeLoc = Lex.getLoc();
1732 switch (Lex.getKind()) {
1734 return TokError(Msg);
1736 // Type ::= 'float' | 'void' (etc)
1737 Result = Lex.getTyVal();
1741 // Type ::= StructType
1742 if (ParseAnonStructType(Result, false))
1745 case lltok::lsquare:
1746 // Type ::= '[' ... ']'
1747 Lex.Lex(); // eat the lsquare.
1748 if (ParseArrayVectorType(Result, false))
1751 case lltok::less: // Either vector or packed struct.
1752 // Type ::= '<' ... '>'
1754 if (Lex.getKind() == lltok::lbrace) {
1755 if (ParseAnonStructType(Result, true) ||
1756 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1758 } else if (ParseArrayVectorType(Result, true))
1761 case lltok::LocalVar: {
1763 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1765 // If the type hasn't been defined yet, create a forward definition and
1766 // remember where that forward def'n was seen (in case it never is defined).
1768 Entry.first = StructType::create(Context, Lex.getStrVal());
1769 Entry.second = Lex.getLoc();
1771 Result = Entry.first;
1776 case lltok::LocalVarID: {
1778 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1780 // If the type hasn't been defined yet, create a forward definition and
1781 // remember where that forward def'n was seen (in case it never is defined).
1783 Entry.first = StructType::create(Context);
1784 Entry.second = Lex.getLoc();
1786 Result = Entry.first;
1792 // Parse the type suffixes.
1794 switch (Lex.getKind()) {
1797 if (!AllowVoid && Result->isVoidTy())
1798 return Error(TypeLoc, "void type only allowed for function results");
1801 // Type ::= Type '*'
1803 if (Result->isLabelTy())
1804 return TokError("basic block pointers are invalid");
1805 if (Result->isVoidTy())
1806 return TokError("pointers to void are invalid - use i8* instead");
1807 if (!PointerType::isValidElementType(Result))
1808 return TokError("pointer to this type is invalid");
1809 Result = PointerType::getUnqual(Result);
1813 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1814 case lltok::kw_addrspace: {
1815 if (Result->isLabelTy())
1816 return TokError("basic block pointers are invalid");
1817 if (Result->isVoidTy())
1818 return TokError("pointers to void are invalid; use i8* instead");
1819 if (!PointerType::isValidElementType(Result))
1820 return TokError("pointer to this type is invalid");
1822 if (ParseOptionalAddrSpace(AddrSpace) ||
1823 ParseToken(lltok::star, "expected '*' in address space"))
1826 Result = PointerType::get(Result, AddrSpace);
1830 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1832 if (ParseFunctionType(Result))
1839 /// ParseParameterList
1841 /// ::= '(' Arg (',' Arg)* ')'
1843 /// ::= Type OptionalAttributes Value OptionalAttributes
1844 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1845 PerFunctionState &PFS, bool IsMustTailCall,
1846 bool InVarArgsFunc) {
1847 if (ParseToken(lltok::lparen, "expected '(' in call"))
1850 unsigned AttrIndex = 1;
1851 while (Lex.getKind() != lltok::rparen) {
1852 // If this isn't the first argument, we need a comma.
1853 if (!ArgList.empty() &&
1854 ParseToken(lltok::comma, "expected ',' in argument list"))
1857 // Parse an ellipsis if this is a musttail call in a variadic function.
1858 if (Lex.getKind() == lltok::dotdotdot) {
1859 const char *Msg = "unexpected ellipsis in argument list for ";
1860 if (!IsMustTailCall)
1861 return TokError(Twine(Msg) + "non-musttail call");
1863 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1864 Lex.Lex(); // Lex the '...', it is purely for readability.
1865 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1868 // Parse the argument.
1870 Type *ArgTy = nullptr;
1871 AttrBuilder ArgAttrs;
1873 if (ParseType(ArgTy, ArgLoc))
1876 if (ArgTy->isMetadataTy()) {
1877 if (ParseMetadataAsValue(V, PFS))
1880 // Otherwise, handle normal operands.
1881 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1884 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1889 if (IsMustTailCall && InVarArgsFunc)
1890 return TokError("expected '...' at end of argument list for musttail call "
1891 "in varargs function");
1893 Lex.Lex(); // Lex the ')'.
1899 /// ParseArgumentList - Parse the argument list for a function type or function
1901 /// ::= '(' ArgTypeListI ')'
1905 /// ::= ArgTypeList ',' '...'
1906 /// ::= ArgType (',' ArgType)*
1908 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1911 assert(Lex.getKind() == lltok::lparen);
1912 Lex.Lex(); // eat the (.
1914 if (Lex.getKind() == lltok::rparen) {
1916 } else if (Lex.getKind() == lltok::dotdotdot) {
1920 LocTy TypeLoc = Lex.getLoc();
1921 Type *ArgTy = nullptr;
1925 if (ParseType(ArgTy) ||
1926 ParseOptionalParamAttrs(Attrs)) return true;
1928 if (ArgTy->isVoidTy())
1929 return Error(TypeLoc, "argument can not have void type");
1931 if (Lex.getKind() == lltok::LocalVar) {
1932 Name = Lex.getStrVal();
1936 if (!FunctionType::isValidArgumentType(ArgTy))
1937 return Error(TypeLoc, "invalid type for function argument");
1939 unsigned AttrIndex = 1;
1940 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1941 AttrIndex++, Attrs),
1944 while (EatIfPresent(lltok::comma)) {
1945 // Handle ... at end of arg list.
1946 if (EatIfPresent(lltok::dotdotdot)) {
1951 // Otherwise must be an argument type.
1952 TypeLoc = Lex.getLoc();
1953 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1955 if (ArgTy->isVoidTy())
1956 return Error(TypeLoc, "argument can not have void type");
1958 if (Lex.getKind() == lltok::LocalVar) {
1959 Name = Lex.getStrVal();
1965 if (!ArgTy->isFirstClassType())
1966 return Error(TypeLoc, "invalid type for function argument");
1968 ArgList.emplace_back(
1970 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1975 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1978 /// ParseFunctionType
1979 /// ::= Type ArgumentList OptionalAttrs
1980 bool LLParser::ParseFunctionType(Type *&Result) {
1981 assert(Lex.getKind() == lltok::lparen);
1983 if (!FunctionType::isValidReturnType(Result))
1984 return TokError("invalid function return type");
1986 SmallVector<ArgInfo, 8> ArgList;
1988 if (ParseArgumentList(ArgList, isVarArg))
1991 // Reject names on the arguments lists.
1992 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1993 if (!ArgList[i].Name.empty())
1994 return Error(ArgList[i].Loc, "argument name invalid in function type");
1995 if (ArgList[i].Attrs.hasAttributes(i + 1))
1996 return Error(ArgList[i].Loc,
1997 "argument attributes invalid in function type");
2000 SmallVector<Type*, 16> ArgListTy;
2001 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2002 ArgListTy.push_back(ArgList[i].Ty);
2004 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2008 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2010 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2011 SmallVector<Type*, 8> Elts;
2012 if (ParseStructBody(Elts)) return true;
2014 Result = StructType::get(Context, Elts, Packed);
2018 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2019 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2020 std::pair<Type*, LocTy> &Entry,
2022 // If the type was already defined, diagnose the redefinition.
2023 if (Entry.first && !Entry.second.isValid())
2024 return Error(TypeLoc, "redefinition of type");
2026 // If we have opaque, just return without filling in the definition for the
2027 // struct. This counts as a definition as far as the .ll file goes.
2028 if (EatIfPresent(lltok::kw_opaque)) {
2029 // This type is being defined, so clear the location to indicate this.
2030 Entry.second = SMLoc();
2032 // If this type number has never been uttered, create it.
2034 Entry.first = StructType::create(Context, Name);
2035 ResultTy = Entry.first;
2039 // If the type starts with '<', then it is either a packed struct or a vector.
2040 bool isPacked = EatIfPresent(lltok::less);
2042 // If we don't have a struct, then we have a random type alias, which we
2043 // accept for compatibility with old files. These types are not allowed to be
2044 // forward referenced and not allowed to be recursive.
2045 if (Lex.getKind() != lltok::lbrace) {
2047 return Error(TypeLoc, "forward references to non-struct type");
2051 return ParseArrayVectorType(ResultTy, true);
2052 return ParseType(ResultTy);
2055 // This type is being defined, so clear the location to indicate this.
2056 Entry.second = SMLoc();
2058 // If this type number has never been uttered, create it.
2060 Entry.first = StructType::create(Context, Name);
2062 StructType *STy = cast<StructType>(Entry.first);
2064 SmallVector<Type*, 8> Body;
2065 if (ParseStructBody(Body) ||
2066 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2069 STy->setBody(Body, isPacked);
2075 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2078 /// ::= '{' Type (',' Type)* '}'
2079 /// ::= '<' '{' '}' '>'
2080 /// ::= '<' '{' Type (',' Type)* '}' '>'
2081 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2082 assert(Lex.getKind() == lltok::lbrace);
2083 Lex.Lex(); // Consume the '{'
2085 // Handle the empty struct.
2086 if (EatIfPresent(lltok::rbrace))
2089 LocTy EltTyLoc = Lex.getLoc();
2091 if (ParseType(Ty)) return true;
2094 if (!StructType::isValidElementType(Ty))
2095 return Error(EltTyLoc, "invalid element type for struct");
2097 while (EatIfPresent(lltok::comma)) {
2098 EltTyLoc = Lex.getLoc();
2099 if (ParseType(Ty)) return true;
2101 if (!StructType::isValidElementType(Ty))
2102 return Error(EltTyLoc, "invalid element type for struct");
2107 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2110 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2111 /// token has already been consumed.
2113 /// ::= '[' APSINTVAL 'x' Types ']'
2114 /// ::= '<' APSINTVAL 'x' Types '>'
2115 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2116 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2117 Lex.getAPSIntVal().getBitWidth() > 64)
2118 return TokError("expected number in address space");
2120 LocTy SizeLoc = Lex.getLoc();
2121 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2124 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2127 LocTy TypeLoc = Lex.getLoc();
2128 Type *EltTy = nullptr;
2129 if (ParseType(EltTy)) return true;
2131 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2132 "expected end of sequential type"))
2137 return Error(SizeLoc, "zero element vector is illegal");
2138 if ((unsigned)Size != Size)
2139 return Error(SizeLoc, "size too large for vector");
2140 if (!VectorType::isValidElementType(EltTy))
2141 return Error(TypeLoc, "invalid vector element type");
2142 Result = VectorType::get(EltTy, unsigned(Size));
2144 if (!ArrayType::isValidElementType(EltTy))
2145 return Error(TypeLoc, "invalid array element type");
2146 Result = ArrayType::get(EltTy, Size);
2151 //===----------------------------------------------------------------------===//
2152 // Function Semantic Analysis.
2153 //===----------------------------------------------------------------------===//
2155 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2157 : P(p), F(f), FunctionNumber(functionNumber) {
2159 // Insert unnamed arguments into the NumberedVals list.
2160 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2163 NumberedVals.push_back(AI);
2166 LLParser::PerFunctionState::~PerFunctionState() {
2167 // If there were any forward referenced non-basicblock values, delete them.
2168 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2169 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2170 if (!isa<BasicBlock>(I->second.first)) {
2171 I->second.first->replaceAllUsesWith(
2172 UndefValue::get(I->second.first->getType()));
2173 delete I->second.first;
2174 I->second.first = nullptr;
2177 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2178 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2179 if (!isa<BasicBlock>(I->second.first)) {
2180 I->second.first->replaceAllUsesWith(
2181 UndefValue::get(I->second.first->getType()));
2182 delete I->second.first;
2183 I->second.first = nullptr;
2187 bool LLParser::PerFunctionState::FinishFunction() {
2188 if (!ForwardRefVals.empty())
2189 return P.Error(ForwardRefVals.begin()->second.second,
2190 "use of undefined value '%" + ForwardRefVals.begin()->first +
2192 if (!ForwardRefValIDs.empty())
2193 return P.Error(ForwardRefValIDs.begin()->second.second,
2194 "use of undefined value '%" +
2195 Twine(ForwardRefValIDs.begin()->first) + "'");
2200 /// GetVal - Get a value with the specified name or ID, creating a
2201 /// forward reference record if needed. This can return null if the value
2202 /// exists but does not have the right type.
2203 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2204 Type *Ty, LocTy Loc) {
2205 // Look this name up in the normal function symbol table.
2206 Value *Val = F.getValueSymbolTable().lookup(Name);
2208 // If this is a forward reference for the value, see if we already created a
2209 // forward ref record.
2211 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2212 I = ForwardRefVals.find(Name);
2213 if (I != ForwardRefVals.end())
2214 Val = I->second.first;
2217 // If we have the value in the symbol table or fwd-ref table, return it.
2219 if (Val->getType() == Ty) return Val;
2220 if (Ty->isLabelTy())
2221 P.Error(Loc, "'%" + Name + "' is not a basic block");
2223 P.Error(Loc, "'%" + Name + "' defined with type '" +
2224 getTypeString(Val->getType()) + "'");
2228 // Don't make placeholders with invalid type.
2229 if (!Ty->isFirstClassType()) {
2230 P.Error(Loc, "invalid use of a non-first-class type");
2234 // Otherwise, create a new forward reference for this value and remember it.
2236 if (Ty->isLabelTy())
2237 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2239 FwdVal = new Argument(Ty, Name);
2241 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2245 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2247 // Look this name up in the normal function symbol table.
2248 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2250 // If this is a forward reference for the value, see if we already created a
2251 // forward ref record.
2253 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2254 I = ForwardRefValIDs.find(ID);
2255 if (I != ForwardRefValIDs.end())
2256 Val = I->second.first;
2259 // If we have the value in the symbol table or fwd-ref table, return it.
2261 if (Val->getType() == Ty) return Val;
2262 if (Ty->isLabelTy())
2263 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2265 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2266 getTypeString(Val->getType()) + "'");
2270 if (!Ty->isFirstClassType()) {
2271 P.Error(Loc, "invalid use of a non-first-class type");
2275 // Otherwise, create a new forward reference for this value and remember it.
2277 if (Ty->isLabelTy())
2278 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2280 FwdVal = new Argument(Ty);
2282 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2286 /// SetInstName - After an instruction is parsed and inserted into its
2287 /// basic block, this installs its name.
2288 bool LLParser::PerFunctionState::SetInstName(int NameID,
2289 const std::string &NameStr,
2290 LocTy NameLoc, Instruction *Inst) {
2291 // If this instruction has void type, it cannot have a name or ID specified.
2292 if (Inst->getType()->isVoidTy()) {
2293 if (NameID != -1 || !NameStr.empty())
2294 return P.Error(NameLoc, "instructions returning void cannot have a name");
2298 // If this was a numbered instruction, verify that the instruction is the
2299 // expected value and resolve any forward references.
2300 if (NameStr.empty()) {
2301 // If neither a name nor an ID was specified, just use the next ID.
2303 NameID = NumberedVals.size();
2305 if (unsigned(NameID) != NumberedVals.size())
2306 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2307 Twine(NumberedVals.size()) + "'");
2309 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2310 ForwardRefValIDs.find(NameID);
2311 if (FI != ForwardRefValIDs.end()) {
2312 if (FI->second.first->getType() != Inst->getType())
2313 return P.Error(NameLoc, "instruction forward referenced with type '" +
2314 getTypeString(FI->second.first->getType()) + "'");
2315 FI->second.first->replaceAllUsesWith(Inst);
2316 delete FI->second.first;
2317 ForwardRefValIDs.erase(FI);
2320 NumberedVals.push_back(Inst);
2324 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2325 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2326 FI = ForwardRefVals.find(NameStr);
2327 if (FI != ForwardRefVals.end()) {
2328 if (FI->second.first->getType() != Inst->getType())
2329 return P.Error(NameLoc, "instruction forward referenced with type '" +
2330 getTypeString(FI->second.first->getType()) + "'");
2331 FI->second.first->replaceAllUsesWith(Inst);
2332 delete FI->second.first;
2333 ForwardRefVals.erase(FI);
2336 // Set the name on the instruction.
2337 Inst->setName(NameStr);
2339 if (Inst->getName() != NameStr)
2340 return P.Error(NameLoc, "multiple definition of local value named '" +
2345 /// GetBB - Get a basic block with the specified name or ID, creating a
2346 /// forward reference record if needed.
2347 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2349 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2350 Type::getLabelTy(F.getContext()), Loc));
2353 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2354 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2355 Type::getLabelTy(F.getContext()), Loc));
2358 /// DefineBB - Define the specified basic block, which is either named or
2359 /// unnamed. If there is an error, this returns null otherwise it returns
2360 /// the block being defined.
2361 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2365 BB = GetBB(NumberedVals.size(), Loc);
2367 BB = GetBB(Name, Loc);
2368 if (!BB) return nullptr; // Already diagnosed error.
2370 // Move the block to the end of the function. Forward ref'd blocks are
2371 // inserted wherever they happen to be referenced.
2372 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2374 // Remove the block from forward ref sets.
2376 ForwardRefValIDs.erase(NumberedVals.size());
2377 NumberedVals.push_back(BB);
2379 // BB forward references are already in the function symbol table.
2380 ForwardRefVals.erase(Name);
2386 //===----------------------------------------------------------------------===//
2388 //===----------------------------------------------------------------------===//
2390 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2391 /// type implied. For example, if we parse "4" we don't know what integer type
2392 /// it has. The value will later be combined with its type and checked for
2393 /// sanity. PFS is used to convert function-local operands of metadata (since
2394 /// metadata operands are not just parsed here but also converted to values).
2395 /// PFS can be null when we are not parsing metadata values inside a function.
2396 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2397 ID.Loc = Lex.getLoc();
2398 switch (Lex.getKind()) {
2399 default: return TokError("expected value token");
2400 case lltok::GlobalID: // @42
2401 ID.UIntVal = Lex.getUIntVal();
2402 ID.Kind = ValID::t_GlobalID;
2404 case lltok::GlobalVar: // @foo
2405 ID.StrVal = Lex.getStrVal();
2406 ID.Kind = ValID::t_GlobalName;
2408 case lltok::LocalVarID: // %42
2409 ID.UIntVal = Lex.getUIntVal();
2410 ID.Kind = ValID::t_LocalID;
2412 case lltok::LocalVar: // %foo
2413 ID.StrVal = Lex.getStrVal();
2414 ID.Kind = ValID::t_LocalName;
2417 ID.APSIntVal = Lex.getAPSIntVal();
2418 ID.Kind = ValID::t_APSInt;
2420 case lltok::APFloat:
2421 ID.APFloatVal = Lex.getAPFloatVal();
2422 ID.Kind = ValID::t_APFloat;
2424 case lltok::kw_true:
2425 ID.ConstantVal = ConstantInt::getTrue(Context);
2426 ID.Kind = ValID::t_Constant;
2428 case lltok::kw_false:
2429 ID.ConstantVal = ConstantInt::getFalse(Context);
2430 ID.Kind = ValID::t_Constant;
2432 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2433 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2434 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2436 case lltok::lbrace: {
2437 // ValID ::= '{' ConstVector '}'
2439 SmallVector<Constant*, 16> Elts;
2440 if (ParseGlobalValueVector(Elts) ||
2441 ParseToken(lltok::rbrace, "expected end of struct constant"))
2444 ID.ConstantStructElts = new Constant*[Elts.size()];
2445 ID.UIntVal = Elts.size();
2446 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2447 ID.Kind = ValID::t_ConstantStruct;
2451 // ValID ::= '<' ConstVector '>' --> Vector.
2452 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2454 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2456 SmallVector<Constant*, 16> Elts;
2457 LocTy FirstEltLoc = Lex.getLoc();
2458 if (ParseGlobalValueVector(Elts) ||
2460 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2461 ParseToken(lltok::greater, "expected end of constant"))
2464 if (isPackedStruct) {
2465 ID.ConstantStructElts = new Constant*[Elts.size()];
2466 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2467 ID.UIntVal = Elts.size();
2468 ID.Kind = ValID::t_PackedConstantStruct;
2473 return Error(ID.Loc, "constant vector must not be empty");
2475 if (!Elts[0]->getType()->isIntegerTy() &&
2476 !Elts[0]->getType()->isFloatingPointTy() &&
2477 !Elts[0]->getType()->isPointerTy())
2478 return Error(FirstEltLoc,
2479 "vector elements must have integer, pointer or floating point type");
2481 // Verify that all the vector elements have the same type.
2482 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2483 if (Elts[i]->getType() != Elts[0]->getType())
2484 return Error(FirstEltLoc,
2485 "vector element #" + Twine(i) +
2486 " is not of type '" + getTypeString(Elts[0]->getType()));
2488 ID.ConstantVal = ConstantVector::get(Elts);
2489 ID.Kind = ValID::t_Constant;
2492 case lltok::lsquare: { // Array Constant
2494 SmallVector<Constant*, 16> Elts;
2495 LocTy FirstEltLoc = Lex.getLoc();
2496 if (ParseGlobalValueVector(Elts) ||
2497 ParseToken(lltok::rsquare, "expected end of array constant"))
2500 // Handle empty element.
2502 // Use undef instead of an array because it's inconvenient to determine
2503 // the element type at this point, there being no elements to examine.
2504 ID.Kind = ValID::t_EmptyArray;
2508 if (!Elts[0]->getType()->isFirstClassType())
2509 return Error(FirstEltLoc, "invalid array element type: " +
2510 getTypeString(Elts[0]->getType()));
2512 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2514 // Verify all elements are correct type!
2515 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2516 if (Elts[i]->getType() != Elts[0]->getType())
2517 return Error(FirstEltLoc,
2518 "array element #" + Twine(i) +
2519 " is not of type '" + getTypeString(Elts[0]->getType()));
2522 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2523 ID.Kind = ValID::t_Constant;
2526 case lltok::kw_c: // c "foo"
2528 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2530 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2531 ID.Kind = ValID::t_Constant;
2534 case lltok::kw_asm: {
2535 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2537 bool HasSideEffect, AlignStack, AsmDialect;
2539 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2540 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2541 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2542 ParseStringConstant(ID.StrVal) ||
2543 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2544 ParseToken(lltok::StringConstant, "expected constraint string"))
2546 ID.StrVal2 = Lex.getStrVal();
2547 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2548 (unsigned(AsmDialect)<<2);
2549 ID.Kind = ValID::t_InlineAsm;
2553 case lltok::kw_blockaddress: {
2554 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2559 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2561 ParseToken(lltok::comma, "expected comma in block address expression")||
2562 ParseValID(Label) ||
2563 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2566 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2567 return Error(Fn.Loc, "expected function name in blockaddress");
2568 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2569 return Error(Label.Loc, "expected basic block name in blockaddress");
2571 // Try to find the function (but skip it if it's forward-referenced).
2572 GlobalValue *GV = nullptr;
2573 if (Fn.Kind == ValID::t_GlobalID) {
2574 if (Fn.UIntVal < NumberedVals.size())
2575 GV = NumberedVals[Fn.UIntVal];
2576 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2577 GV = M->getNamedValue(Fn.StrVal);
2579 Function *F = nullptr;
2581 // Confirm that it's actually a function with a definition.
2582 if (!isa<Function>(GV))
2583 return Error(Fn.Loc, "expected function name in blockaddress");
2584 F = cast<Function>(GV);
2585 if (F->isDeclaration())
2586 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2590 // Make a global variable as a placeholder for this reference.
2591 GlobalValue *&FwdRef =
2592 ForwardRefBlockAddresses.insert(std::make_pair(
2594 std::map<ValID, GlobalValue *>()))
2595 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2598 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2599 GlobalValue::InternalLinkage, nullptr, "");
2600 ID.ConstantVal = FwdRef;
2601 ID.Kind = ValID::t_Constant;
2605 // We found the function; now find the basic block. Don't use PFS, since we
2606 // might be inside a constant expression.
2608 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2609 if (Label.Kind == ValID::t_LocalID)
2610 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2612 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2614 return Error(Label.Loc, "referenced value is not a basic block");
2616 if (Label.Kind == ValID::t_LocalID)
2617 return Error(Label.Loc, "cannot take address of numeric label after "
2618 "the function is defined");
2619 BB = dyn_cast_or_null<BasicBlock>(
2620 F->getValueSymbolTable().lookup(Label.StrVal));
2622 return Error(Label.Loc, "referenced value is not a basic block");
2625 ID.ConstantVal = BlockAddress::get(F, BB);
2626 ID.Kind = ValID::t_Constant;
2630 case lltok::kw_trunc:
2631 case lltok::kw_zext:
2632 case lltok::kw_sext:
2633 case lltok::kw_fptrunc:
2634 case lltok::kw_fpext:
2635 case lltok::kw_bitcast:
2636 case lltok::kw_addrspacecast:
2637 case lltok::kw_uitofp:
2638 case lltok::kw_sitofp:
2639 case lltok::kw_fptoui:
2640 case lltok::kw_fptosi:
2641 case lltok::kw_inttoptr:
2642 case lltok::kw_ptrtoint: {
2643 unsigned Opc = Lex.getUIntVal();
2644 Type *DestTy = nullptr;
2647 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2648 ParseGlobalTypeAndValue(SrcVal) ||
2649 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2650 ParseType(DestTy) ||
2651 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2653 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2654 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2655 getTypeString(SrcVal->getType()) + "' to '" +
2656 getTypeString(DestTy) + "'");
2657 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2659 ID.Kind = ValID::t_Constant;
2662 case lltok::kw_extractvalue: {
2665 SmallVector<unsigned, 4> Indices;
2666 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2667 ParseGlobalTypeAndValue(Val) ||
2668 ParseIndexList(Indices) ||
2669 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2672 if (!Val->getType()->isAggregateType())
2673 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2674 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2675 return Error(ID.Loc, "invalid indices for extractvalue");
2676 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2677 ID.Kind = ValID::t_Constant;
2680 case lltok::kw_insertvalue: {
2682 Constant *Val0, *Val1;
2683 SmallVector<unsigned, 4> Indices;
2684 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2685 ParseGlobalTypeAndValue(Val0) ||
2686 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2687 ParseGlobalTypeAndValue(Val1) ||
2688 ParseIndexList(Indices) ||
2689 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2691 if (!Val0->getType()->isAggregateType())
2692 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2694 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2696 return Error(ID.Loc, "invalid indices for insertvalue");
2697 if (IndexedType != Val1->getType())
2698 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2699 getTypeString(Val1->getType()) +
2700 "' instead of '" + getTypeString(IndexedType) +
2702 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2703 ID.Kind = ValID::t_Constant;
2706 case lltok::kw_icmp:
2707 case lltok::kw_fcmp: {
2708 unsigned PredVal, Opc = Lex.getUIntVal();
2709 Constant *Val0, *Val1;
2711 if (ParseCmpPredicate(PredVal, Opc) ||
2712 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2713 ParseGlobalTypeAndValue(Val0) ||
2714 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2715 ParseGlobalTypeAndValue(Val1) ||
2716 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2719 if (Val0->getType() != Val1->getType())
2720 return Error(ID.Loc, "compare operands must have the same type");
2722 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2724 if (Opc == Instruction::FCmp) {
2725 if (!Val0->getType()->isFPOrFPVectorTy())
2726 return Error(ID.Loc, "fcmp requires floating point operands");
2727 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2729 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2730 if (!Val0->getType()->isIntOrIntVectorTy() &&
2731 !Val0->getType()->getScalarType()->isPointerTy())
2732 return Error(ID.Loc, "icmp requires pointer or integer operands");
2733 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2735 ID.Kind = ValID::t_Constant;
2739 // Binary Operators.
2741 case lltok::kw_fadd:
2743 case lltok::kw_fsub:
2745 case lltok::kw_fmul:
2746 case lltok::kw_udiv:
2747 case lltok::kw_sdiv:
2748 case lltok::kw_fdiv:
2749 case lltok::kw_urem:
2750 case lltok::kw_srem:
2751 case lltok::kw_frem:
2753 case lltok::kw_lshr:
2754 case lltok::kw_ashr: {
2758 unsigned Opc = Lex.getUIntVal();
2759 Constant *Val0, *Val1;
2761 LocTy ModifierLoc = Lex.getLoc();
2762 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2763 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2764 if (EatIfPresent(lltok::kw_nuw))
2766 if (EatIfPresent(lltok::kw_nsw)) {
2768 if (EatIfPresent(lltok::kw_nuw))
2771 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2772 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2773 if (EatIfPresent(lltok::kw_exact))
2776 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2777 ParseGlobalTypeAndValue(Val0) ||
2778 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2779 ParseGlobalTypeAndValue(Val1) ||
2780 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2782 if (Val0->getType() != Val1->getType())
2783 return Error(ID.Loc, "operands of constexpr must have same type");
2784 if (!Val0->getType()->isIntOrIntVectorTy()) {
2786 return Error(ModifierLoc, "nuw only applies to integer operations");
2788 return Error(ModifierLoc, "nsw only applies to integer operations");
2790 // Check that the type is valid for the operator.
2792 case Instruction::Add:
2793 case Instruction::Sub:
2794 case Instruction::Mul:
2795 case Instruction::UDiv:
2796 case Instruction::SDiv:
2797 case Instruction::URem:
2798 case Instruction::SRem:
2799 case Instruction::Shl:
2800 case Instruction::AShr:
2801 case Instruction::LShr:
2802 if (!Val0->getType()->isIntOrIntVectorTy())
2803 return Error(ID.Loc, "constexpr requires integer operands");
2805 case Instruction::FAdd:
2806 case Instruction::FSub:
2807 case Instruction::FMul:
2808 case Instruction::FDiv:
2809 case Instruction::FRem:
2810 if (!Val0->getType()->isFPOrFPVectorTy())
2811 return Error(ID.Loc, "constexpr requires fp operands");
2813 default: llvm_unreachable("Unknown binary operator!");
2816 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2817 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2818 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2819 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2821 ID.Kind = ValID::t_Constant;
2825 // Logical Operations
2828 case lltok::kw_xor: {
2829 unsigned Opc = Lex.getUIntVal();
2830 Constant *Val0, *Val1;
2832 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2833 ParseGlobalTypeAndValue(Val0) ||
2834 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2835 ParseGlobalTypeAndValue(Val1) ||
2836 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2838 if (Val0->getType() != Val1->getType())
2839 return Error(ID.Loc, "operands of constexpr must have same type");
2840 if (!Val0->getType()->isIntOrIntVectorTy())
2841 return Error(ID.Loc,
2842 "constexpr requires integer or integer vector operands");
2843 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2844 ID.Kind = ValID::t_Constant;
2848 case lltok::kw_getelementptr:
2849 case lltok::kw_shufflevector:
2850 case lltok::kw_insertelement:
2851 case lltok::kw_extractelement:
2852 case lltok::kw_select: {
2853 unsigned Opc = Lex.getUIntVal();
2854 SmallVector<Constant*, 16> Elts;
2855 bool InBounds = false;
2859 if (Opc == Instruction::GetElementPtr)
2860 InBounds = EatIfPresent(lltok::kw_inbounds);
2862 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2865 LocTy ExplicitTypeLoc = Lex.getLoc();
2866 if (Opc == Instruction::GetElementPtr) {
2867 if (ParseType(Ty) ||
2868 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2872 if (ParseGlobalValueVector(Elts) ||
2873 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2876 if (Opc == Instruction::GetElementPtr) {
2877 if (Elts.size() == 0 ||
2878 !Elts[0]->getType()->getScalarType()->isPointerTy())
2879 return Error(ID.Loc, "base of getelementptr must be a pointer");
2881 Type *BaseType = Elts[0]->getType();
2882 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2883 if (Ty != BasePointerType->getElementType())
2886 "explicit pointee type doesn't match operand's pointee type");
2888 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2889 for (Constant *Val : Indices) {
2890 Type *ValTy = Val->getType();
2891 if (!ValTy->getScalarType()->isIntegerTy())
2892 return Error(ID.Loc, "getelementptr index must be an integer");
2893 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2894 return Error(ID.Loc, "getelementptr index type missmatch");
2895 if (ValTy->isVectorTy()) {
2896 unsigned ValNumEl = ValTy->getVectorNumElements();
2897 unsigned PtrNumEl = BaseType->getVectorNumElements();
2898 if (ValNumEl != PtrNumEl)
2901 "getelementptr vector index has a wrong number of elements");
2905 SmallPtrSet<const Type*, 4> Visited;
2906 if (!Indices.empty() && !Ty->isSized(&Visited))
2907 return Error(ID.Loc, "base element of getelementptr must be sized");
2909 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2910 return Error(ID.Loc, "invalid getelementptr indices");
2912 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2913 } else if (Opc == Instruction::Select) {
2914 if (Elts.size() != 3)
2915 return Error(ID.Loc, "expected three operands to select");
2916 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2918 return Error(ID.Loc, Reason);
2919 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2920 } else if (Opc == Instruction::ShuffleVector) {
2921 if (Elts.size() != 3)
2922 return Error(ID.Loc, "expected three operands to shufflevector");
2923 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2924 return Error(ID.Loc, "invalid operands to shufflevector");
2926 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2927 } else if (Opc == Instruction::ExtractElement) {
2928 if (Elts.size() != 2)
2929 return Error(ID.Loc, "expected two operands to extractelement");
2930 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2931 return Error(ID.Loc, "invalid extractelement operands");
2932 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2934 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2935 if (Elts.size() != 3)
2936 return Error(ID.Loc, "expected three operands to insertelement");
2937 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2938 return Error(ID.Loc, "invalid insertelement operands");
2940 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2943 ID.Kind = ValID::t_Constant;
2952 /// ParseGlobalValue - Parse a global value with the specified type.
2953 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2957 bool Parsed = ParseValID(ID) ||
2958 ConvertValIDToValue(Ty, ID, V, nullptr);
2959 if (V && !(C = dyn_cast<Constant>(V)))
2960 return Error(ID.Loc, "global values must be constants");
2964 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2966 return ParseType(Ty) ||
2967 ParseGlobalValue(Ty, V);
2970 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2973 LocTy KwLoc = Lex.getLoc();
2974 if (!EatIfPresent(lltok::kw_comdat))
2977 if (EatIfPresent(lltok::lparen)) {
2978 if (Lex.getKind() != lltok::ComdatVar)
2979 return TokError("expected comdat variable");
2980 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2982 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2985 if (GlobalName.empty())
2986 return TokError("comdat cannot be unnamed");
2987 C = getComdat(GlobalName, KwLoc);
2993 /// ParseGlobalValueVector
2995 /// ::= TypeAndValue (',' TypeAndValue)*
2996 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2998 if (Lex.getKind() == lltok::rbrace ||
2999 Lex.getKind() == lltok::rsquare ||
3000 Lex.getKind() == lltok::greater ||
3001 Lex.getKind() == lltok::rparen)
3005 if (ParseGlobalTypeAndValue(C)) return true;
3008 while (EatIfPresent(lltok::comma)) {
3009 if (ParseGlobalTypeAndValue(C)) return true;
3016 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3017 SmallVector<Metadata *, 16> Elts;
3018 if (ParseMDNodeVector(Elts))
3021 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3028 /// ::= !DILocation(...)
3029 bool LLParser::ParseMDNode(MDNode *&N) {
3030 if (Lex.getKind() == lltok::MetadataVar)
3031 return ParseSpecializedMDNode(N);
3033 return ParseToken(lltok::exclaim, "expected '!' here") ||
3037 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3039 if (Lex.getKind() == lltok::lbrace)
3040 return ParseMDTuple(N);
3043 return ParseMDNodeID(N);
3048 /// Structure to represent an optional metadata field.
3049 template <class FieldTy> struct MDFieldImpl {
3050 typedef MDFieldImpl ImplTy;
3054 void assign(FieldTy Val) {
3056 this->Val = std::move(Val);
3059 explicit MDFieldImpl(FieldTy Default)
3060 : Val(std::move(Default)), Seen(false) {}
3063 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3066 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3067 : ImplTy(Default), Max(Max) {}
3069 struct LineField : public MDUnsignedField {
3070 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3072 struct ColumnField : public MDUnsignedField {
3073 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3075 struct DwarfTagField : public MDUnsignedField {
3076 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3077 DwarfTagField(dwarf::Tag DefaultTag)
3078 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3080 struct DwarfAttEncodingField : public MDUnsignedField {
3081 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3083 struct DwarfVirtualityField : public MDUnsignedField {
3084 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3086 struct DwarfLangField : public MDUnsignedField {
3087 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3090 struct DIFlagField : public MDUnsignedField {
3091 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3094 struct MDSignedField : public MDFieldImpl<int64_t> {
3098 MDSignedField(int64_t Default = 0)
3099 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3100 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3101 : ImplTy(Default), Min(Min), Max(Max) {}
3104 struct MDBoolField : public MDFieldImpl<bool> {
3105 MDBoolField(bool Default = false) : ImplTy(Default) {}
3107 struct MDField : public MDFieldImpl<Metadata *> {
3110 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3112 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3113 MDConstant() : ImplTy(nullptr) {}
3115 struct MDStringField : public MDFieldImpl<MDString *> {
3117 MDStringField(bool AllowEmpty = true)
3118 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3120 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3121 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3129 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3130 MDUnsignedField &Result) {
3131 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3132 return TokError("expected unsigned integer");
3134 auto &U = Lex.getAPSIntVal();
3135 if (U.ugt(Result.Max))
3136 return TokError("value for '" + Name + "' too large, limit is " +
3138 Result.assign(U.getZExtValue());
3139 assert(Result.Val <= Result.Max && "Expected value in range");
3145 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3146 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3149 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3150 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3154 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3155 if (Lex.getKind() == lltok::APSInt)
3156 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3158 if (Lex.getKind() != lltok::DwarfTag)
3159 return TokError("expected DWARF tag");
3161 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3162 if (Tag == dwarf::DW_TAG_invalid)
3163 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3164 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3172 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3173 DwarfVirtualityField &Result) {
3174 if (Lex.getKind() == lltok::APSInt)
3175 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3177 if (Lex.getKind() != lltok::DwarfVirtuality)
3178 return TokError("expected DWARF virtuality code");
3180 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3182 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3183 Lex.getStrVal() + "'");
3184 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3185 Result.assign(Virtuality);
3191 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3192 if (Lex.getKind() == lltok::APSInt)
3193 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3195 if (Lex.getKind() != lltok::DwarfLang)
3196 return TokError("expected DWARF language");
3198 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3200 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3202 assert(Lang <= Result.Max && "Expected valid DWARF language");
3203 Result.assign(Lang);
3209 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3210 DwarfAttEncodingField &Result) {
3211 if (Lex.getKind() == lltok::APSInt)
3212 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3214 if (Lex.getKind() != lltok::DwarfAttEncoding)
3215 return TokError("expected DWARF type attribute encoding");
3217 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3219 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3220 Lex.getStrVal() + "'");
3221 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3222 Result.assign(Encoding);
3229 /// ::= DIFlagVector
3230 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3232 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3233 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3235 // Parser for a single flag.
3236 auto parseFlag = [&](unsigned &Val) {
3237 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3238 return ParseUInt32(Val);
3240 if (Lex.getKind() != lltok::DIFlag)
3241 return TokError("expected debug info flag");
3243 Val = DINode::getFlag(Lex.getStrVal());
3245 return TokError(Twine("invalid debug info flag flag '") +
3246 Lex.getStrVal() + "'");
3251 // Parse the flags and combine them together.
3252 unsigned Combined = 0;
3258 } while (EatIfPresent(lltok::bar));
3260 Result.assign(Combined);
3265 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3266 MDSignedField &Result) {
3267 if (Lex.getKind() != lltok::APSInt)
3268 return TokError("expected signed integer");
3270 auto &S = Lex.getAPSIntVal();
3272 return TokError("value for '" + Name + "' too small, limit is " +
3275 return TokError("value for '" + Name + "' too large, limit is " +
3277 Result.assign(S.getExtValue());
3278 assert(Result.Val >= Result.Min && "Expected value in range");
3279 assert(Result.Val <= Result.Max && "Expected value in range");
3285 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3286 switch (Lex.getKind()) {
3288 return TokError("expected 'true' or 'false'");
3289 case lltok::kw_true:
3290 Result.assign(true);
3292 case lltok::kw_false:
3293 Result.assign(false);
3301 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3302 if (Lex.getKind() == lltok::kw_null) {
3303 if (!Result.AllowNull)
3304 return TokError("'" + Name + "' cannot be null");
3306 Result.assign(nullptr);
3311 if (ParseMetadata(MD, nullptr))
3319 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3321 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3324 Result.assign(cast<ConstantAsMetadata>(MD));
3329 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3330 LocTy ValueLoc = Lex.getLoc();
3332 if (ParseStringConstant(S))
3335 if (!Result.AllowEmpty && S.empty())
3336 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3338 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3343 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3344 SmallVector<Metadata *, 4> MDs;
3345 if (ParseMDNodeVector(MDs))
3348 Result.assign(std::move(MDs));
3352 } // end namespace llvm
3354 template <class ParserTy>
3355 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3357 if (Lex.getKind() != lltok::LabelStr)
3358 return TokError("expected field label here");
3362 } while (EatIfPresent(lltok::comma));
3367 template <class ParserTy>
3368 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3369 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3372 if (ParseToken(lltok::lparen, "expected '(' here"))
3374 if (Lex.getKind() != lltok::rparen)
3375 if (ParseMDFieldsImplBody(parseField))
3378 ClosingLoc = Lex.getLoc();
3379 return ParseToken(lltok::rparen, "expected ')' here");
3382 template <class FieldTy>
3383 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3385 return TokError("field '" + Name + "' cannot be specified more than once");
3387 LocTy Loc = Lex.getLoc();
3389 return ParseMDField(Loc, Name, Result);
3392 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3393 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3395 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3396 if (Lex.getStrVal() == #CLASS) \
3397 return Parse##CLASS(N, IsDistinct);
3398 #include "llvm/IR/Metadata.def"
3400 return TokError("expected metadata type");
3403 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3404 #define NOP_FIELD(NAME, TYPE, INIT)
3405 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3407 return Error(ClosingLoc, "missing required field '" #NAME "'");
3408 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3409 if (Lex.getStrVal() == #NAME) \
3410 return ParseMDField(#NAME, NAME);
3411 #define PARSE_MD_FIELDS() \
3412 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3415 if (ParseMDFieldsImpl([&]() -> bool { \
3416 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3417 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3420 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3422 #define GET_OR_DISTINCT(CLASS, ARGS) \
3423 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3425 /// ParseDILocationFields:
3426 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3427 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3428 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3429 OPTIONAL(line, LineField, ); \
3430 OPTIONAL(column, ColumnField, ); \
3431 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3432 OPTIONAL(inlinedAt, MDField, );
3434 #undef VISIT_MD_FIELDS
3436 Result = GET_OR_DISTINCT(
3437 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3441 /// ParseGenericDINode:
3442 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3443 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3444 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3445 REQUIRED(tag, DwarfTagField, ); \
3446 OPTIONAL(header, MDStringField, ); \
3447 OPTIONAL(operands, MDFieldList, );
3449 #undef VISIT_MD_FIELDS
3451 Result = GET_OR_DISTINCT(GenericDINode,
3452 (Context, tag.Val, header.Val, operands.Val));
3456 /// ParseDISubrange:
3457 /// ::= !DISubrange(count: 30, lowerBound: 2)
3458 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3459 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3460 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3461 OPTIONAL(lowerBound, MDSignedField, );
3463 #undef VISIT_MD_FIELDS
3465 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3469 /// ParseDIEnumerator:
3470 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3471 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3472 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3473 REQUIRED(name, MDStringField, ); \
3474 REQUIRED(value, MDSignedField, );
3476 #undef VISIT_MD_FIELDS
3478 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3482 /// ParseDIBasicType:
3483 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3484 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3485 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3486 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3487 OPTIONAL(name, MDStringField, ); \
3488 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3489 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3490 OPTIONAL(encoding, DwarfAttEncodingField, );
3492 #undef VISIT_MD_FIELDS
3494 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3495 align.Val, encoding.Val));
3499 /// ParseDIDerivedType:
3500 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3501 /// line: 7, scope: !1, baseType: !2, size: 32,
3502 /// align: 32, offset: 0, flags: 0, extraData: !3)
3503 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3504 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3505 REQUIRED(tag, DwarfTagField, ); \
3506 OPTIONAL(name, MDStringField, ); \
3507 OPTIONAL(file, MDField, ); \
3508 OPTIONAL(line, LineField, ); \
3509 OPTIONAL(scope, MDField, ); \
3510 REQUIRED(baseType, MDField, ); \
3511 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3512 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3513 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3514 OPTIONAL(flags, DIFlagField, ); \
3515 OPTIONAL(extraData, MDField, );
3517 #undef VISIT_MD_FIELDS
3519 Result = GET_OR_DISTINCT(DIDerivedType,
3520 (Context, tag.Val, name.Val, file.Val, line.Val,
3521 scope.Val, baseType.Val, size.Val, align.Val,
3522 offset.Val, flags.Val, extraData.Val));
3526 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3527 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3528 REQUIRED(tag, DwarfTagField, ); \
3529 OPTIONAL(name, MDStringField, ); \
3530 OPTIONAL(file, MDField, ); \
3531 OPTIONAL(line, LineField, ); \
3532 OPTIONAL(scope, MDField, ); \
3533 OPTIONAL(baseType, MDField, ); \
3534 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3535 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3536 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3537 OPTIONAL(flags, DIFlagField, ); \
3538 OPTIONAL(elements, MDField, ); \
3539 OPTIONAL(runtimeLang, DwarfLangField, ); \
3540 OPTIONAL(vtableHolder, MDField, ); \
3541 OPTIONAL(templateParams, MDField, ); \
3542 OPTIONAL(identifier, MDStringField, );
3544 #undef VISIT_MD_FIELDS
3546 Result = GET_OR_DISTINCT(
3548 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3549 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3550 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3554 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3555 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3556 OPTIONAL(flags, DIFlagField, ); \
3557 REQUIRED(types, MDField, );
3559 #undef VISIT_MD_FIELDS
3561 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3565 /// ParseDIFileType:
3566 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3567 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3568 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3569 REQUIRED(filename, MDStringField, ); \
3570 REQUIRED(directory, MDStringField, );
3572 #undef VISIT_MD_FIELDS
3574 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3578 /// ParseDICompileUnit:
3579 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3580 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3581 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3582 /// enums: !1, retainedTypes: !2, subprograms: !3,
3583 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3584 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3585 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3586 REQUIRED(language, DwarfLangField, ); \
3587 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3588 OPTIONAL(producer, MDStringField, );