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/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/SaveAndRestore.h"
31 #include "llvm/Support/raw_ostream.h"
34 static std::string getTypeString(Type *T) {
36 raw_string_ostream Tmp(Result);
41 /// Run: module ::= toplevelentity*
42 bool LLParser::Run() {
46 return ParseTopLevelEntities() ||
47 ValidateEndOfModule();
50 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
52 bool LLParser::ValidateEndOfModule() {
53 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
56 // Handle any function attribute group forward references.
57 for (std::map<Value*, std::vector<unsigned> >::iterator
58 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
61 std::vector<unsigned> &Vec = I->second;
64 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
66 B.merge(NumberedAttrBuilders[*VI]);
68 if (Function *Fn = dyn_cast<Function>(V)) {
69 AttributeSet AS = Fn->getAttributes();
70 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72 AS.getFnAttributes());
76 // If the alignment was parsed as an attribute, move to the alignment
78 if (FnAttrs.hasAlignmentAttr()) {
79 Fn->setAlignment(FnAttrs.getAlignment());
80 FnAttrs.removeAttribute(Attribute::Alignment);
83 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84 AttributeSet::get(Context,
85 AttributeSet::FunctionIndex,
87 Fn->setAttributes(AS);
88 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89 AttributeSet AS = CI->getAttributes();
90 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92 AS.getFnAttributes());
94 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95 AttributeSet::get(Context,
96 AttributeSet::FunctionIndex,
98 CI->setAttributes(AS);
99 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100 AttributeSet AS = II->getAttributes();
101 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103 AS.getFnAttributes());
105 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106 AttributeSet::get(Context,
107 AttributeSet::FunctionIndex,
109 II->setAttributes(AS);
111 llvm_unreachable("invalid object with forward attribute group reference");
115 // If there are entries in ForwardRefBlockAddresses at this point, the
116 // function was never defined.
117 if (!ForwardRefBlockAddresses.empty())
118 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119 "expected function name in blockaddress");
121 for (const auto &NT : NumberedTypes)
122 if (NT.second.second.isValid())
123 return Error(NT.second.second,
124 "use of undefined type '%" + Twine(NT.first) + "'");
126 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128 if (I->second.second.isValid())
129 return Error(I->second.second,
130 "use of undefined type named '" + I->getKey() + "'");
132 if (!ForwardRefComdats.empty())
133 return Error(ForwardRefComdats.begin()->second,
134 "use of undefined comdat '$" +
135 ForwardRefComdats.begin()->first + "'");
137 if (!ForwardRefVals.empty())
138 return Error(ForwardRefVals.begin()->second.second,
139 "use of undefined value '@" + ForwardRefVals.begin()->first +
142 if (!ForwardRefValIDs.empty())
143 return Error(ForwardRefValIDs.begin()->second.second,
144 "use of undefined value '@" +
145 Twine(ForwardRefValIDs.begin()->first) + "'");
147 if (!ForwardRefMDNodes.empty())
148 return Error(ForwardRefMDNodes.begin()->second.second,
149 "use of undefined metadata '!" +
150 Twine(ForwardRefMDNodes.begin()->first) + "'");
152 // Resolve metadata cycles.
153 for (auto &N : NumberedMetadata) {
154 if (N.second && !N.second->isResolved())
155 N.second->resolveCycles();
158 // Look for intrinsic functions and CallInst that need to be upgraded
159 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
162 UpgradeDebugInfo(*M);
167 //===----------------------------------------------------------------------===//
168 // Top-Level Entities
169 //===----------------------------------------------------------------------===//
171 bool LLParser::ParseTopLevelEntities() {
173 switch (Lex.getKind()) {
174 default: return TokError("expected top-level entity");
175 case lltok::Eof: return false;
176 case lltok::kw_declare: if (ParseDeclare()) return true; break;
177 case lltok::kw_define: if (ParseDefine()) return true; break;
178 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
179 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
180 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
181 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
182 case lltok::LocalVar: if (ParseNamedType()) return true; break;
183 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
184 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
185 case lltok::ComdatVar: if (parseComdat()) return true; break;
186 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
187 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
189 // The Global variable production with no name can have many different
190 // optional leading prefixes, the production is:
191 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
193 // ('constant'|'global') ...
194 case lltok::kw_private: // OptionalLinkage
195 case lltok::kw_internal: // OptionalLinkage
196 case lltok::kw_weak: // OptionalLinkage
197 case lltok::kw_weak_odr: // OptionalLinkage
198 case lltok::kw_linkonce: // OptionalLinkage
199 case lltok::kw_linkonce_odr: // OptionalLinkage
200 case lltok::kw_appending: // OptionalLinkage
201 case lltok::kw_common: // OptionalLinkage
202 case lltok::kw_extern_weak: // OptionalLinkage
203 case lltok::kw_external: // OptionalLinkage
204 case lltok::kw_default: // OptionalVisibility
205 case lltok::kw_hidden: // OptionalVisibility
206 case lltok::kw_protected: // OptionalVisibility
207 case lltok::kw_dllimport: // OptionalDLLStorageClass
208 case lltok::kw_dllexport: // OptionalDLLStorageClass
209 case lltok::kw_thread_local: // OptionalThreadLocal
210 case lltok::kw_addrspace: // OptionalAddrSpace
211 case lltok::kw_constant: // GlobalType
212 case lltok::kw_global: { // GlobalType
213 unsigned Linkage, Visibility, DLLStorageClass;
215 GlobalVariable::ThreadLocalMode TLM;
217 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
218 ParseOptionalVisibility(Visibility) ||
219 ParseOptionalDLLStorageClass(DLLStorageClass) ||
220 ParseOptionalThreadLocal(TLM) ||
221 parseOptionalUnnamedAddr(UnnamedAddr) ||
222 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
223 DLLStorageClass, TLM, UnnamedAddr))
228 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
229 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230 case lltok::kw_uselistorder_bb:
231 if (ParseUseListOrderBB()) return true; break;
238 /// ::= 'module' 'asm' STRINGCONSTANT
239 bool LLParser::ParseModuleAsm() {
240 assert(Lex.getKind() == lltok::kw_module);
244 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245 ParseStringConstant(AsmStr)) return true;
247 M->appendModuleInlineAsm(AsmStr);
252 /// ::= 'target' 'triple' '=' STRINGCONSTANT
253 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
254 bool LLParser::ParseTargetDefinition() {
255 assert(Lex.getKind() == lltok::kw_target);
258 default: return TokError("unknown target property");
259 case lltok::kw_triple:
261 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262 ParseStringConstant(Str))
264 M->setTargetTriple(Str);
266 case lltok::kw_datalayout:
268 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269 ParseStringConstant(Str))
271 M->setDataLayout(Str);
277 /// ::= 'deplibs' '=' '[' ']'
278 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279 /// FIXME: Remove in 4.0. Currently parse, but ignore.
280 bool LLParser::ParseDepLibs() {
281 assert(Lex.getKind() == lltok::kw_deplibs);
283 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
287 if (EatIfPresent(lltok::rsquare))
292 if (ParseStringConstant(Str)) return true;
293 } while (EatIfPresent(lltok::comma));
295 return ParseToken(lltok::rsquare, "expected ']' at end of list");
298 /// ParseUnnamedType:
299 /// ::= LocalVarID '=' 'type' type
300 bool LLParser::ParseUnnamedType() {
301 LocTy TypeLoc = Lex.getLoc();
302 unsigned TypeID = Lex.getUIntVal();
303 Lex.Lex(); // eat LocalVarID;
305 if (ParseToken(lltok::equal, "expected '=' after name") ||
306 ParseToken(lltok::kw_type, "expected 'type' after '='"))
309 Type *Result = nullptr;
310 if (ParseStructDefinition(TypeLoc, "",
311 NumberedTypes[TypeID], Result)) return true;
313 if (!isa<StructType>(Result)) {
314 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
316 return Error(TypeLoc, "non-struct types may not be recursive");
317 Entry.first = Result;
318 Entry.second = SMLoc();
326 /// ::= LocalVar '=' 'type' type
327 bool LLParser::ParseNamedType() {
328 std::string Name = Lex.getStrVal();
329 LocTy NameLoc = Lex.getLoc();
330 Lex.Lex(); // eat LocalVar.
332 if (ParseToken(lltok::equal, "expected '=' after name") ||
333 ParseToken(lltok::kw_type, "expected 'type' after name"))
336 Type *Result = nullptr;
337 if (ParseStructDefinition(NameLoc, Name,
338 NamedTypes[Name], Result)) return true;
340 if (!isa<StructType>(Result)) {
341 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
343 return Error(NameLoc, "non-struct types may not be recursive");
344 Entry.first = Result;
345 Entry.second = SMLoc();
353 /// ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
359 return ParseFunctionHeader(F, false);
363 /// ::= 'define' FunctionHeader '{' ...
364 bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
376 bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
379 else if (Lex.getKind() == lltok::kw_global)
383 return TokError("expected 'global' or 'constant'");
389 /// ParseUnnamedGlobal:
390 /// OptionalVisibility ALIAS ...
391 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392 /// ... -> global variable
393 /// GlobalID '=' OptionalVisibility ALIAS ...
394 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395 /// ... -> global variable
396 bool LLParser::ParseUnnamedGlobal() {
397 unsigned VarID = NumberedVals.size();
399 LocTy NameLoc = Lex.getLoc();
401 // Handle the GlobalID form.
402 if (Lex.getKind() == lltok::GlobalID) {
403 if (Lex.getUIntVal() != VarID)
404 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
406 Lex.Lex(); // eat GlobalID;
408 if (ParseToken(lltok::equal, "expected '=' after name"))
413 unsigned Linkage, Visibility, DLLStorageClass;
414 GlobalVariable::ThreadLocalMode TLM;
416 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
417 ParseOptionalVisibility(Visibility) ||
418 ParseOptionalDLLStorageClass(DLLStorageClass) ||
419 ParseOptionalThreadLocal(TLM) ||
420 parseOptionalUnnamedAddr(UnnamedAddr))
423 if (Lex.getKind() != lltok::kw_alias)
424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
425 DLLStorageClass, TLM, UnnamedAddr);
426 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
430 /// ParseNamedGlobal:
431 /// GlobalVar '=' OptionalVisibility ALIAS ...
432 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433 /// ... -> global variable
434 bool LLParser::ParseNamedGlobal() {
435 assert(Lex.getKind() == lltok::GlobalVar);
436 LocTy NameLoc = Lex.getLoc();
437 std::string Name = Lex.getStrVal();
441 unsigned Linkage, Visibility, DLLStorageClass;
442 GlobalVariable::ThreadLocalMode TLM;
444 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445 ParseOptionalLinkage(Linkage, HasLinkage) ||
446 ParseOptionalVisibility(Visibility) ||
447 ParseOptionalDLLStorageClass(DLLStorageClass) ||
448 ParseOptionalThreadLocal(TLM) ||
449 parseOptionalUnnamedAddr(UnnamedAddr))
452 if (Lex.getKind() != lltok::kw_alias)
453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
454 DLLStorageClass, TLM, UnnamedAddr);
456 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
460 bool LLParser::parseComdat() {
461 assert(Lex.getKind() == lltok::ComdatVar);
462 std::string Name = Lex.getStrVal();
463 LocTy NameLoc = Lex.getLoc();
466 if (ParseToken(lltok::equal, "expected '=' here"))
469 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470 return TokError("expected comdat type");
472 Comdat::SelectionKind SK;
473 switch (Lex.getKind()) {
475 return TokError("unknown selection kind");
479 case lltok::kw_exactmatch:
480 SK = Comdat::ExactMatch;
482 case lltok::kw_largest:
483 SK = Comdat::Largest;
485 case lltok::kw_noduplicates:
486 SK = Comdat::NoDuplicates;
488 case lltok::kw_samesize:
489 SK = Comdat::SameSize;
494 // See if the comdat was forward referenced, if so, use the comdat.
495 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
501 if (I != ComdatSymTab.end())
504 C = M->getOrInsertComdat(Name);
505 C->setSelectionKind(SK);
511 // ::= '!' STRINGCONSTANT
512 bool LLParser::ParseMDString(MDString *&Result) {
514 if (ParseStringConstant(Str)) return true;
515 llvm::UpgradeMDStringConstant(Str);
516 Result = MDString::get(Context, Str);
521 // ::= '!' MDNodeNumber
522 bool LLParser::ParseMDNodeID(MDNode *&Result) {
523 // !{ ..., !42, ... }
525 if (ParseUInt32(MID))
528 // If not a forward reference, just return it now.
529 if (NumberedMetadata.count(MID)) {
530 Result = NumberedMetadata[MID];
534 // Otherwise, create MDNode forward reference.
535 auto &FwdRef = ForwardRefMDNodes[MID];
536 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
538 Result = FwdRef.first.get();
539 NumberedMetadata[MID].reset(Result);
543 /// ParseNamedMetadata:
544 /// !foo = !{ !1, !2 }
545 bool LLParser::ParseNamedMetadata() {
546 assert(Lex.getKind() == lltok::MetadataVar);
547 std::string Name = Lex.getStrVal();
550 if (ParseToken(lltok::equal, "expected '=' here") ||
551 ParseToken(lltok::exclaim, "Expected '!' here") ||
552 ParseToken(lltok::lbrace, "Expected '{' here"))
555 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
556 if (Lex.getKind() != lltok::rbrace)
558 if (ParseToken(lltok::exclaim, "Expected '!' here"))
562 if (ParseMDNodeID(N)) return true;
564 } while (EatIfPresent(lltok::comma));
566 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
572 /// ParseStandaloneMetadata:
574 bool LLParser::ParseStandaloneMetadata() {
575 assert(Lex.getKind() == lltok::exclaim);
577 unsigned MetadataID = 0;
580 if (ParseUInt32(MetadataID) ||
581 ParseToken(lltok::equal, "expected '=' here"))
584 // Detect common error, from old metadata syntax.
585 if (Lex.getKind() == lltok::Type)
586 return TokError("unexpected type in metadata definition");
588 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
589 if (Lex.getKind() == lltok::MetadataVar) {
590 if (ParseSpecializedMDNode(Init, IsDistinct))
592 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
593 ParseMDTuple(Init, IsDistinct))
596 // See if this was forward referenced, if so, handle it.
597 auto FI = ForwardRefMDNodes.find(MetadataID);
598 if (FI != ForwardRefMDNodes.end()) {
599 FI->second.first->replaceAllUsesWith(Init);
600 ForwardRefMDNodes.erase(FI);
602 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
604 if (NumberedMetadata.count(MetadataID))
605 return TokError("Metadata id is already used");
606 NumberedMetadata[MetadataID].reset(Init);
612 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
613 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
614 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
618 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
619 /// OptionalDLLStorageClass OptionalThreadLocal
620 /// OptionalUnNammedAddr 'alias' Aliasee
625 /// Everything through OptionalUnNammedAddr has already been parsed.
627 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
628 unsigned Visibility, unsigned DLLStorageClass,
629 GlobalVariable::ThreadLocalMode TLM,
631 assert(Lex.getKind() == lltok::kw_alias);
634 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
636 if(!GlobalAlias::isValidLinkage(Linkage))
637 return Error(NameLoc, "invalid linkage type for alias");
639 if (!isValidVisibilityForLinkage(Visibility, L))
640 return Error(NameLoc,
641 "symbol with local linkage must have default visibility");
644 LocTy AliaseeLoc = Lex.getLoc();
645 if (Lex.getKind() != lltok::kw_bitcast &&
646 Lex.getKind() != lltok::kw_getelementptr &&
647 Lex.getKind() != lltok::kw_addrspacecast &&
648 Lex.getKind() != lltok::kw_inttoptr) {
649 if (ParseGlobalTypeAndValue(Aliasee))
652 // The bitcast dest type is not present, it is implied by the dest type.
656 if (ID.Kind != ValID::t_Constant)
657 return Error(AliaseeLoc, "invalid aliasee");
658 Aliasee = ID.ConstantVal;
661 Type *AliaseeType = Aliasee->getType();
662 auto *PTy = dyn_cast<PointerType>(AliaseeType);
664 return Error(AliaseeLoc, "An alias must have pointer type");
665 Type *Ty = PTy->getElementType();
666 unsigned AddrSpace = PTy->getAddressSpace();
668 // Okay, create the alias but do not insert it into the module yet.
669 std::unique_ptr<GlobalAlias> GA(
670 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
671 Name, Aliasee, /*Parent*/ nullptr));
672 GA->setThreadLocalMode(TLM);
673 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
674 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
675 GA->setUnnamedAddr(UnnamedAddr);
677 // See if this value already exists in the symbol table. If so, it is either
678 // a redefinition or a definition of a forward reference.
679 if (GlobalValue *Val = M->getNamedValue(Name)) {
680 // See if this was a redefinition. If so, there is no entry in
682 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
683 I = ForwardRefVals.find(Name);
684 if (I == ForwardRefVals.end())
685 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
687 // Otherwise, this was a definition of forward ref. Verify that types
689 if (Val->getType() != GA->getType())
690 return Error(NameLoc,
691 "forward reference and definition of alias have different types");
693 // If they agree, just RAUW the old value with the alias and remove the
695 Val->replaceAllUsesWith(GA.get());
696 Val->eraseFromParent();
697 ForwardRefVals.erase(I);
700 // Insert into the module, we know its name won't collide now.
701 M->getAliasList().push_back(GA.get());
702 assert(GA->getName() == Name && "Should not be a name conflict!");
704 // The module owns this now
711 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
712 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
713 /// OptionalExternallyInitialized GlobalType Type Const
714 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
715 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
716 /// OptionalExternallyInitialized GlobalType Type Const
718 /// Everything up to and including OptionalUnNammedAddr has been parsed
721 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
722 unsigned Linkage, bool HasLinkage,
723 unsigned Visibility, unsigned DLLStorageClass,
724 GlobalVariable::ThreadLocalMode TLM,
726 if (!isValidVisibilityForLinkage(Visibility, Linkage))
727 return Error(NameLoc,
728 "symbol with local linkage must have default visibility");
731 bool IsConstant, IsExternallyInitialized;
732 LocTy IsExternallyInitializedLoc;
736 if (ParseOptionalAddrSpace(AddrSpace) ||
737 ParseOptionalToken(lltok::kw_externally_initialized,
738 IsExternallyInitialized,
739 &IsExternallyInitializedLoc) ||
740 ParseGlobalType(IsConstant) ||
741 ParseType(Ty, TyLoc))
744 // If the linkage is specified and is external, then no initializer is
746 Constant *Init = nullptr;
747 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
748 Linkage != GlobalValue::ExternalLinkage)) {
749 if (ParseGlobalValue(Ty, Init))
753 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
754 return Error(TyLoc, "invalid type for global variable");
756 GlobalValue *GVal = nullptr;
758 // See if the global was forward referenced, if so, use the global.
760 GVal = M->getNamedValue(Name);
762 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
763 return Error(NameLoc, "redefinition of global '@" + Name + "'");
766 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
767 I = ForwardRefValIDs.find(NumberedVals.size());
768 if (I != ForwardRefValIDs.end()) {
769 GVal = I->second.first;
770 ForwardRefValIDs.erase(I);
776 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
777 Name, nullptr, GlobalVariable::NotThreadLocal,
780 if (GVal->getType()->getElementType() != Ty)
782 "forward reference and definition of global have different types");
784 GV = cast<GlobalVariable>(GVal);
786 // Move the forward-reference to the correct spot in the module.
787 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
791 NumberedVals.push_back(GV);
793 // Set the parsed properties on the global.
795 GV->setInitializer(Init);
796 GV->setConstant(IsConstant);
797 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
798 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
799 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
800 GV->setExternallyInitialized(IsExternallyInitialized);
801 GV->setThreadLocalMode(TLM);
802 GV->setUnnamedAddr(UnnamedAddr);
804 // Parse attributes on the global.
805 while (Lex.getKind() == lltok::comma) {
808 if (Lex.getKind() == lltok::kw_section) {
810 GV->setSection(Lex.getStrVal());
811 if (ParseToken(lltok::StringConstant, "expected global section string"))
813 } else if (Lex.getKind() == lltok::kw_align) {
815 if (ParseOptionalAlignment(Alignment)) return true;
816 GV->setAlignment(Alignment);
819 if (parseOptionalComdat(Name, C))
824 return TokError("unknown global variable property!");
831 /// ParseUnnamedAttrGrp
832 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
833 bool LLParser::ParseUnnamedAttrGrp() {
834 assert(Lex.getKind() == lltok::kw_attributes);
835 LocTy AttrGrpLoc = Lex.getLoc();
838 if (Lex.getKind() != lltok::AttrGrpID)
839 return TokError("expected attribute group id");
841 unsigned VarID = Lex.getUIntVal();
842 std::vector<unsigned> unused;
846 if (ParseToken(lltok::equal, "expected '=' here") ||
847 ParseToken(lltok::lbrace, "expected '{' here") ||
848 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
850 ParseToken(lltok::rbrace, "expected end of attribute group"))
853 if (!NumberedAttrBuilders[VarID].hasAttributes())
854 return Error(AttrGrpLoc, "attribute group has no attributes");
859 /// ParseFnAttributeValuePairs
860 /// ::= <attr> | <attr> '=' <value>
861 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
862 std::vector<unsigned> &FwdRefAttrGrps,
863 bool inAttrGrp, LocTy &BuiltinLoc) {
864 bool HaveError = false;
869 lltok::Kind Token = Lex.getKind();
870 if (Token == lltok::kw_builtin)
871 BuiltinLoc = Lex.getLoc();
874 if (!inAttrGrp) return HaveError;
875 return Error(Lex.getLoc(), "unterminated attribute group");
880 case lltok::AttrGrpID: {
881 // Allow a function to reference an attribute group:
883 // define void @foo() #1 { ... }
887 "cannot have an attribute group reference in an attribute group");
889 unsigned AttrGrpNum = Lex.getUIntVal();
890 if (inAttrGrp) break;
892 // Save the reference to the attribute group. We'll fill it in later.
893 FwdRefAttrGrps.push_back(AttrGrpNum);
896 // Target-dependent attributes:
897 case lltok::StringConstant: {
898 std::string Attr = Lex.getStrVal();
901 if (EatIfPresent(lltok::equal) &&
902 ParseStringConstant(Val))
905 B.addAttribute(Attr, Val);
909 // Target-independent attributes:
910 case lltok::kw_align: {
911 // As a hack, we allow function alignment to be initially parsed as an
912 // attribute on a function declaration/definition or added to an attribute
913 // group and later moved to the alignment field.
917 if (ParseToken(lltok::equal, "expected '=' here") ||
918 ParseUInt32(Alignment))
921 if (ParseOptionalAlignment(Alignment))
924 B.addAlignmentAttr(Alignment);
927 case lltok::kw_alignstack: {
931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
935 if (ParseOptionalStackAlignment(Alignment))
938 B.addStackAlignmentAttr(Alignment);
941 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
942 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
943 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
944 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
945 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
946 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
947 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
948 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
949 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
950 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
951 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
952 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
953 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
954 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
955 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
956 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
957 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
958 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
959 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
960 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
961 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
962 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
963 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
964 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
965 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
966 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
967 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
970 case lltok::kw_inreg:
971 case lltok::kw_signext:
972 case lltok::kw_zeroext:
975 "invalid use of attribute on a function");
977 case lltok::kw_byval:
978 case lltok::kw_dereferenceable:
979 case lltok::kw_dereferenceable_or_null:
980 case lltok::kw_inalloca:
982 case lltok::kw_noalias:
983 case lltok::kw_nocapture:
984 case lltok::kw_nonnull:
985 case lltok::kw_returned:
989 "invalid use of parameter-only attribute on a function");
997 //===----------------------------------------------------------------------===//
998 // GlobalValue Reference/Resolution Routines.
999 //===----------------------------------------------------------------------===//
1001 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1002 /// forward reference record if needed. This can return null if the value
1003 /// exists but does not have the right type.
1004 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1006 PointerType *PTy = dyn_cast<PointerType>(Ty);
1008 Error(Loc, "global variable reference must have pointer type");
1012 // Look this name up in the normal function symbol table.
1014 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1016 // If this is a forward reference for the value, see if we already created a
1017 // forward ref record.
1019 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1020 I = ForwardRefVals.find(Name);
1021 if (I != ForwardRefVals.end())
1022 Val = I->second.first;
1025 // If we have the value in the symbol table or fwd-ref table, return it.
1027 if (Val->getType() == Ty) return Val;
1028 Error(Loc, "'@" + Name + "' defined with type '" +
1029 getTypeString(Val->getType()) + "'");
1033 // Otherwise, create a new forward reference for this value and remember it.
1034 GlobalValue *FwdVal;
1035 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1036 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1038 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1039 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1040 nullptr, GlobalVariable::NotThreadLocal,
1041 PTy->getAddressSpace());
1043 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1047 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1048 PointerType *PTy = dyn_cast<PointerType>(Ty);
1050 Error(Loc, "global variable reference must have pointer type");
1054 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1056 // If this is a forward reference for the value, see if we already created a
1057 // forward ref record.
1059 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1060 I = ForwardRefValIDs.find(ID);
1061 if (I != ForwardRefValIDs.end())
1062 Val = I->second.first;
1065 // If we have the value in the symbol table or fwd-ref table, return it.
1067 if (Val->getType() == Ty) return Val;
1068 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1069 getTypeString(Val->getType()) + "'");
1073 // Otherwise, create a new forward reference for this value and remember it.
1074 GlobalValue *FwdVal;
1075 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1076 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1078 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1079 GlobalValue::ExternalWeakLinkage, nullptr, "");
1081 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1086 //===----------------------------------------------------------------------===//
1087 // Comdat Reference/Resolution Routines.
1088 //===----------------------------------------------------------------------===//
1090 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1091 // Look this name up in the comdat symbol table.
1092 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1093 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1094 if (I != ComdatSymTab.end())
1097 // Otherwise, create a new forward reference for this value and remember it.
1098 Comdat *C = M->getOrInsertComdat(Name);
1099 ForwardRefComdats[Name] = Loc;
1104 //===----------------------------------------------------------------------===//
1106 //===----------------------------------------------------------------------===//
1108 /// ParseToken - If the current token has the specified kind, eat it and return
1109 /// success. Otherwise, emit the specified error and return failure.
1110 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1111 if (Lex.getKind() != T)
1112 return TokError(ErrMsg);
1117 /// ParseStringConstant
1118 /// ::= StringConstant
1119 bool LLParser::ParseStringConstant(std::string &Result) {
1120 if (Lex.getKind() != lltok::StringConstant)
1121 return TokError("expected string constant");
1122 Result = Lex.getStrVal();
1129 bool LLParser::ParseUInt32(unsigned &Val) {
1130 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1131 return TokError("expected integer");
1132 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1133 if (Val64 != unsigned(Val64))
1134 return TokError("expected 32-bit integer (too large)");
1142 bool LLParser::ParseUInt64(uint64_t &Val) {
1143 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1144 return TokError("expected integer");
1145 Val = Lex.getAPSIntVal().getLimitedValue();
1151 /// := 'localdynamic'
1152 /// := 'initialexec'
1154 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1155 switch (Lex.getKind()) {
1157 return TokError("expected localdynamic, initialexec or localexec");
1158 case lltok::kw_localdynamic:
1159 TLM = GlobalVariable::LocalDynamicTLSModel;
1161 case lltok::kw_initialexec:
1162 TLM = GlobalVariable::InitialExecTLSModel;
1164 case lltok::kw_localexec:
1165 TLM = GlobalVariable::LocalExecTLSModel;
1173 /// ParseOptionalThreadLocal
1175 /// := 'thread_local'
1176 /// := 'thread_local' '(' tlsmodel ')'
1177 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1178 TLM = GlobalVariable::NotThreadLocal;
1179 if (!EatIfPresent(lltok::kw_thread_local))
1182 TLM = GlobalVariable::GeneralDynamicTLSModel;
1183 if (Lex.getKind() == lltok::lparen) {
1185 return ParseTLSModel(TLM) ||
1186 ParseToken(lltok::rparen, "expected ')' after thread local model");
1191 /// ParseOptionalAddrSpace
1193 /// := 'addrspace' '(' uint32 ')'
1194 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1196 if (!EatIfPresent(lltok::kw_addrspace))
1198 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1199 ParseUInt32(AddrSpace) ||
1200 ParseToken(lltok::rparen, "expected ')' in address space");
1203 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1204 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1205 bool HaveError = false;
1210 lltok::Kind Token = Lex.getKind();
1212 default: // End of attributes.
1214 case lltok::kw_align: {
1216 if (ParseOptionalAlignment(Alignment))
1218 B.addAlignmentAttr(Alignment);
1221 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1222 case lltok::kw_dereferenceable: {
1224 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1226 B.addDereferenceableAttr(Bytes);
1229 case lltok::kw_dereferenceable_or_null: {
1231 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1233 B.addDereferenceableOrNullAttr(Bytes);
1236 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1237 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1238 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1239 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1240 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1241 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1242 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1243 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1244 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1245 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1246 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1247 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1249 case lltok::kw_alignstack:
1250 case lltok::kw_alwaysinline:
1251 case lltok::kw_builtin:
1252 case lltok::kw_inlinehint:
1253 case lltok::kw_jumptable:
1254 case lltok::kw_minsize:
1255 case lltok::kw_naked:
1256 case lltok::kw_nobuiltin:
1257 case lltok::kw_noduplicate:
1258 case lltok::kw_noimplicitfloat:
1259 case lltok::kw_noinline:
1260 case lltok::kw_nonlazybind:
1261 case lltok::kw_noredzone:
1262 case lltok::kw_noreturn:
1263 case lltok::kw_nounwind:
1264 case lltok::kw_optnone:
1265 case lltok::kw_optsize:
1266 case lltok::kw_returns_twice:
1267 case lltok::kw_sanitize_address:
1268 case lltok::kw_sanitize_memory:
1269 case lltok::kw_sanitize_thread:
1271 case lltok::kw_sspreq:
1272 case lltok::kw_sspstrong:
1273 case lltok::kw_uwtable:
1274 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1282 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1283 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1284 bool HaveError = false;
1289 lltok::Kind Token = Lex.getKind();
1291 default: // End of attributes.
1293 case lltok::kw_dereferenceable: {
1295 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1297 B.addDereferenceableAttr(Bytes);
1300 case lltok::kw_dereferenceable_or_null: {
1302 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1304 B.addDereferenceableOrNullAttr(Bytes);
1307 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1308 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1309 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1310 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1311 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1314 case lltok::kw_align:
1315 case lltok::kw_byval:
1316 case lltok::kw_inalloca:
1317 case lltok::kw_nest:
1318 case lltok::kw_nocapture:
1319 case lltok::kw_returned:
1320 case lltok::kw_sret:
1321 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1324 case lltok::kw_alignstack:
1325 case lltok::kw_alwaysinline:
1326 case lltok::kw_builtin:
1327 case lltok::kw_cold:
1328 case lltok::kw_inlinehint:
1329 case lltok::kw_jumptable:
1330 case lltok::kw_minsize:
1331 case lltok::kw_naked:
1332 case lltok::kw_nobuiltin:
1333 case lltok::kw_noduplicate:
1334 case lltok::kw_noimplicitfloat:
1335 case lltok::kw_noinline:
1336 case lltok::kw_nonlazybind:
1337 case lltok::kw_noredzone:
1338 case lltok::kw_noreturn:
1339 case lltok::kw_nounwind:
1340 case lltok::kw_optnone:
1341 case lltok::kw_optsize:
1342 case lltok::kw_returns_twice:
1343 case lltok::kw_sanitize_address:
1344 case lltok::kw_sanitize_memory:
1345 case lltok::kw_sanitize_thread:
1347 case lltok::kw_sspreq:
1348 case lltok::kw_sspstrong:
1349 case lltok::kw_uwtable:
1350 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1353 case lltok::kw_readnone:
1354 case lltok::kw_readonly:
1355 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1362 /// ParseOptionalLinkage
1369 /// ::= 'linkonce_odr'
1370 /// ::= 'available_externally'
1373 /// ::= 'extern_weak'
1375 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1377 switch (Lex.getKind()) {
1378 default: Res=GlobalValue::ExternalLinkage; return false;
1379 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1380 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1381 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1382 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1383 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1384 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1385 case lltok::kw_available_externally:
1386 Res = GlobalValue::AvailableExternallyLinkage;
1388 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1389 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1390 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1391 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1398 /// ParseOptionalVisibility
1404 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1405 switch (Lex.getKind()) {
1406 default: Res = GlobalValue::DefaultVisibility; return false;
1407 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1408 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1409 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1415 /// ParseOptionalDLLStorageClass
1420 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1421 switch (Lex.getKind()) {
1422 default: Res = GlobalValue::DefaultStorageClass; return false;
1423 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1424 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1430 /// ParseOptionalCallingConv
1434 /// ::= 'intel_ocl_bicc'
1436 /// ::= 'x86_stdcallcc'
1437 /// ::= 'x86_fastcallcc'
1438 /// ::= 'x86_thiscallcc'
1439 /// ::= 'x86_vectorcallcc'
1440 /// ::= 'arm_apcscc'
1441 /// ::= 'arm_aapcscc'
1442 /// ::= 'arm_aapcs_vfpcc'
1443 /// ::= 'msp430_intrcc'
1444 /// ::= 'ptx_kernel'
1445 /// ::= 'ptx_device'
1447 /// ::= 'spir_kernel'
1448 /// ::= 'x86_64_sysvcc'
1449 /// ::= 'x86_64_win64cc'
1450 /// ::= 'webkit_jscc'
1452 /// ::= 'preserve_mostcc'
1453 /// ::= 'preserve_allcc'
1457 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1458 switch (Lex.getKind()) {
1459 default: CC = CallingConv::C; return false;
1460 case lltok::kw_ccc: CC = CallingConv::C; break;
1461 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1462 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1463 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1464 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1465 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1466 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1467 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1468 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1469 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1470 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1471 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1472 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1473 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1474 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1475 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1476 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1477 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1478 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1479 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1480 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1481 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1482 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1483 case lltok::kw_cc: {
1485 return ParseUInt32(CC);
1493 /// ParseMetadataAttachment
1495 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1496 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1498 std::string Name = Lex.getStrVal();
1499 Kind = M->getMDKindID(Name);
1502 return ParseMDNode(MD);
1505 /// ParseInstructionMetadata
1506 /// ::= !dbg !42 (',' !dbg !57)*
1507 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1508 PerFunctionState *PFS) {
1510 if (Lex.getKind() != lltok::MetadataVar)
1511 return TokError("expected metadata after comma");
1515 if (ParseMetadataAttachment(MDK, N))
1518 Inst->setMetadata(MDK, N);
1519 if (MDK == LLVMContext::MD_tbaa)
1520 InstsWithTBAATag.push_back(Inst);
1522 // If this is the end of the list, we're done.
1523 } while (EatIfPresent(lltok::comma));
1527 /// ParseOptionalAlignment
1530 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1532 if (!EatIfPresent(lltok::kw_align))
1534 LocTy AlignLoc = Lex.getLoc();
1535 if (ParseUInt32(Alignment)) return true;
1536 if (!isPowerOf2_32(Alignment))
1537 return Error(AlignLoc, "alignment is not a power of two");
1538 if (Alignment > Value::MaximumAlignment)
1539 return Error(AlignLoc, "huge alignments are not supported yet");
1543 /// ParseOptionalDerefAttrBytes
1545 /// ::= AttrKind '(' 4 ')'
1547 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1548 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1550 assert((AttrKind == lltok::kw_dereferenceable ||
1551 AttrKind == lltok::kw_dereferenceable_or_null) &&
1555 if (!EatIfPresent(AttrKind))
1557 LocTy ParenLoc = Lex.getLoc();
1558 if (!EatIfPresent(lltok::lparen))
1559 return Error(ParenLoc, "expected '('");
1560 LocTy DerefLoc = Lex.getLoc();
1561 if (ParseUInt64(Bytes)) return true;
1562 ParenLoc = Lex.getLoc();
1563 if (!EatIfPresent(lltok::rparen))
1564 return Error(ParenLoc, "expected ')'");
1566 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1570 /// ParseOptionalCommaAlign
1574 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1576 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1577 bool &AteExtraComma) {
1578 AteExtraComma = false;
1579 while (EatIfPresent(lltok::comma)) {
1580 // Metadata at the end is an early exit.
1581 if (Lex.getKind() == lltok::MetadataVar) {
1582 AteExtraComma = true;
1586 if (Lex.getKind() != lltok::kw_align)
1587 return Error(Lex.getLoc(), "expected metadata or 'align'");
1589 if (ParseOptionalAlignment(Alignment)) return true;
1595 /// ParseScopeAndOrdering
1596 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1599 /// This sets Scope and Ordering to the parsed values.
1600 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1601 AtomicOrdering &Ordering) {
1605 Scope = CrossThread;
1606 if (EatIfPresent(lltok::kw_singlethread))
1607 Scope = SingleThread;
1609 return ParseOrdering(Ordering);
1613 /// ::= AtomicOrdering
1615 /// This sets Ordering to the parsed value.
1616 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1617 switch (Lex.getKind()) {
1618 default: return TokError("Expected ordering on atomic instruction");
1619 case lltok::kw_unordered: Ordering = Unordered; break;
1620 case lltok::kw_monotonic: Ordering = Monotonic; break;
1621 case lltok::kw_acquire: Ordering = Acquire; break;
1622 case lltok::kw_release: Ordering = Release; break;
1623 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1624 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1630 /// ParseOptionalStackAlignment
1632 /// ::= 'alignstack' '(' 4 ')'
1633 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1635 if (!EatIfPresent(lltok::kw_alignstack))
1637 LocTy ParenLoc = Lex.getLoc();
1638 if (!EatIfPresent(lltok::lparen))
1639 return Error(ParenLoc, "expected '('");
1640 LocTy AlignLoc = Lex.getLoc();
1641 if (ParseUInt32(Alignment)) return true;
1642 ParenLoc = Lex.getLoc();
1643 if (!EatIfPresent(lltok::rparen))
1644 return Error(ParenLoc, "expected ')'");
1645 if (!isPowerOf2_32(Alignment))
1646 return Error(AlignLoc, "stack alignment is not a power of two");
1650 /// ParseIndexList - This parses the index list for an insert/extractvalue
1651 /// instruction. This sets AteExtraComma in the case where we eat an extra
1652 /// comma at the end of the line and find that it is followed by metadata.
1653 /// Clients that don't allow metadata can call the version of this function that
1654 /// only takes one argument.
1657 /// ::= (',' uint32)+
1659 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1660 bool &AteExtraComma) {
1661 AteExtraComma = false;
1663 if (Lex.getKind() != lltok::comma)
1664 return TokError("expected ',' as start of index list");
1666 while (EatIfPresent(lltok::comma)) {
1667 if (Lex.getKind() == lltok::MetadataVar) {
1668 if (Indices.empty()) return TokError("expected index");
1669 AteExtraComma = true;
1673 if (ParseUInt32(Idx)) return true;
1674 Indices.push_back(Idx);
1680 //===----------------------------------------------------------------------===//
1682 //===----------------------------------------------------------------------===//
1684 /// ParseType - Parse a type.
1685 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1686 SMLoc TypeLoc = Lex.getLoc();
1687 switch (Lex.getKind()) {
1689 return TokError(Msg);
1691 // Type ::= 'float' | 'void' (etc)
1692 Result = Lex.getTyVal();
1696 // Type ::= StructType
1697 if (ParseAnonStructType(Result, false))
1700 case lltok::lsquare:
1701 // Type ::= '[' ... ']'
1702 Lex.Lex(); // eat the lsquare.
1703 if (ParseArrayVectorType(Result, false))
1706 case lltok::less: // Either vector or packed struct.
1707 // Type ::= '<' ... '>'
1709 if (Lex.getKind() == lltok::lbrace) {
1710 if (ParseAnonStructType(Result, true) ||
1711 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1713 } else if (ParseArrayVectorType(Result, true))
1716 case lltok::LocalVar: {
1718 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1720 // If the type hasn't been defined yet, create a forward definition and
1721 // remember where that forward def'n was seen (in case it never is defined).
1723 Entry.first = StructType::create(Context, Lex.getStrVal());
1724 Entry.second = Lex.getLoc();
1726 Result = Entry.first;
1731 case lltok::LocalVarID: {
1733 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1735 // If the type hasn't been defined yet, create a forward definition and
1736 // remember where that forward def'n was seen (in case it never is defined).
1738 Entry.first = StructType::create(Context);
1739 Entry.second = Lex.getLoc();
1741 Result = Entry.first;
1747 // Parse the type suffixes.
1749 switch (Lex.getKind()) {
1752 if (!AllowVoid && Result->isVoidTy())
1753 return Error(TypeLoc, "void type only allowed for function results");
1756 // Type ::= Type '*'
1758 if (Result->isLabelTy())
1759 return TokError("basic block pointers are invalid");
1760 if (Result->isVoidTy())
1761 return TokError("pointers to void are invalid - use i8* instead");
1762 if (!PointerType::isValidElementType(Result))
1763 return TokError("pointer to this type is invalid");
1764 Result = PointerType::getUnqual(Result);
1768 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1769 case lltok::kw_addrspace: {
1770 if (Result->isLabelTy())
1771 return TokError("basic block pointers are invalid");
1772 if (Result->isVoidTy())
1773 return TokError("pointers to void are invalid; use i8* instead");
1774 if (!PointerType::isValidElementType(Result))
1775 return TokError("pointer to this type is invalid");
1777 if (ParseOptionalAddrSpace(AddrSpace) ||
1778 ParseToken(lltok::star, "expected '*' in address space"))
1781 Result = PointerType::get(Result, AddrSpace);
1785 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1787 if (ParseFunctionType(Result))
1794 /// ParseParameterList
1796 /// ::= '(' Arg (',' Arg)* ')'
1798 /// ::= Type OptionalAttributes Value OptionalAttributes
1799 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1800 PerFunctionState &PFS, bool IsMustTailCall,
1801 bool InVarArgsFunc) {
1802 if (ParseToken(lltok::lparen, "expected '(' in call"))
1805 unsigned AttrIndex = 1;
1806 while (Lex.getKind() != lltok::rparen) {
1807 // If this isn't the first argument, we need a comma.
1808 if (!ArgList.empty() &&
1809 ParseToken(lltok::comma, "expected ',' in argument list"))
1812 // Parse an ellipsis if this is a musttail call in a variadic function.
1813 if (Lex.getKind() == lltok::dotdotdot) {
1814 const char *Msg = "unexpected ellipsis in argument list for ";
1815 if (!IsMustTailCall)
1816 return TokError(Twine(Msg) + "non-musttail call");
1818 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1819 Lex.Lex(); // Lex the '...', it is purely for readability.
1820 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1823 // Parse the argument.
1825 Type *ArgTy = nullptr;
1826 AttrBuilder ArgAttrs;
1828 if (ParseType(ArgTy, ArgLoc))
1831 if (ArgTy->isMetadataTy()) {
1832 if (ParseMetadataAsValue(V, PFS))
1835 // Otherwise, handle normal operands.
1836 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1839 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1844 if (IsMustTailCall && InVarArgsFunc)
1845 return TokError("expected '...' at end of argument list for musttail call "
1846 "in varargs function");
1848 Lex.Lex(); // Lex the ')'.
1854 /// ParseArgumentList - Parse the argument list for a function type or function
1856 /// ::= '(' ArgTypeListI ')'
1860 /// ::= ArgTypeList ',' '...'
1861 /// ::= ArgType (',' ArgType)*
1863 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1866 assert(Lex.getKind() == lltok::lparen);
1867 Lex.Lex(); // eat the (.
1869 if (Lex.getKind() == lltok::rparen) {
1871 } else if (Lex.getKind() == lltok::dotdotdot) {
1875 LocTy TypeLoc = Lex.getLoc();
1876 Type *ArgTy = nullptr;
1880 if (ParseType(ArgTy) ||
1881 ParseOptionalParamAttrs(Attrs)) return true;
1883 if (ArgTy->isVoidTy())
1884 return Error(TypeLoc, "argument can not have void type");
1886 if (Lex.getKind() == lltok::LocalVar) {
1887 Name = Lex.getStrVal();
1891 if (!FunctionType::isValidArgumentType(ArgTy))
1892 return Error(TypeLoc, "invalid type for function argument");
1894 unsigned AttrIndex = 1;
1895 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1896 AttributeSet::get(ArgTy->getContext(),
1897 AttrIndex++, Attrs), Name));
1899 while (EatIfPresent(lltok::comma)) {
1900 // Handle ... at end of arg list.
1901 if (EatIfPresent(lltok::dotdotdot)) {
1906 // Otherwise must be an argument type.
1907 TypeLoc = Lex.getLoc();
1908 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1910 if (ArgTy->isVoidTy())
1911 return Error(TypeLoc, "argument can not have void type");
1913 if (Lex.getKind() == lltok::LocalVar) {
1914 Name = Lex.getStrVal();
1920 if (!ArgTy->isFirstClassType())
1921 return Error(TypeLoc, "invalid type for function argument");
1923 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1924 AttributeSet::get(ArgTy->getContext(),
1925 AttrIndex++, Attrs),
1930 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1933 /// ParseFunctionType
1934 /// ::= Type ArgumentList OptionalAttrs
1935 bool LLParser::ParseFunctionType(Type *&Result) {
1936 assert(Lex.getKind() == lltok::lparen);
1938 if (!FunctionType::isValidReturnType(Result))
1939 return TokError("invalid function return type");
1941 SmallVector<ArgInfo, 8> ArgList;
1943 if (ParseArgumentList(ArgList, isVarArg))
1946 // Reject names on the arguments lists.
1947 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1948 if (!ArgList[i].Name.empty())
1949 return Error(ArgList[i].Loc, "argument name invalid in function type");
1950 if (ArgList[i].Attrs.hasAttributes(i + 1))
1951 return Error(ArgList[i].Loc,
1952 "argument attributes invalid in function type");
1955 SmallVector<Type*, 16> ArgListTy;
1956 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1957 ArgListTy.push_back(ArgList[i].Ty);
1959 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1963 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1965 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1966 SmallVector<Type*, 8> Elts;
1967 if (ParseStructBody(Elts)) return true;
1969 Result = StructType::get(Context, Elts, Packed);
1973 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1974 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1975 std::pair<Type*, LocTy> &Entry,
1977 // If the type was already defined, diagnose the redefinition.
1978 if (Entry.first && !Entry.second.isValid())
1979 return Error(TypeLoc, "redefinition of type");
1981 // If we have opaque, just return without filling in the definition for the
1982 // struct. This counts as a definition as far as the .ll file goes.
1983 if (EatIfPresent(lltok::kw_opaque)) {
1984 // This type is being defined, so clear the location to indicate this.
1985 Entry.second = SMLoc();
1987 // If this type number has never been uttered, create it.
1989 Entry.first = StructType::create(Context, Name);
1990 ResultTy = Entry.first;
1994 // If the type starts with '<', then it is either a packed struct or a vector.
1995 bool isPacked = EatIfPresent(lltok::less);
1997 // If we don't have a struct, then we have a random type alias, which we
1998 // accept for compatibility with old files. These types are not allowed to be
1999 // forward referenced and not allowed to be recursive.
2000 if (Lex.getKind() != lltok::lbrace) {
2002 return Error(TypeLoc, "forward references to non-struct type");
2006 return ParseArrayVectorType(ResultTy, true);
2007 return ParseType(ResultTy);
2010 // This type is being defined, so clear the location to indicate this.
2011 Entry.second = SMLoc();
2013 // If this type number has never been uttered, create it.
2015 Entry.first = StructType::create(Context, Name);
2017 StructType *STy = cast<StructType>(Entry.first);
2019 SmallVector<Type*, 8> Body;
2020 if (ParseStructBody(Body) ||
2021 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2024 STy->setBody(Body, isPacked);
2030 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2033 /// ::= '{' Type (',' Type)* '}'
2034 /// ::= '<' '{' '}' '>'
2035 /// ::= '<' '{' Type (',' Type)* '}' '>'
2036 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2037 assert(Lex.getKind() == lltok::lbrace);
2038 Lex.Lex(); // Consume the '{'
2040 // Handle the empty struct.
2041 if (EatIfPresent(lltok::rbrace))
2044 LocTy EltTyLoc = Lex.getLoc();
2046 if (ParseType(Ty)) return true;
2049 if (!StructType::isValidElementType(Ty))
2050 return Error(EltTyLoc, "invalid element type for struct");
2052 while (EatIfPresent(lltok::comma)) {
2053 EltTyLoc = Lex.getLoc();
2054 if (ParseType(Ty)) return true;
2056 if (!StructType::isValidElementType(Ty))
2057 return Error(EltTyLoc, "invalid element type for struct");
2062 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2065 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2066 /// token has already been consumed.
2068 /// ::= '[' APSINTVAL 'x' Types ']'
2069 /// ::= '<' APSINTVAL 'x' Types '>'
2070 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2071 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2072 Lex.getAPSIntVal().getBitWidth() > 64)
2073 return TokError("expected number in address space");
2075 LocTy SizeLoc = Lex.getLoc();
2076 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2079 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2082 LocTy TypeLoc = Lex.getLoc();
2083 Type *EltTy = nullptr;
2084 if (ParseType(EltTy)) return true;
2086 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2087 "expected end of sequential type"))
2092 return Error(SizeLoc, "zero element vector is illegal");
2093 if ((unsigned)Size != Size)
2094 return Error(SizeLoc, "size too large for vector");
2095 if (!VectorType::isValidElementType(EltTy))
2096 return Error(TypeLoc, "invalid vector element type");
2097 Result = VectorType::get(EltTy, unsigned(Size));
2099 if (!ArrayType::isValidElementType(EltTy))
2100 return Error(TypeLoc, "invalid array element type");
2101 Result = ArrayType::get(EltTy, Size);
2106 //===----------------------------------------------------------------------===//
2107 // Function Semantic Analysis.
2108 //===----------------------------------------------------------------------===//
2110 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2112 : P(p), F(f), FunctionNumber(functionNumber) {
2114 // Insert unnamed arguments into the NumberedVals list.
2115 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2118 NumberedVals.push_back(AI);
2121 LLParser::PerFunctionState::~PerFunctionState() {
2122 // If there were any forward referenced non-basicblock values, delete them.
2123 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2124 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2125 if (!isa<BasicBlock>(I->second.first)) {
2126 I->second.first->replaceAllUsesWith(
2127 UndefValue::get(I->second.first->getType()));
2128 delete I->second.first;
2129 I->second.first = nullptr;
2132 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2133 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2134 if (!isa<BasicBlock>(I->second.first)) {
2135 I->second.first->replaceAllUsesWith(
2136 UndefValue::get(I->second.first->getType()));
2137 delete I->second.first;
2138 I->second.first = nullptr;
2142 bool LLParser::PerFunctionState::FinishFunction() {
2143 if (!ForwardRefVals.empty())
2144 return P.Error(ForwardRefVals.begin()->second.second,
2145 "use of undefined value '%" + ForwardRefVals.begin()->first +
2147 if (!ForwardRefValIDs.empty())
2148 return P.Error(ForwardRefValIDs.begin()->second.second,
2149 "use of undefined value '%" +
2150 Twine(ForwardRefValIDs.begin()->first) + "'");
2155 /// GetVal - Get a value with the specified name or ID, creating a
2156 /// forward reference record if needed. This can return null if the value
2157 /// exists but does not have the right type.
2158 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2159 Type *Ty, LocTy Loc) {
2160 // Look this name up in the normal function symbol table.
2161 Value *Val = F.getValueSymbolTable().lookup(Name);
2163 // If this is a forward reference for the value, see if we already created a
2164 // forward ref record.
2166 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2167 I = ForwardRefVals.find(Name);
2168 if (I != ForwardRefVals.end())
2169 Val = I->second.first;
2172 // If we have the value in the symbol table or fwd-ref table, return it.
2174 if (Val->getType() == Ty) return Val;
2175 if (Ty->isLabelTy())
2176 P.Error(Loc, "'%" + Name + "' is not a basic block");
2178 P.Error(Loc, "'%" + Name + "' defined with type '" +
2179 getTypeString(Val->getType()) + "'");
2183 // Don't make placeholders with invalid type.
2184 if (!Ty->isFirstClassType()) {
2185 P.Error(Loc, "invalid use of a non-first-class type");
2189 // Otherwise, create a new forward reference for this value and remember it.
2191 if (Ty->isLabelTy())
2192 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2194 FwdVal = new Argument(Ty, Name);
2196 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2200 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2202 // Look this name up in the normal function symbol table.
2203 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2205 // If this is a forward reference for the value, see if we already created a
2206 // forward ref record.
2208 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2209 I = ForwardRefValIDs.find(ID);
2210 if (I != ForwardRefValIDs.end())
2211 Val = I->second.first;
2214 // If we have the value in the symbol table or fwd-ref table, return it.
2216 if (Val->getType() == Ty) return Val;
2217 if (Ty->isLabelTy())
2218 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2220 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2221 getTypeString(Val->getType()) + "'");
2225 if (!Ty->isFirstClassType()) {
2226 P.Error(Loc, "invalid use of a non-first-class type");
2230 // Otherwise, create a new forward reference for this value and remember it.
2232 if (Ty->isLabelTy())
2233 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2235 FwdVal = new Argument(Ty);
2237 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2241 /// SetInstName - After an instruction is parsed and inserted into its
2242 /// basic block, this installs its name.
2243 bool LLParser::PerFunctionState::SetInstName(int NameID,
2244 const std::string &NameStr,
2245 LocTy NameLoc, Instruction *Inst) {
2246 // If this instruction has void type, it cannot have a name or ID specified.
2247 if (Inst->getType()->isVoidTy()) {
2248 if (NameID != -1 || !NameStr.empty())
2249 return P.Error(NameLoc, "instructions returning void cannot have a name");
2253 // If this was a numbered instruction, verify that the instruction is the
2254 // expected value and resolve any forward references.
2255 if (NameStr.empty()) {
2256 // If neither a name nor an ID was specified, just use the next ID.
2258 NameID = NumberedVals.size();
2260 if (unsigned(NameID) != NumberedVals.size())
2261 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2262 Twine(NumberedVals.size()) + "'");
2264 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2265 ForwardRefValIDs.find(NameID);
2266 if (FI != ForwardRefValIDs.end()) {
2267 if (FI->second.first->getType() != Inst->getType())
2268 return P.Error(NameLoc, "instruction forward referenced with type '" +
2269 getTypeString(FI->second.first->getType()) + "'");
2270 FI->second.first->replaceAllUsesWith(Inst);
2271 delete FI->second.first;
2272 ForwardRefValIDs.erase(FI);
2275 NumberedVals.push_back(Inst);
2279 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2280 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2281 FI = ForwardRefVals.find(NameStr);
2282 if (FI != ForwardRefVals.end()) {
2283 if (FI->second.first->getType() != Inst->getType())
2284 return P.Error(NameLoc, "instruction forward referenced with type '" +
2285 getTypeString(FI->second.first->getType()) + "'");
2286 FI->second.first->replaceAllUsesWith(Inst);
2287 delete FI->second.first;
2288 ForwardRefVals.erase(FI);
2291 // Set the name on the instruction.
2292 Inst->setName(NameStr);
2294 if (Inst->getName() != NameStr)
2295 return P.Error(NameLoc, "multiple definition of local value named '" +
2300 /// GetBB - Get a basic block with the specified name or ID, creating a
2301 /// forward reference record if needed.
2302 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2304 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2305 Type::getLabelTy(F.getContext()), Loc));
2308 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2309 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2310 Type::getLabelTy(F.getContext()), Loc));
2313 /// DefineBB - Define the specified basic block, which is either named or
2314 /// unnamed. If there is an error, this returns null otherwise it returns
2315 /// the block being defined.
2316 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2320 BB = GetBB(NumberedVals.size(), Loc);
2322 BB = GetBB(Name, Loc);
2323 if (!BB) return nullptr; // Already diagnosed error.
2325 // Move the block to the end of the function. Forward ref'd blocks are
2326 // inserted wherever they happen to be referenced.
2327 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2329 // Remove the block from forward ref sets.
2331 ForwardRefValIDs.erase(NumberedVals.size());
2332 NumberedVals.push_back(BB);
2334 // BB forward references are already in the function symbol table.
2335 ForwardRefVals.erase(Name);
2341 //===----------------------------------------------------------------------===//
2343 //===----------------------------------------------------------------------===//
2345 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2346 /// type implied. For example, if we parse "4" we don't know what integer type
2347 /// it has. The value will later be combined with its type and checked for
2348 /// sanity. PFS is used to convert function-local operands of metadata (since
2349 /// metadata operands are not just parsed here but also converted to values).
2350 /// PFS can be null when we are not parsing metadata values inside a function.
2351 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2352 ID.Loc = Lex.getLoc();
2353 switch (Lex.getKind()) {
2354 default: return TokError("expected value token");
2355 case lltok::GlobalID: // @42
2356 ID.UIntVal = Lex.getUIntVal();
2357 ID.Kind = ValID::t_GlobalID;
2359 case lltok::GlobalVar: // @foo
2360 ID.StrVal = Lex.getStrVal();
2361 ID.Kind = ValID::t_GlobalName;
2363 case lltok::LocalVarID: // %42
2364 ID.UIntVal = Lex.getUIntVal();
2365 ID.Kind = ValID::t_LocalID;
2367 case lltok::LocalVar: // %foo
2368 ID.StrVal = Lex.getStrVal();
2369 ID.Kind = ValID::t_LocalName;
2372 ID.APSIntVal = Lex.getAPSIntVal();
2373 ID.Kind = ValID::t_APSInt;
2375 case lltok::APFloat:
2376 ID.APFloatVal = Lex.getAPFloatVal();
2377 ID.Kind = ValID::t_APFloat;
2379 case lltok::kw_true:
2380 ID.ConstantVal = ConstantInt::getTrue(Context);
2381 ID.Kind = ValID::t_Constant;
2383 case lltok::kw_false:
2384 ID.ConstantVal = ConstantInt::getFalse(Context);
2385 ID.Kind = ValID::t_Constant;
2387 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2388 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2389 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2391 case lltok::lbrace: {
2392 // ValID ::= '{' ConstVector '}'
2394 SmallVector<Constant*, 16> Elts;
2395 if (ParseGlobalValueVector(Elts) ||
2396 ParseToken(lltok::rbrace, "expected end of struct constant"))
2399 ID.ConstantStructElts = new Constant*[Elts.size()];
2400 ID.UIntVal = Elts.size();
2401 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2402 ID.Kind = ValID::t_ConstantStruct;
2406 // ValID ::= '<' ConstVector '>' --> Vector.
2407 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2409 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2411 SmallVector<Constant*, 16> Elts;
2412 LocTy FirstEltLoc = Lex.getLoc();
2413 if (ParseGlobalValueVector(Elts) ||
2415 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2416 ParseToken(lltok::greater, "expected end of constant"))
2419 if (isPackedStruct) {
2420 ID.ConstantStructElts = new Constant*[Elts.size()];
2421 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2422 ID.UIntVal = Elts.size();
2423 ID.Kind = ValID::t_PackedConstantStruct;
2428 return Error(ID.Loc, "constant vector must not be empty");
2430 if (!Elts[0]->getType()->isIntegerTy() &&
2431 !Elts[0]->getType()->isFloatingPointTy() &&
2432 !Elts[0]->getType()->isPointerTy())
2433 return Error(FirstEltLoc,
2434 "vector elements must have integer, pointer or floating point type");
2436 // Verify that all the vector elements have the same type.
2437 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2438 if (Elts[i]->getType() != Elts[0]->getType())
2439 return Error(FirstEltLoc,
2440 "vector element #" + Twine(i) +
2441 " is not of type '" + getTypeString(Elts[0]->getType()));
2443 ID.ConstantVal = ConstantVector::get(Elts);
2444 ID.Kind = ValID::t_Constant;
2447 case lltok::lsquare: { // Array Constant
2449 SmallVector<Constant*, 16> Elts;
2450 LocTy FirstEltLoc = Lex.getLoc();
2451 if (ParseGlobalValueVector(Elts) ||
2452 ParseToken(lltok::rsquare, "expected end of array constant"))
2455 // Handle empty element.
2457 // Use undef instead of an array because it's inconvenient to determine
2458 // the element type at this point, there being no elements to examine.
2459 ID.Kind = ValID::t_EmptyArray;
2463 if (!Elts[0]->getType()->isFirstClassType())
2464 return Error(FirstEltLoc, "invalid array element type: " +
2465 getTypeString(Elts[0]->getType()));
2467 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2469 // Verify all elements are correct type!
2470 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2471 if (Elts[i]->getType() != Elts[0]->getType())
2472 return Error(FirstEltLoc,
2473 "array element #" + Twine(i) +
2474 " is not of type '" + getTypeString(Elts[0]->getType()));
2477 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2478 ID.Kind = ValID::t_Constant;
2481 case lltok::kw_c: // c "foo"
2483 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2485 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2486 ID.Kind = ValID::t_Constant;
2489 case lltok::kw_asm: {
2490 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2492 bool HasSideEffect, AlignStack, AsmDialect;
2494 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2495 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2496 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2497 ParseStringConstant(ID.StrVal) ||
2498 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2499 ParseToken(lltok::StringConstant, "expected constraint string"))
2501 ID.StrVal2 = Lex.getStrVal();
2502 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2503 (unsigned(AsmDialect)<<2);
2504 ID.Kind = ValID::t_InlineAsm;
2508 case lltok::kw_blockaddress: {
2509 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2514 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2516 ParseToken(lltok::comma, "expected comma in block address expression")||
2517 ParseValID(Label) ||
2518 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2521 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2522 return Error(Fn.Loc, "expected function name in blockaddress");
2523 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2524 return Error(Label.Loc, "expected basic block name in blockaddress");
2526 // Try to find the function (but skip it if it's forward-referenced).
2527 GlobalValue *GV = nullptr;
2528 if (Fn.Kind == ValID::t_GlobalID) {
2529 if (Fn.UIntVal < NumberedVals.size())
2530 GV = NumberedVals[Fn.UIntVal];
2531 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2532 GV = M->getNamedValue(Fn.StrVal);
2534 Function *F = nullptr;
2536 // Confirm that it's actually a function with a definition.
2537 if (!isa<Function>(GV))
2538 return Error(Fn.Loc, "expected function name in blockaddress");
2539 F = cast<Function>(GV);
2540 if (F->isDeclaration())
2541 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2545 // Make a global variable as a placeholder for this reference.
2546 GlobalValue *&FwdRef =
2547 ForwardRefBlockAddresses.insert(std::make_pair(
2549 std::map<ValID, GlobalValue *>()))
2550 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2553 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2554 GlobalValue::InternalLinkage, nullptr, "");
2555 ID.ConstantVal = FwdRef;
2556 ID.Kind = ValID::t_Constant;
2560 // We found the function; now find the basic block. Don't use PFS, since we
2561 // might be inside a constant expression.
2563 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2564 if (Label.Kind == ValID::t_LocalID)
2565 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2567 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2569 return Error(Label.Loc, "referenced value is not a basic block");
2571 if (Label.Kind == ValID::t_LocalID)
2572 return Error(Label.Loc, "cannot take address of numeric label after "
2573 "the function is defined");
2574 BB = dyn_cast_or_null<BasicBlock>(
2575 F->getValueSymbolTable().lookup(Label.StrVal));
2577 return Error(Label.Loc, "referenced value is not a basic block");
2580 ID.ConstantVal = BlockAddress::get(F, BB);
2581 ID.Kind = ValID::t_Constant;
2585 case lltok::kw_trunc:
2586 case lltok::kw_zext:
2587 case lltok::kw_sext:
2588 case lltok::kw_fptrunc:
2589 case lltok::kw_fpext:
2590 case lltok::kw_bitcast:
2591 case lltok::kw_addrspacecast:
2592 case lltok::kw_uitofp:
2593 case lltok::kw_sitofp:
2594 case lltok::kw_fptoui:
2595 case lltok::kw_fptosi:
2596 case lltok::kw_inttoptr:
2597 case lltok::kw_ptrtoint: {
2598 unsigned Opc = Lex.getUIntVal();
2599 Type *DestTy = nullptr;
2602 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2603 ParseGlobalTypeAndValue(SrcVal) ||
2604 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2605 ParseType(DestTy) ||
2606 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2608 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2609 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2610 getTypeString(SrcVal->getType()) + "' to '" +
2611 getTypeString(DestTy) + "'");
2612 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2614 ID.Kind = ValID::t_Constant;
2617 case lltok::kw_extractvalue: {
2620 SmallVector<unsigned, 4> Indices;
2621 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2622 ParseGlobalTypeAndValue(Val) ||
2623 ParseIndexList(Indices) ||
2624 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2627 if (!Val->getType()->isAggregateType())
2628 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2629 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2630 return Error(ID.Loc, "invalid indices for extractvalue");
2631 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2632 ID.Kind = ValID::t_Constant;
2635 case lltok::kw_insertvalue: {
2637 Constant *Val0, *Val1;
2638 SmallVector<unsigned, 4> Indices;
2639 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2640 ParseGlobalTypeAndValue(Val0) ||
2641 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2642 ParseGlobalTypeAndValue(Val1) ||
2643 ParseIndexList(Indices) ||
2644 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2646 if (!Val0->getType()->isAggregateType())
2647 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2649 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2651 return Error(ID.Loc, "invalid indices for insertvalue");
2652 if (IndexedType != Val1->getType())
2653 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2654 getTypeString(Val1->getType()) +
2655 "' instead of '" + getTypeString(IndexedType) +
2657 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2658 ID.Kind = ValID::t_Constant;
2661 case lltok::kw_icmp:
2662 case lltok::kw_fcmp: {
2663 unsigned PredVal, Opc = Lex.getUIntVal();
2664 Constant *Val0, *Val1;
2666 if (ParseCmpPredicate(PredVal, Opc) ||
2667 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2668 ParseGlobalTypeAndValue(Val0) ||
2669 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2670 ParseGlobalTypeAndValue(Val1) ||
2671 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2674 if (Val0->getType() != Val1->getType())
2675 return Error(ID.Loc, "compare operands must have the same type");
2677 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2679 if (Opc == Instruction::FCmp) {
2680 if (!Val0->getType()->isFPOrFPVectorTy())
2681 return Error(ID.Loc, "fcmp requires floating point operands");
2682 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2684 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2685 if (!Val0->getType()->isIntOrIntVectorTy() &&
2686 !Val0->getType()->getScalarType()->isPointerTy())
2687 return Error(ID.Loc, "icmp requires pointer or integer operands");
2688 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2690 ID.Kind = ValID::t_Constant;
2694 // Binary Operators.
2696 case lltok::kw_fadd:
2698 case lltok::kw_fsub:
2700 case lltok::kw_fmul:
2701 case lltok::kw_udiv:
2702 case lltok::kw_sdiv:
2703 case lltok::kw_fdiv:
2704 case lltok::kw_urem:
2705 case lltok::kw_srem:
2706 case lltok::kw_frem:
2708 case lltok::kw_lshr:
2709 case lltok::kw_ashr: {
2713 unsigned Opc = Lex.getUIntVal();
2714 Constant *Val0, *Val1;
2716 LocTy ModifierLoc = Lex.getLoc();
2717 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2718 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2719 if (EatIfPresent(lltok::kw_nuw))
2721 if (EatIfPresent(lltok::kw_nsw)) {
2723 if (EatIfPresent(lltok::kw_nuw))
2726 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2727 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2728 if (EatIfPresent(lltok::kw_exact))
2731 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2732 ParseGlobalTypeAndValue(Val0) ||
2733 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2734 ParseGlobalTypeAndValue(Val1) ||
2735 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2737 if (Val0->getType() != Val1->getType())
2738 return Error(ID.Loc, "operands of constexpr must have same type");
2739 if (!Val0->getType()->isIntOrIntVectorTy()) {
2741 return Error(ModifierLoc, "nuw only applies to integer operations");
2743 return Error(ModifierLoc, "nsw only applies to integer operations");
2745 // Check that the type is valid for the operator.
2747 case Instruction::Add:
2748 case Instruction::Sub:
2749 case Instruction::Mul:
2750 case Instruction::UDiv:
2751 case Instruction::SDiv:
2752 case Instruction::URem:
2753 case Instruction::SRem:
2754 case Instruction::Shl:
2755 case Instruction::AShr:
2756 case Instruction::LShr:
2757 if (!Val0->getType()->isIntOrIntVectorTy())
2758 return Error(ID.Loc, "constexpr requires integer operands");
2760 case Instruction::FAdd:
2761 case Instruction::FSub:
2762 case Instruction::FMul:
2763 case Instruction::FDiv:
2764 case Instruction::FRem:
2765 if (!Val0->getType()->isFPOrFPVectorTy())
2766 return Error(ID.Loc, "constexpr requires fp operands");
2768 default: llvm_unreachable("Unknown binary operator!");
2771 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2772 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2773 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2774 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2776 ID.Kind = ValID::t_Constant;
2780 // Logical Operations
2783 case lltok::kw_xor: {
2784 unsigned Opc = Lex.getUIntVal();
2785 Constant *Val0, *Val1;
2787 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2788 ParseGlobalTypeAndValue(Val0) ||
2789 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2790 ParseGlobalTypeAndValue(Val1) ||
2791 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2793 if (Val0->getType() != Val1->getType())
2794 return Error(ID.Loc, "operands of constexpr must have same type");
2795 if (!Val0->getType()->isIntOrIntVectorTy())
2796 return Error(ID.Loc,
2797 "constexpr requires integer or integer vector operands");
2798 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2799 ID.Kind = ValID::t_Constant;
2803 case lltok::kw_getelementptr:
2804 case lltok::kw_shufflevector:
2805 case lltok::kw_insertelement:
2806 case lltok::kw_extractelement:
2807 case lltok::kw_select: {
2808 unsigned Opc = Lex.getUIntVal();
2809 SmallVector<Constant*, 16> Elts;
2810 bool InBounds = false;
2814 if (Opc == Instruction::GetElementPtr)
2815 InBounds = EatIfPresent(lltok::kw_inbounds);
2817 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2820 LocTy ExplicitTypeLoc = Lex.getLoc();
2821 if (Opc == Instruction::GetElementPtr) {
2822 if (ParseType(Ty) ||
2823 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2827 if (ParseGlobalValueVector(Elts) ||
2828 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2831 if (Opc == Instruction::GetElementPtr) {
2832 if (Elts.size() == 0 ||
2833 !Elts[0]->getType()->getScalarType()->isPointerTy())
2834 return Error(ID.Loc, "base of getelementptr must be a pointer");
2836 Type *BaseType = Elts[0]->getType();
2837 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2838 if (Ty != BasePointerType->getElementType())
2841 "explicit pointee type doesn't match operand's pointee type");
2843 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2844 for (Constant *Val : Indices) {
2845 Type *ValTy = Val->getType();
2846 if (!ValTy->getScalarType()->isIntegerTy())
2847 return Error(ID.Loc, "getelementptr index must be an integer");
2848 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2849 return Error(ID.Loc, "getelementptr index type missmatch");
2850 if (ValTy->isVectorTy()) {
2851 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2852 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2853 if (ValNumEl != PtrNumEl)
2856 "getelementptr vector index has a wrong number of elements");
2860 SmallPtrSet<const Type*, 4> Visited;
2861 if (!Indices.empty() && !Ty->isSized(&Visited))
2862 return Error(ID.Loc, "base element of getelementptr must be sized");
2864 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2865 return Error(ID.Loc, "invalid getelementptr indices");
2867 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2868 } else if (Opc == Instruction::Select) {
2869 if (Elts.size() != 3)
2870 return Error(ID.Loc, "expected three operands to select");
2871 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2873 return Error(ID.Loc, Reason);
2874 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2875 } else if (Opc == Instruction::ShuffleVector) {
2876 if (Elts.size() != 3)
2877 return Error(ID.Loc, "expected three operands to shufflevector");
2878 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2879 return Error(ID.Loc, "invalid operands to shufflevector");
2881 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2882 } else if (Opc == Instruction::ExtractElement) {
2883 if (Elts.size() != 2)
2884 return Error(ID.Loc, "expected two operands to extractelement");
2885 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2886 return Error(ID.Loc, "invalid extractelement operands");
2887 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2889 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2890 if (Elts.size() != 3)
2891 return Error(ID.Loc, "expected three operands to insertelement");
2892 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2893 return Error(ID.Loc, "invalid insertelement operands");
2895 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2898 ID.Kind = ValID::t_Constant;
2907 /// ParseGlobalValue - Parse a global value with the specified type.
2908 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2912 bool Parsed = ParseValID(ID) ||
2913 ConvertValIDToValue(Ty, ID, V, nullptr);
2914 if (V && !(C = dyn_cast<Constant>(V)))
2915 return Error(ID.Loc, "global values must be constants");
2919 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2921 return ParseType(Ty) ||
2922 ParseGlobalValue(Ty, V);
2925 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2928 LocTy KwLoc = Lex.getLoc();
2929 if (!EatIfPresent(lltok::kw_comdat))
2932 if (EatIfPresent(lltok::lparen)) {
2933 if (Lex.getKind() != lltok::ComdatVar)
2934 return TokError("expected comdat variable");
2935 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2937 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2940 if (GlobalName.empty())
2941 return TokError("comdat cannot be unnamed");
2942 C = getComdat(GlobalName, KwLoc);
2948 /// ParseGlobalValueVector
2950 /// ::= TypeAndValue (',' TypeAndValue)*
2951 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2953 if (Lex.getKind() == lltok::rbrace ||
2954 Lex.getKind() == lltok::rsquare ||
2955 Lex.getKind() == lltok::greater ||
2956 Lex.getKind() == lltok::rparen)
2960 if (ParseGlobalTypeAndValue(C)) return true;
2963 while (EatIfPresent(lltok::comma)) {
2964 if (ParseGlobalTypeAndValue(C)) return true;
2971 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2972 SmallVector<Metadata *, 16> Elts;
2973 if (ParseMDNodeVector(Elts))
2976 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2983 /// ::= !MDLocation(...)
2984 bool LLParser::ParseMDNode(MDNode *&N) {
2985 if (Lex.getKind() == lltok::MetadataVar)
2986 return ParseSpecializedMDNode(N);
2988 return ParseToken(lltok::exclaim, "expected '!' here") ||
2992 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2994 if (Lex.getKind() == lltok::lbrace)
2995 return ParseMDTuple(N);
2998 return ParseMDNodeID(N);
3003 /// Structure to represent an optional metadata field.
3004 template <class FieldTy> struct MDFieldImpl {
3005 typedef MDFieldImpl ImplTy;
3009 void assign(FieldTy Val) {
3011 this->Val = std::move(Val);
3014 explicit MDFieldImpl(FieldTy Default)
3015 : Val(std::move(Default)), Seen(false) {}
3018 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3021 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3022 : ImplTy(Default), Max(Max) {}
3024 struct LineField : public MDUnsignedField {
3025 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3027 struct ColumnField : public MDUnsignedField {
3028 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3030 struct DwarfTagField : public MDUnsignedField {
3031 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3032 DwarfTagField(dwarf::Tag DefaultTag)
3033 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3035 struct DwarfAttEncodingField : public MDUnsignedField {
3036 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3038 struct DwarfVirtualityField : public MDUnsignedField {
3039 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3041 struct DwarfLangField : public MDUnsignedField {
3042 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3045 struct DIFlagField : public MDUnsignedField {
3046 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3049 struct MDSignedField : public MDFieldImpl<int64_t> {
3053 MDSignedField(int64_t Default = 0)
3054 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3055 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3056 : ImplTy(Default), Min(Min), Max(Max) {}
3059 struct MDBoolField : public MDFieldImpl<bool> {
3060 MDBoolField(bool Default = false) : ImplTy(Default) {}
3062 struct MDField : public MDFieldImpl<Metadata *> {
3065 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3067 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3068 MDConstant() : ImplTy(nullptr) {}
3070 struct MDStringField : public MDFieldImpl<MDString *> {
3072 MDStringField(bool AllowEmpty = true)
3073 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3075 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3076 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3084 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3085 MDUnsignedField &Result) {
3086 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3087 return TokError("expected unsigned integer");
3089 auto &U = Lex.getAPSIntVal();
3090 if (U.ugt(Result.Max))
3091 return TokError("value for '" + Name + "' too large, limit is " +
3093 Result.assign(U.getZExtValue());
3094 assert(Result.Val <= Result.Max && "Expected value in range");
3100 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3101 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3104 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3105 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3109 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3110 if (Lex.getKind() == lltok::APSInt)
3111 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3113 if (Lex.getKind() != lltok::DwarfTag)
3114 return TokError("expected DWARF tag");
3116 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3117 if (Tag == dwarf::DW_TAG_invalid)
3118 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3119 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3127 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3128 DwarfVirtualityField &Result) {
3129 if (Lex.getKind() == lltok::APSInt)
3130 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3132 if (Lex.getKind() != lltok::DwarfVirtuality)
3133 return TokError("expected DWARF virtuality code");
3135 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3137 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3138 Lex.getStrVal() + "'");
3139 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3140 Result.assign(Virtuality);
3146 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3147 if (Lex.getKind() == lltok::APSInt)
3148 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3150 if (Lex.getKind() != lltok::DwarfLang)
3151 return TokError("expected DWARF language");
3153 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3155 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3157 assert(Lang <= Result.Max && "Expected valid DWARF language");
3158 Result.assign(Lang);
3164 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3165 DwarfAttEncodingField &Result) {
3166 if (Lex.getKind() == lltok::APSInt)
3167 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3169 if (Lex.getKind() != lltok::DwarfAttEncoding)
3170 return TokError("expected DWARF type attribute encoding");
3172 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3174 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3175 Lex.getStrVal() + "'");
3176 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3177 Result.assign(Encoding);
3184 /// ::= DIFlagVector
3185 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3187 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3188 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3190 // Parser for a single flag.
3191 auto parseFlag = [&](unsigned &Val) {
3192 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3193 return ParseUInt32(Val);
3195 if (Lex.getKind() != lltok::DIFlag)
3196 return TokError("expected debug info flag");
3198 Val = DebugNode::getFlag(Lex.getStrVal());
3200 return TokError(Twine("invalid debug info flag flag '") +
3201 Lex.getStrVal() + "'");
3206 // Parse the flags and combine them together.
3207 unsigned Combined = 0;
3213 } while (EatIfPresent(lltok::bar));
3215 Result.assign(Combined);
3220 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3221 MDSignedField &Result) {
3222 if (Lex.getKind() != lltok::APSInt)
3223 return TokError("expected signed integer");
3225 auto &S = Lex.getAPSIntVal();
3227 return TokError("value for '" + Name + "' too small, limit is " +
3230 return TokError("value for '" + Name + "' too large, limit is " +
3232 Result.assign(S.getExtValue());
3233 assert(Result.Val >= Result.Min && "Expected value in range");
3234 assert(Result.Val <= Result.Max && "Expected value in range");
3240 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3241 switch (Lex.getKind()) {
3243 return TokError("expected 'true' or 'false'");
3244 case lltok::kw_true:
3245 Result.assign(true);
3247 case lltok::kw_false:
3248 Result.assign(false);
3256 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3257 if (Lex.getKind() == lltok::kw_null) {
3258 if (!Result.AllowNull)
3259 return TokError("'" + Name + "' cannot be null");
3261 Result.assign(nullptr);
3266 if (ParseMetadata(MD, nullptr))
3274 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3276 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3279 Result.assign(cast<ConstantAsMetadata>(MD));
3284 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3285 LocTy ValueLoc = Lex.getLoc();
3287 if (ParseStringConstant(S))
3290 if (!Result.AllowEmpty && S.empty())
3291 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3293 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3298 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3299 SmallVector<Metadata *, 4> MDs;
3300 if (ParseMDNodeVector(MDs))
3303 Result.assign(std::move(MDs));
3307 } // end namespace llvm
3309 template <class ParserTy>
3310 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3312 if (Lex.getKind() != lltok::LabelStr)
3313 return TokError("expected field label here");
3317 } while (EatIfPresent(lltok::comma));
3322 template <class ParserTy>
3323 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3324 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3327 if (ParseToken(lltok::lparen, "expected '(' here"))
3329 if (Lex.getKind() != lltok::rparen)
3330 if (ParseMDFieldsImplBody(parseField))
3333 ClosingLoc = Lex.getLoc();
3334 return ParseToken(lltok::rparen, "expected ')' here");
3337 template <class FieldTy>
3338 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3340 return TokError("field '" + Name + "' cannot be specified more than once");
3342 LocTy Loc = Lex.getLoc();
3344 return ParseMDField(Loc, Name, Result);
3347 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3348 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3350 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3351 if (Lex.getStrVal() == #CLASS) \
3352 return Parse##CLASS(N, IsDistinct);
3353 #include "llvm/IR/Metadata.def"
3355 return TokError("expected metadata type");
3358 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3359 #define NOP_FIELD(NAME, TYPE, INIT)
3360 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3362 return Error(ClosingLoc, "missing required field '" #NAME "'");
3363 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3364 if (Lex.getStrVal() == #NAME) \
3365 return ParseMDField(#NAME, NAME);
3366 #define PARSE_MD_FIELDS() \
3367 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3370 if (ParseMDFieldsImpl([&]() -> bool { \
3371 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3372 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3375 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3377 #define GET_OR_DISTINCT(CLASS, ARGS) \
3378 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3380 /// ParseMDLocationFields:
3381 /// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3382 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3383 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3384 OPTIONAL(line, LineField, ); \
3385 OPTIONAL(column, ColumnField, ); \
3386 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3387 OPTIONAL(inlinedAt, MDField, );
3389 #undef VISIT_MD_FIELDS
3391 Result = GET_OR_DISTINCT(
3392 MDLocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3396 /// ParseGenericDebugNode:
3397 /// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3398 bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3399 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3400 REQUIRED(tag, DwarfTagField, ); \
3401 OPTIONAL(header, MDStringField, ); \
3402 OPTIONAL(operands, MDFieldList, );
3404 #undef VISIT_MD_FIELDS
3406 Result = GET_OR_DISTINCT(GenericDebugNode,
3407 (Context, tag.Val, header.Val, operands.Val));
3411 /// ParseMDSubrange:
3412 /// ::= !MDSubrange(count: 30, lowerBound: 2)
3413 bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
3414 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3415 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3416 OPTIONAL(lowerBound, MDSignedField, );
3418 #undef VISIT_MD_FIELDS
3420 Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3424 /// ParseMDEnumerator:
3425 /// ::= !MDEnumerator(value: 30, name: "SomeKind")
3426 bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
3427 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3428 REQUIRED(name, MDStringField, ); \
3429 REQUIRED(value, MDSignedField, );
3431 #undef VISIT_MD_FIELDS
3433 Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3437 /// ParseMDBasicType:
3438 /// ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3439 bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
3440 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3441 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3442 OPTIONAL(name, MDStringField, ); \
3443 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3444 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3445 OPTIONAL(encoding, DwarfAttEncodingField, );
3447 #undef VISIT_MD_FIELDS
3449 Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3450 align.Val, encoding.Val));
3454 /// ParseMDDerivedType:
3455 /// ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3456 /// line: 7, scope: !1, baseType: !2, size: 32,
3457 /// align: 32, offset: 0, flags: 0, extraData: !3)
3458 bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
3459 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3460 REQUIRED(tag, DwarfTagField, ); \
3461 OPTIONAL(name, MDStringField, ); \
3462 OPTIONAL(file, MDField, ); \
3463 OPTIONAL(line, LineField, ); \
3464 OPTIONAL(scope, MDField, ); \
3465 REQUIRED(baseType, MDField, ); \
3466 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3467 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3468 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3469 OPTIONAL(flags, DIFlagField, ); \
3470 OPTIONAL(extraData, MDField, );
3472 #undef VISIT_MD_FIELDS
3474 Result = GET_OR_DISTINCT(MDDerivedType,
3475 (Context, tag.Val, name.Val, file.Val, line.Val,
3476 scope.Val, baseType.Val, size.Val, align.Val,
3477 offset.Val, flags.Val, extraData.Val));
3481 bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
3482 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3483 REQUIRED(tag, DwarfTagField, ); \
3484 OPTIONAL(name, MDStringField, ); \
3485 OPTIONAL(file, MDField, ); \
3486 OPTIONAL(line, LineField, ); \
3487 OPTIONAL(scope, MDField, ); \
3488 OPTIONAL(baseType, MDField, ); \
3489 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3490 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3491 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3492 OPTIONAL(flags, DIFlagField, ); \
3493 OPTIONAL(elements, MDField, ); \
3494 OPTIONAL(runtimeLang, DwarfLangField, ); \
3495 OPTIONAL(vtableHolder, MDField, ); \
3496 OPTIONAL(templateParams, MDField, ); \
3497 OPTIONAL(identifier, MDStringField, );
3499 #undef VISIT_MD_FIELDS
3501 Result = GET_OR_DISTINCT(
3503 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3504 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3505 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3509 bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
3510 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3511 OPTIONAL(flags, DIFlagField, ); \
3512 REQUIRED(types, MDField, );
3514 #undef VISIT_MD_FIELDS
3516 Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3520 /// ParseMDFileType:
3521 /// ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
3522 bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
3523 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3524 REQUIRED(filename, MDStringField, ); \
3525 REQUIRED(directory, MDStringField, );
3527 #undef VISIT_MD_FIELDS
3529 Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3533 /// ParseMDCompileUnit:
3534 /// ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3535 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3536 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3537 /// enums: !1, retainedTypes: !2, subprograms: !3,
3538 /// globals: !4, imports: !5)
3539 bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
3540 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3541 REQUIRED(language, DwarfLangField, ); \
3542 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3543 OPTIONAL(producer, MDStringField, ); \
3544 OPTIONAL(isOptimized, MDBoolField, ); \
3545 OPTIONAL(flags, MDStringField, ); \
3546 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3547 OPTIONAL(splitDebugFilename, MDStringField, ); \
3548 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3549 OPTIONAL(enums, MDField, ); \
3550 OPTIONAL(retainedTypes, MDField, ); \
3551 OPTIONAL(subprograms, MDField, ); \
3552 OPTIONAL(globals, MDField, ); \
3553 OPTIONAL(imports, MDField, );
3555 #undef VISIT_MD_FIELDS
3557 Result = GET_OR_DISTINCT(MDCompileUnit,
3558 (Context, language.Val, file.Val, producer.Val,
3559 isOptimized.Val, flags.Val, runtimeVersion.Val,
3560 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3561 retainedTypes.Val, subprograms.Val, globals.Val,
3566 /// ParseMDSubprogram:
3567 /// ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3568 /// file: !1, line: 7, type: !2, isLocal: false,
3569 /// isDefinition: true, scopeLine: 8, containingType: !3,
3570 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3571 /// virtualIndex: 10, flags: 11,
3572 /// isOptimized: false, function: void ()* @_Z3foov,
3573 /// templateParams: !4, declaration: !5, variables: !6)
3574 bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
3575 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3576 OPTIONAL(scope, MDField, ); \
3577 OPTIONAL(name, MDStringField, ); \
3578 OPTIONAL(linkageName, MDStringField, ); \
3579 OPTIONAL(file, MDField, ); \
3580 OPTIONAL(line, LineField, ); \
3581 OPTIONAL(type, MDField, ); \
3582 OPTIONAL(isLocal, MDBoolField, ); \
3583 OPTIONAL(isDefinition, MDBoolField, (true)); \
3584 OPTIONAL(scopeLine, LineField, ); \
3585 OPTIONAL(containingType, MDField, ); \
3586 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3587 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3588 OPTIONAL(flags, DIFlagField, ); \
3589 OPTIONAL(isOptimized, MDBoolField, ); \
3590 OPTIONAL(function, MDConstant, ); \
3591 OPTIONAL(templateParams, MDField, ); \
3592 OPTIONAL(declaration, MDField, ); \
3593 OPTIONAL(variables, MDField, );
3595 #undef VISIT_MD_FIELDS
3597 Result = GET_OR_DISTINCT(
3598 MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3599 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3600 scopeLine.Val, containingType.Val, virtuality.Val,
3601 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3602 templateParams.Val, declaration.Val, variables.Val));
3606 /// ParseMDLexicalBlock:
3607 /// ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3608 bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
3609 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3610 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3611 OPTIONAL(file, MDField, ); \
3612 OPTIONAL(line, LineField, ); \
3613 OPTIONAL(column, ColumnField, );
3615 #undef VISIT_MD_FIELDS
3617 Result = GET_OR_DISTINCT(
3618 MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3622 /// ParseMDLexicalBlockFile:
3623 /// ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3624 bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3625 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3626 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3627 OPTIONAL(file, MDField, ); \
3628 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3630 #undef VISIT_MD_FIELDS
3632 Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3633 (Context, scope.Val, file.Val, discriminator.Val));
3637 /// ParseMDNamespace:
3638 /// ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3639 bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
3640 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3641 REQUIRED(scope, MDField, ); \
3642 OPTIONAL(file, MDField, ); \
3643 OPTIONAL(name, MDStringField, ); \
3644 OPTIONAL(line, LineField, );
3646 #undef VISIT_MD_FIELDS
3648 Result = GET_OR_DISTINCT(MDNamespace,
3649 (Context, scope.Val, file.Val, name.Val, line.Val));
3653 /// ParseMDTemplateTypeParameter:
3654 /// ::= !MDTemplateTypeParameter(name: "Ty", type: !1)
3655 bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3656 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3657 OPTIONAL(name, MDStringField, ); \
3658 REQUIRED(type, MDField, );
3660 #undef VISIT_MD_FIELDS
3663 GET_OR_DISTINCT(MDTemplateTypeParameter, (Context, name.Val, type.Val));
3667 /// ParseMDTemplateValueParameter:
3668 /// ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
3669 /// name: "V", type: !1, value: i32 7)
3670 bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3671 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3672 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3673 OPTIONAL(name, MDStringField, ); \
3674 OPTIONAL(type, MDField, ); \
3675 REQUIRED(value, MDField, );
3677 #undef VISIT_MD_FIELDS
3679 Result = GET_OR_DISTINCT(MDTemplateValueParameter,
3680 (Context, tag.Val, name.Val, type.Val, value.Val));
3684 /// ParseMDGlobalVariable:
3685 /// ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3686 /// file: !1, line: 7, type: !2, isLocal: false,
3687 /// isDefinition: true, variable: i32* @foo,
3688 /// declaration: !3)
3689 bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
3690 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3691 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3692 OPTIONAL(scope, MDField, ); \
3693 OPTIONAL(linkageName, MDStringField, ); \
3694 OPTIONAL(file, MDField, ); \
3695 OPTIONAL(line, LineField, ); \
3696 OPTIONAL(type, MDField, ); \
3697 OPTIONAL(isLocal, MDBoolField, ); \
3698 OPTIONAL(isDefinition, MDBoolField, (true)); \
3699 OPTIONAL(variable, MDConstant, ); \
3700 OPTIONAL(declaration, MDField, );
3702 #undef VISIT_MD_FIELDS
3704 Result = GET_OR_DISTINCT(MDGlobalVariable,
3705 (Context, scope.Val, name.Val, linkageName.Val,
3706 file.Val, line.Val, type.Val, isLocal.Val,
3707 isDefinition.Val, variable.Val, declaration.Val));
3711 /// ParseMDLocalVariable:
3712 /// ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3713 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3714 bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
3715 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3716 REQUIRED(tag, DwarfTagField, ); \
3717 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3718 OPTIONAL(name, MDStringField, ); \
3719 OPTIONAL(file, MDField, ); \
3720 OPTIONAL(line, LineField, ); \
3721 OPTIONAL(type, MDField, ); \
3722 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
3723 OPTIONAL(flags, DIFlagField, );
3725 #undef VISIT_MD_FIELDS
3727 Result = GET_OR_DISTINCT(MDLocalVariable,
3728 (Context, tag.Val, scope.Val, name.Val, file.Val,
3729 line.Val, type.Val, arg.Val, flags.Val));
3733 /// ParseMDExpression:
3734 /// ::= !MDExpression(0, 7, -1)
3735 bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
3736 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3739 if (ParseToken(lltok::lparen, "expected '(' here"))
3742 SmallVector<uint64_t, 8> Elements;
3743 if (Lex.getKind() != lltok::rparen)
3745 if (Lex.getKind() == lltok::DwarfOp) {
3746 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3748 Elements.push_back(Op);
3751 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3754 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3755 return TokError("expected unsigned integer");
3757 auto &U = Lex.getAPSIntVal();
3758 if (U.ugt(UINT64_MAX))
3759 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3760 Elements.push_back(U.getZExtValue());
3762 } while (EatIfPresent(lltok::comma));
3764 if (ParseToken(lltok::rparen, "expected ')' here"))
3767 Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3771 /// ParseMDObjCProperty:
3772 /// ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3773 /// getter: "getFoo", attributes: 7, type: !2)
3774 bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
3775 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3776 OPTIONAL(name, MDStringField, ); \
3777 OPTIONAL(file, MDField, ); \
3778 OPTIONAL(line, LineField, ); \
3779 OPTIONAL(setter, MDStringField, ); \
3780 OPTIONAL(getter, MDStringField, ); \
3781 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3782 OPTIONAL(type, MDField, );
3784 #undef VISIT_MD_FIELDS
3786 Result = GET_OR_DISTINCT(MDObjCProperty,
3787 (Context, name.Val, file.Val, line.Val, setter.Val,
3788 getter.Val, attributes.Val, type.Val));
3792 /// ParseMDImportedEntity:
3793 /// ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3794 /// line: 7, name: "foo")
3795 bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
3796 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3797 REQUIRED(tag, DwarfTagField, ); \
3798 REQUIRED(scope, MDField, ); \
3799 OPTIONAL(entity, MDField, ); \
3800 OPTIONAL(line, LineField, ); \
3801 OPTIONAL(name, MDStringField, );
3803 #undef VISIT_MD_FIELDS
3805 Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3806 entity.Val, line.Val, name.Val));
3810 #undef PARSE_MD_FIELD
3812 #undef REQUIRE_FIELD
3813 #undef DECLARE_FIELD
3815 /// ParseMetadataAsValue
3816 /// ::= metadata i32 %local
3817 /// ::= metadata i32 @global
3818 /// ::= metadata i32 7
3820 /// ::= metadata !{...}
3821 /// ::= metadata !"string"
3822 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3823 // Note: the type 'metadata' has already been parsed.
3825 if (ParseMetadata(MD, &PFS))
3828 V = MetadataAsValue::get(Context, MD);
3832 /// ParseValueAsMetadata
3836 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3837 PerFunctionState *PFS) {
3840 if (ParseType(Ty, TypeMsg, Loc))
3842 if (Ty->isMetadataTy())
3843 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3846 if (ParseValue(Ty, V, PFS))
3849 MD = ValueAsMetadata::get(V);
3860 /// ::= !MDLocation(...)
3861 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3862 if (Lex.getKind() == lltok::MetadataVar) {
3864 if (ParseSpecializedMDNode(N))
3872 if (Lex.getKind() != lltok::exclaim)
3873 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3876 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3880 // ::= '!' STRINGCONSTANT
3881 if (Lex.getKind() == lltok::StringConstant) {
3883 if (ParseMDString(S))
3893 if (ParseMDNodeTail(N))
3900 //===----------------------------------------------------------------------===//
3901 // Function Parsing.
3902 //===----------------------------------------------------------------------===//
3904 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3905 PerFunctionState *PFS) {
3906 if (Ty->isFunctionTy())
3907 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3910 case ValID::t_LocalID:
3911 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3912 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3913 return V == nullptr;
3914 case ValID::t_LocalName:
3915 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3916 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3917 return V == nullptr;
3918 case ValID::t_InlineAsm: {
3919 PointerType *PTy = dyn_cast<PointerType>(Ty);
3921 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3922 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3923 return Error(ID.Loc, "invalid type for inline asm constraint string");
3924 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3925 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3928 case ValID::t_GlobalName:
3929 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3930 return V == nullptr;
3931 case ValID::t_GlobalID:
3932 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3933 return V == nullptr;
3934 case ValID::t_APSInt:
3935 if (!Ty->isIntegerTy())
3936 return Error(ID.Loc, "integer constant must have integer type");
3937 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3938 V = ConstantInt::get(Context, ID.APSIntVal);
3940 case ValID::t_APFloat:
3941 if (!Ty->isFloatingPointTy() ||
3942 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3943 return Error(ID.Loc, "floating point constant invalid for type");
3945 // The lexer has no type info, so builds all half, float, and double FP
3946 // constants as double. Fix this here. Long double does not need this.
3947 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3950 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3952 else if (Ty->isFloatTy())
3953 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3956 V = ConstantFP::get(Context, ID.APFloatVal);
3958 if (V->getType() != Ty)
3959 return Error(ID.Loc, "floating point constant does not have type '" +
3960 getTypeString(Ty) + "'");
3964 if (!Ty->isPointerTy())
3965 return Error(ID.Loc, "null must be a pointer type");
3966 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3968 case ValID::t_Undef:
3969 // FIXME: LabelTy should not be a first-class type.
3970 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3971 return Error(ID.Loc, "invalid type for undef constant");
3972 V = UndefValue::get(Ty);
3974 case ValID::t_EmptyArray:
3975 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3976 return Error(ID.Loc, "invalid empty array initializer");
3977 V = UndefValue::get(Ty);
3980 // FIXME: LabelTy should not be a first-class type.
3981 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3982 return Error(ID.Loc, "invalid type for null constant");
3983 V = Constant::getNullValue(Ty);
3985 case ValID::t_Constant:
3986 if (ID.ConstantVal->getType() != Ty)
3987 return Error(ID.Loc, "constant expression type mismatch");
3991 case ValID::t_ConstantStruct:
3992 case ValID::t_PackedConstantStruct:
3993 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3994 if (ST->getNumElements() != ID.UIntVal)
3995 return Error(ID.Loc,
3996 "initializer with struct type has wrong # elements");
3997 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3998 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4000 // Verify that the elements are compatible with the structtype.
4001 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4002 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4003 return Error(ID.Loc, "element " + Twine(i) +
4004 " of struct initializer doesn't match struct element type");
4006 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4009 return Error(ID.Loc, "constant expression type mismatch");
4012 llvm_unreachable("Invalid ValID");
4015 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4018 return ParseValID(ID, PFS) ||
4019 ConvertValIDToValue(Ty, ID, V, PFS);
4022 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4024 return ParseType(Ty) ||
4025 ParseValue(Ty, V, PFS);
4028 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4029 PerFunctionState &PFS) {
4032 if (ParseTypeAndValue(V, PFS)) return true;
4033 if (!isa<BasicBlock>(V))
4034 return Error(Loc, "expected a basic block");
4035 BB = cast<BasicBlock>(V);
4041 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4042 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4043 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
4044 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4045 // Parse the linkage.
4046 LocTy LinkageLoc = Lex.getLoc();
4049 unsigned Visibility;
4050 unsigned DLLStorageClass;
4051 AttrBuilder RetAttrs;
4053 Type *RetType = nullptr;
4054 LocTy RetTypeLoc = Lex.getLoc();
4055 if (ParseOptionalLinkage(Linkage) ||
4056 ParseOptionalVisibility(Visibility) ||
4057 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4058 ParseOptionalCallingConv(CC) ||
4059 ParseOptionalReturnAttrs(RetAttrs) ||
4060 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4063 // Verify that the linkage is ok.
4064 switch ((GlobalValue::LinkageTypes)Linkage) {
4065 case GlobalValue::ExternalLinkage:
4066 break; // always ok.
4067 case GlobalValue::ExternalWeakLinkage:
4069 return Error(LinkageLoc, "invalid linkage for function definition");
4071 case GlobalValue::PrivateLinkage:
4072 case GlobalValue::InternalLinkage:
4073 case GlobalValue::AvailableExternallyLinkage:
4074 case GlobalValue::LinkOnceAnyLinkage:
4075 case GlobalValue::LinkOnceODRLinkage:
4076 case GlobalValue::WeakAnyLinkage:
4077 case GlobalValue::WeakODRLinkage:
4079 return Error(LinkageLoc, "invalid linkage for function declaration");
4081 case GlobalValue::AppendingLinkage:
4082 case GlobalValue::CommonLinkage:
4083 return Error(LinkageLoc, "invalid function linkage type");
4086 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4087 return Error(LinkageLoc,
4088 "symbol with local linkage must have default visibility");
4090 if (!FunctionType::isValidReturnType(RetType))
4091 return Error(RetTypeLoc, "invalid function return type");
4093 LocTy NameLoc = Lex.getLoc();
4095 std::string FunctionName;
4096 if (Lex.getKind() == lltok::GlobalVar) {
4097 FunctionName = Lex.getStrVal();
4098 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4099 unsigned NameID = Lex.getUIntVal();
4101 if (NameID != NumberedVals.size())
4102 return TokError("function expected to be numbered '%" +
4103 Twine(NumberedVals.size()) + "'");
4105 return TokError("expected function name");
4110 if (Lex.getKind() != lltok::lparen)
4111 return TokError("expected '(' in function argument list");
4113 SmallVector<ArgInfo, 8> ArgList;
4115 AttrBuilder FuncAttrs;
4116 std::vector<unsigned> FwdRefAttrGrps;
4118 std::string Section;
4122 LocTy UnnamedAddrLoc;
4123 Constant *Prefix = nullptr;
4124 Constant *Prologue = nullptr;
4127 if (ParseArgumentList(ArgList, isVarArg) ||
4128 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4130 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4132 (EatIfPresent(lltok::kw_section) &&
4133 ParseStringConstant(Section)) ||
4134 parseOptionalComdat(FunctionName, C) ||
4135 ParseOptionalAlignment(Alignment) ||
4136 (EatIfPresent(lltok::kw_gc) &&
4137 ParseStringConstant(GC)) ||
4138 (EatIfPresent(lltok::kw_prefix) &&
4139 ParseGlobalTypeAndValue(Prefix)) ||
4140 (EatIfPresent(lltok::kw_prologue) &&
4141 ParseGlobalTypeAndValue(Prologue)))
4144 if (FuncAttrs.contains(Attribute::Builtin))
4145 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4147 // If the alignment was parsed as an attribute, move to the alignment field.
4148 if (FuncAttrs.hasAlignmentAttr()) {
4149 Alignment = FuncAttrs.getAlignment();
4150 FuncAttrs.removeAttribute(Attribute::Alignment);
4153 // Okay, if we got here, the function is syntactically valid. Convert types
4154 // and do semantic checks.
4155 std::vector<Type*> ParamTypeList;
4156 SmallVector<AttributeSet, 8> Attrs;
4158 if (RetAttrs.hasAttributes())
4159 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4160 AttributeSet::ReturnIndex,
4163 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4164 ParamTypeList.push_back(ArgList[i].Ty);
4165 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4166 AttrBuilder B(ArgList[i].Attrs, i + 1);
4167 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4171 if (FuncAttrs.hasAttributes())
4172 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4173 AttributeSet::FunctionIndex,
4176 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4178 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4179 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4182 FunctionType::get(RetType, ParamTypeList, isVarArg);
4183 PointerType *PFT = PointerType::getUnqual(FT);
4186 if (!FunctionName.empty()) {
4187 // If this was a definition of a forward reference, remove the definition
4188 // from the forward reference table and fill in the forward ref.
4189 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4190 ForwardRefVals.find(FunctionName);
4191 if (FRVI != ForwardRefVals.end()) {
4192 Fn = M->getFunction(FunctionName);
4194 return Error(FRVI->second.second, "invalid forward reference to "
4195 "function as global value!");
4196 if (Fn->getType() != PFT)
4197 return Error(FRVI->second.second, "invalid forward reference to "
4198 "function '" + FunctionName + "' with wrong type!");
4200 ForwardRefVals.erase(FRVI);
4201 } else if ((Fn = M->getFunction(FunctionName))) {
4202 // Reject redefinitions.
4203 return Error(NameLoc, "invalid redefinition of function '" +
4204 FunctionName + "'");
4205 } else if (M->getNamedValue(FunctionName)) {
4206 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4210 // If this is a definition of a forward referenced function, make sure the
4212 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4213 = ForwardRefValIDs.find(NumberedVals.size());
4214 if (I != ForwardRefValIDs.end()) {
4215 Fn = cast<Function>(I->second.first);
4216 if (Fn->getType() != PFT)
4217 return Error(NameLoc, "type of definition and forward reference of '@" +
4218 Twine(NumberedVals.size()) + "' disagree");
4219 ForwardRefValIDs.erase(I);
4224 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4225 else // Move the forward-reference to the correct spot in the module.
4226 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4228 if (FunctionName.empty())
4229 NumberedVals.push_back(Fn);
4231 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4232 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4233 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4234 Fn->setCallingConv(CC);
4235 Fn->setAttributes(PAL);
4236 Fn->setUnnamedAddr(UnnamedAddr);
4237 Fn->setAlignment(Alignment);
4238 Fn->setSection(Section);
4240 if (!GC.empty()) Fn->setGC(GC.c_str());
4241 Fn->setPrefixData(Prefix);
4242 Fn->setPrologueData(Prologue);
4243 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4245 // Add all of the arguments we parsed to the function.
4246 Function::arg_iterator ArgIt = Fn->arg_begin();
4247 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4248 // If the argument has a name, insert it into the argument symbol table.
4249 if (ArgList[i].Name.empty()) continue;
4251 // Set the name, if it conflicted, it will be auto-renamed.
4252 ArgIt->setName(ArgList[i].Name);
4254 if (ArgIt->getName() != ArgList[i].Name)
4255 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4256 ArgList[i].Name + "'");
4262 // Check the declaration has no block address forward references.
4264 if (FunctionName.empty()) {
4265 ID.Kind = ValID::t_GlobalID;
4266 ID.UIntVal = NumberedVals.size() - 1;
4268 ID.Kind = ValID::t_GlobalName;
4269 ID.StrVal = FunctionName;
4271 auto Blocks = ForwardRefBlockAddresses.find(ID);
4272 if (Blocks != ForwardRefBlockAddresses.end())
4273 return Error(Blocks->first.Loc,
4274 "cannot take blockaddress inside a declaration");
4278 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4280 if (FunctionNumber == -1) {
4281 ID.Kind = ValID::t_GlobalName;
4282 ID.StrVal = F.getName();
4284 ID.Kind = ValID::t_GlobalID;
4285 ID.UIntVal = FunctionNumber;
4288 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4289 if (Blocks == P.ForwardRefBlockAddresses.end())
4292 for (const auto &I : Blocks->second) {
4293 const ValID &BBID = I.first;
4294 GlobalValue *GV = I.second;
4296 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4297 "Expected local id or name");
4299 if (BBID.Kind == ValID::t_LocalName)
4300 BB = GetBB(BBID.StrVal, BBID.Loc);
4302 BB = GetBB(BBID.UIntVal, BBID.Loc);
4304 return P.Error(BBID.Loc, "referenced value is not a basic block");
4306 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4307 GV->eraseFromParent();
4310 P.ForwardRefBlockAddresses.erase(Blocks);
4314 /// ParseFunctionBody
4315 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4316 bool LLParser::ParseFunctionBody(Function &Fn) {
4317 if (Lex.getKind() != lltok::lbrace)
4318 return TokError("expected '{' in function body");
4319 Lex.Lex(); // eat the {.
4321 int FunctionNumber = -1;
4322 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4324 PerFunctionState PFS(*this, Fn, FunctionNumber);
4326 // Resolve block addresses and allow basic blocks to be forward-declared
4327 // within this function.
4328 if (PFS.resolveForwardRefBlockAddresses())
4330 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4332 // We need at least one basic block.
4333 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4334 return TokError("function body requires at least one basic block");
4336 while (Lex.getKind() != lltok::rbrace &&
4337 Lex.getKind() != lltok::kw_uselistorder)
4338 if (ParseBasicBlock(PFS)) return true;
4340 while (Lex.getKind() != lltok::rbrace)
4341 if (ParseUseListOrder(&PFS))
4347 // Verify function is ok.
4348 return PFS.FinishFunction();
4352 /// ::= LabelStr? Instruction*
4353 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4354 // If this basic block starts out with a name, remember it.
4356 LocTy NameLoc = Lex.getLoc();
4357 if (Lex.getKind() == lltok::LabelStr) {
4358 Name = Lex.getStrVal();
4362 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4364 return Error(NameLoc,
4365 "unable to create block named '" + Name + "'");
4367 std::string NameStr;
4369 // Parse the instructions in this block until we get a terminator.
4372 // This instruction may have three possibilities for a name: a) none
4373 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4374 LocTy NameLoc = Lex.getLoc();
4378 if (Lex.getKind() == lltok::LocalVarID) {
4379 NameID = Lex.getUIntVal();
4381 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4383 } else if (Lex.getKind() == lltok::LocalVar) {
4384 NameStr = Lex.getStrVal();
4386 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4390 switch (ParseInstruction(Inst, BB, PFS)) {
4391 default: llvm_unreachable("Unknown ParseInstruction result!");
4392 case InstError: return true;
4394 BB->getInstList().push_back(Inst);
4396 // With a normal result, we check to see if the instruction is followed by
4397 // a comma and metadata.
4398 if (EatIfPresent(lltok::comma))
4399 if (ParseInstructionMetadata(Inst, &PFS))
4402 case InstExtraComma:
4403 BB->getInstList().push_back(Inst);
4405 // If the instruction parser ate an extra comma at the end of it, it
4406 // *must* be followed by metadata.
4407 if (ParseInstructionMetadata(Inst, &PFS))
4412 // Set the name on the instruction.
4413 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4414 } while (!isa<TerminatorInst>(Inst));
4419 //===----------------------------------------------------------------------===//
4420 // Instruction Parsing.
4421 //===----------------------------------------------------------------------===//
4423 /// ParseInstruction - Parse one of the many different instructions.
4425 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4426 PerFunctionState &PFS) {
4427 lltok::Kind Token = Lex.getKind();
4428 if (Token == lltok::Eof)
4429 return TokError("found end of file when expecting more instructions");
4430 LocTy Loc = Lex.getLoc();
4431 unsigned KeywordVal = Lex.getUIntVal();
4432 Lex.Lex(); // Eat the keyword.
4435 default: return Error(Loc, "expected instruction opcode");
4436 // Terminator Instructions.
4437 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4438 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4439 case lltok::kw_br: return ParseBr(Inst, PFS);
4440 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4441 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4442 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4443 case lltok::kw_resume: return ParseResume(Inst, PFS);
4444 // Binary Operators.
4448 case lltok::kw_shl: {
4449 bool NUW = EatIfPresent(lltok::kw_nuw);
4450 bool NSW = EatIfPresent(lltok::kw_nsw);
4451 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4453 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4455 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4456 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4459 case lltok::kw_fadd:
4460 case lltok::kw_fsub:
4461 case lltok::kw_fmul:
4462 case lltok::kw_fdiv:
4463 case lltok::kw_frem: {
4464 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4465 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4469 Inst->setFastMathFlags(FMF);
4473 case lltok::kw_sdiv:
4474 case lltok::kw_udiv:
4475 case lltok::kw_lshr:
4476 case lltok::kw_ashr: {
4477 bool Exact = EatIfPresent(lltok::kw_exact);
4479 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4480 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4484 case lltok::kw_urem:
4485 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4488 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4489 case lltok::kw_icmp:
4490 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
4492 case lltok::kw_trunc:
4493 case lltok::kw_zext:
4494 case lltok::kw_sext:
4495 case lltok::kw_fptrunc:
4496 case lltok::kw_fpext:
4497 case lltok::kw_bitcast:
4498 case lltok::kw_addrspacecast:
4499 case lltok::kw_uitofp:
4500 case lltok::kw_sitofp:
4501 case lltok::kw_fptoui:
4502 case lltok::kw_fptosi:
4503 case lltok::kw_inttoptr:
4504 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4506 case lltok::kw_select: return ParseSelect(Inst, PFS);
4507 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4508 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4509 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4510 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4511 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4512 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4514 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4515 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4516 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4518 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4519 case lltok::kw_load: return ParseLoad(Inst, PFS);
4520 case lltok::kw_store: return ParseStore(Inst, PFS);
4521 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4522 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4523 case lltok::kw_fence: return ParseFence(Inst, PFS);
4524 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4525 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4526 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4530 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4531 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4532 if (Opc == Instruction::FCmp) {
4533 switch (Lex.getKind()) {
4534 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4535 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4536 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4537 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4538 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4539 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4540 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4541 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4542 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4543 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4544 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4545 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4546 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4547 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4548 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4549 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4550 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4553 switch (Lex.getKind()) {
4554 default: return TokError("expected icmp predicate (e.g. 'eq')");
4555 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4556 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4557 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4558 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4559 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4560 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4561 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4562 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4563 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4564 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4571 //===----------------------------------------------------------------------===//
4572 // Terminator Instructions.
4573 //===----------------------------------------------------------------------===//
4575 /// ParseRet - Parse a return instruction.
4576 /// ::= 'ret' void (',' !dbg, !1)*
4577 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4578 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4579 PerFunctionState &PFS) {
4580 SMLoc TypeLoc = Lex.getLoc();
4582 if (ParseType(Ty, true /*void allowed*/)) return true;
4584 Type *ResType = PFS.getFunction().getReturnType();
4586 if (Ty->isVoidTy()) {
4587 if (!ResType->isVoidTy())
4588 return Error(TypeLoc, "value doesn't match function result type '" +
4589 getTypeString(ResType) + "'");
4591 Inst = ReturnInst::Create(Context);
4596 if (ParseValue(Ty, RV, PFS)) return true;
4598 if (ResType != RV->getType())
4599 return Error(TypeLoc, "value doesn't match function result type '" +
4600 getTypeString(ResType) + "'");
4602 Inst = ReturnInst::Create(Context, RV);
4608 /// ::= 'br' TypeAndValue
4609 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4610 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4613 BasicBlock *Op1, *Op2;
4614 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4616 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4617 Inst = BranchInst::Create(BB);
4621 if (Op0->getType() != Type::getInt1Ty(Context))
4622 return Error(Loc, "branch condition must have 'i1' type");
4624 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4625 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4626 ParseToken(lltok::comma, "expected ',' after true destination") ||
4627 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4630 Inst = BranchInst::Create(Op1, Op2, Op0);
4636 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4638 /// ::= (TypeAndValue ',' TypeAndValue)*
4639 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4640 LocTy CondLoc, BBLoc;
4642 BasicBlock *DefaultBB;
4643 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4644 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4645 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4646 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4649 if (!Cond->getType()->isIntegerTy())
4650 return Error(CondLoc, "switch condition must have integer type");
4652 // Parse the jump table pairs.
4653 SmallPtrSet<Value*, 32> SeenCases;
4654 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4655 while (Lex.getKind() != lltok::rsquare) {
4659 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4660 ParseToken(lltok::comma, "expected ',' after case value") ||
4661 ParseTypeAndBasicBlock(DestBB, PFS))
4664 if (!SeenCases.insert(Constant).second)
4665 return Error(CondLoc, "duplicate case value in switch");
4666 if (!isa<ConstantInt>(Constant))
4667 return Error(CondLoc, "case value is not a constant integer");
4669 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4672 Lex.Lex(); // Eat the ']'.
4674 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4675 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4676 SI->addCase(Table[i].first, Table[i].second);
4683 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4684 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4687 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4688 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4689 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4692 if (!Address->getType()->isPointerTy())
4693 return Error(AddrLoc, "indirectbr address must have pointer type");
4695 // Parse the destination list.
4696 SmallVector<BasicBlock*, 16> DestList;
4698 if (Lex.getKind() != lltok::rsquare) {
4700 if (ParseTypeAndBasicBlock(DestBB, PFS))
4702 DestList.push_back(DestBB);
4704 while (EatIfPresent(lltok::comma)) {
4705 if (ParseTypeAndBasicBlock(DestBB, PFS))
4707 DestList.push_back(DestBB);
4711 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4714 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4715 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4716 IBI->addDestination(DestList[i]);
4723 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4724 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4725 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4726 LocTy CallLoc = Lex.getLoc();
4727 AttrBuilder RetAttrs, FnAttrs;
4728 std::vector<unsigned> FwdRefAttrGrps;
4731 Type *RetType = nullptr;
4734 SmallVector<ParamInfo, 16> ArgList;
4736 BasicBlock *NormalBB, *UnwindBB;
4737 if (ParseOptionalCallingConv(CC) ||
4738 ParseOptionalReturnAttrs(RetAttrs) ||
4739 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4740 ParseValID(CalleeID) ||
4741 ParseParameterList(ArgList, PFS) ||
4742 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4744 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4745 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4746 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4747 ParseTypeAndBasicBlock(UnwindBB, PFS))
4750 // If RetType is a non-function pointer type, then this is the short syntax
4751 // for the call, which means that RetType is just the return type. Infer the
4752 // rest of the function argument types from the arguments that are present.
4753 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4755 // Pull out the types of all of the arguments...
4756 std::vector<Type*> ParamTypes;
4757 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4758 ParamTypes.push_back(ArgList[i].V->getType());
4760 if (!FunctionType::isValidReturnType(RetType))
4761 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4763 Ty = FunctionType::get(RetType, ParamTypes, false);
4766 // Look up the callee.
4768 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4771 // Set up the Attribute for the function.
4772 SmallVector<AttributeSet, 8> Attrs;
4773 if (RetAttrs.hasAttributes())
4774 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4775 AttributeSet::ReturnIndex,
4778 SmallVector<Value*, 8> Args;
4780 // Loop through FunctionType's arguments and ensure they are specified
4781 // correctly. Also, gather any parameter attributes.
4782 FunctionType::param_iterator I = Ty->param_begin();
4783 FunctionType::param_iterator E = Ty->param_end();
4784 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4785 Type *ExpectedTy = nullptr;
4788 } else if (!Ty->isVarArg()) {
4789 return Error(ArgList[i].Loc, "too many arguments specified");
4792 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4793 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4794 getTypeString(ExpectedTy) + "'");
4795 Args.push_back(ArgList[i].V);
4796 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4797 AttrBuilder B(ArgList[i].Attrs, i + 1);
4798 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4803 return Error(CallLoc, "not enough parameters specified for call");
4805 if (FnAttrs.hasAttributes()) {
4806 if (FnAttrs.hasAlignmentAttr())
4807 return Error(CallLoc, "invoke instructions may not have an alignment");
4809 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4810 AttributeSet::FunctionIndex,
4814 // Finish off the Attribute and check them
4815 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4817 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4818 II->setCallingConv(CC);
4819 II->setAttributes(PAL);
4820 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4826 /// ::= 'resume' TypeAndValue
4827 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4828 Value *Exn; LocTy ExnLoc;
4829 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4832 ResumeInst *RI = ResumeInst::Create(Exn);
4837 //===----------------------------------------------------------------------===//
4838 // Binary Operators.
4839 //===----------------------------------------------------------------------===//
4842 /// ::= ArithmeticOps TypeAndValue ',' Value
4844 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4845 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4846 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4847 unsigned Opc, unsigned OperandType) {
4848 LocTy Loc; Value *LHS, *RHS;
4849 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4850 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4851 ParseValue(LHS->getType(), RHS, PFS))
4855 switch (OperandType) {
4856 default: llvm_unreachable("Unknown operand type!");
4857 case 0: // int or FP.
4858 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4859 LHS->getType()->isFPOrFPVectorTy();
4861 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4862 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4866 return Error(Loc, "invalid operand type for instruction");
4868 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4873 /// ::= ArithmeticOps TypeAndValue ',' Value {
4874 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4876 LocTy Loc; Value *LHS, *RHS;
4877 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4878 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4879 ParseValue(LHS->getType(), RHS, PFS))
4882 if (!LHS->getType()->isIntOrIntVectorTy())
4883 return Error(Loc,"instruction requires integer or integer vector operands");
4885 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4891 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4892 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4893 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4895 // Parse the integer/fp comparison predicate.
4899 if (ParseCmpPredicate(Pred, Opc) ||
4900 ParseTypeAndValue(LHS, Loc, PFS) ||
4901 ParseToken(lltok::comma, "expected ',' after compare value") ||
4902 ParseValue(LHS->getType(), RHS, PFS))
4905 if (Opc == Instruction::FCmp) {
4906 if (!LHS->getType()->isFPOrFPVectorTy())
4907 return Error(Loc, "fcmp requires floating point operands");
4908 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4910 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4911 if (!LHS->getType()->isIntOrIntVectorTy() &&
4912 !LHS->getType()->getScalarType()->isPointerTy())
4913 return Error(Loc, "icmp requires integer operands");
4914 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4919 //===----------------------------------------------------------------------===//
4920 // Other Instructions.
4921 //===----------------------------------------------------------------------===//
4925 /// ::= CastOpc TypeAndValue 'to' Type
4926 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4930 Type *DestTy = nullptr;
4931 if (ParseTypeAndValue(Op, Loc, PFS) ||
4932 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4936 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4937 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4938 return Error(Loc, "invalid cast opcode for cast from '" +
4939 getTypeString(Op->getType()) + "' to '" +
4940 getTypeString(DestTy) + "'");
4942 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4947 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4948 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4950 Value *Op0, *Op1, *Op2;
4951 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4952 ParseToken(lltok::comma, "expected ',' after select condition") ||
4953 ParseTypeAndValue(Op1, PFS) ||
4954 ParseToken(lltok::comma, "expected ',' after select value") ||
4955 ParseTypeAndValue(Op2, PFS))
4958 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4959 return Error(Loc, Reason);
4961 Inst = SelectInst::Create(Op0, Op1, Op2);
4966 /// ::= 'va_arg' TypeAndValue ',' Type
4967 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4969 Type *EltTy = nullptr;
4971 if (ParseTypeAndValue(Op, PFS) ||
4972 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4973 ParseType(EltTy, TypeLoc))
4976 if (!EltTy->isFirstClassType())
4977 return Error(TypeLoc, "va_arg requires operand with first class type");
4979 Inst = new VAArgInst(Op, EltTy);
4983 /// ParseExtractElement
4984 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4985 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4988 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4989 ParseToken(lltok::comma, "expected ',' after extract value") ||
4990 ParseTypeAndValue(Op1, PFS))
4993 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4994 return Error(Loc, "invalid extractelement operands");
4996 Inst = ExtractElementInst::Create(Op0, Op1);
5000 /// ParseInsertElement
5001 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5002 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5004 Value *Op0, *Op1, *Op2;
5005 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5006 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5007 ParseTypeAndValue(Op1, PFS) ||
5008 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5009 ParseTypeAndValue(Op2, PFS))
5012 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5013 return Error(Loc, "invalid insertelement operands");
5015 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5019 /// ParseShuffleVector
5020 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5021 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5023 Value *Op0, *Op1, *Op2;
5024 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5025 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5026 ParseTypeAndValue(Op1, PFS) ||
5027 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5028 ParseTypeAndValue(Op2, PFS))
5031 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5032 return Error(Loc, "invalid shufflevector operands");
5034 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5039 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5040 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5041 Type *Ty = nullptr; LocTy TypeLoc;
5044 if (ParseType(Ty, TypeLoc) ||
5045 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5046 ParseValue(Ty, Op0, PFS) ||
5047 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5048 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5049 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5052 bool AteExtraComma = false;
5053 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5055 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5057 if (!EatIfPresent(lltok::comma))
5060 if (Lex.getKind() == lltok::MetadataVar) {
5061 AteExtraComma = true;
5065 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5066 ParseValue(Ty, Op0, PFS) ||
5067 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5068 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5069 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5073 if (!Ty->isFirstClassType())
5074 return Error(TypeLoc, "phi node must have first class type");
5076 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5077 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5078 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5080 return AteExtraComma ? InstExtraComma : InstNormal;
5084 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5086 /// ::= 'catch' TypeAndValue
5088 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5089 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5090 Type *Ty = nullptr; LocTy TyLoc;
5091 Value *PersFn; LocTy PersFnLoc;
5093 if (ParseType(Ty, TyLoc) ||
5094 ParseToken(lltok::kw_personality, "expected 'personality'") ||
5095 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5098 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
5099 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5101 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5102 LandingPadInst::ClauseType CT;
5103 if (EatIfPresent(lltok::kw_catch))
5104 CT = LandingPadInst::Catch;
5105 else if (EatIfPresent(lltok::kw_filter))
5106 CT = LandingPadInst::Filter;
5108 return TokError("expected 'catch' or 'filter' clause type");
5112 if (ParseTypeAndValue(V, VLoc, PFS))
5115 // A 'catch' type expects a non-array constant. A filter clause expects an
5117 if (CT == LandingPadInst::Catch) {
5118 if (isa<ArrayType>(V->getType()))
5119 Error(VLoc, "'catch' clause has an invalid type");
5121 if (!isa<ArrayType>(V->getType()))
5122 Error(VLoc, "'filter' clause has an invalid type");
5125 Constant *CV = dyn_cast<Constant>(V);
5127 return Error(VLoc, "clause argument must be a constant");
5131 Inst = LP.release();
5136 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5137 /// ParameterList OptionalAttrs
5138 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5139 /// ParameterList OptionalAttrs
5140 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5141 /// ParameterList OptionalAttrs
5142 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5143 CallInst::TailCallKind TCK) {
5144 AttrBuilder RetAttrs, FnAttrs;
5145 std::vector<unsigned> FwdRefAttrGrps;
5148 Type *RetType = nullptr;
5151 SmallVector<ParamInfo, 16> ArgList;
5152 LocTy CallLoc = Lex.getLoc();
5154 if ((TCK != CallInst::TCK_None &&
5155 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5156 ParseOptionalCallingConv(CC) ||
5157 ParseOptionalReturnAttrs(RetAttrs) ||
5158 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5159 ParseValID(CalleeID) ||
5160 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5161 PFS.getFunction().isVarArg()) ||
5162 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5166 // If RetType is a non-function pointer type, then this is the short syntax
5167 // for the call, which means that RetType is just the return type. Infer the
5168 // rest of the function argument types from the arguments that are present.
5169 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5171 // Pull out the types of all of the arguments...
5172 std::vector<Type*> ParamTypes;
5173 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5174 ParamTypes.push_back(ArgList[i].V->getType());
5176 if (!FunctionType::isValidReturnType(RetType))
5177 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5179 Ty = FunctionType::get(RetType, ParamTypes, false);
5182 // Look up the callee.
5184 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5187 // Set up the Attribute for the function.
5188 SmallVector<AttributeSet, 8> Attrs;
5189 if (RetAttrs.hasAttributes())
5190 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5191 AttributeSet::ReturnIndex,
5194 SmallVector<Value*, 8> Args;
5196 // Loop through FunctionType's arguments and ensure they are specified
5197 // correctly. Also, gather any parameter attributes.
5198 FunctionType::param_iterator I = Ty->param_begin();
5199 FunctionType::param_iterator E = Ty->param_end();
5200 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5201 Type *ExpectedTy = nullptr;
5204 } else if (!Ty->isVarArg()) {
5205 return Error(ArgList[i].Loc, "too many arguments specified");
5208 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5209 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5210 getTypeString(ExpectedTy) + "'");
5211 Args.push_back(ArgList[i].V);
5212 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5213 AttrBuilder B(ArgList[i].Attrs, i + 1);
5214 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5219 return Error(CallLoc, "not enough parameters specified for call");
5221 if (FnAttrs.hasAttributes()) {
5222 if (FnAttrs.hasAlignmentAttr())
5223 return Error(CallLoc, "call instructions may not have an alignment");
5225 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5226 AttributeSet::FunctionIndex,
5230 // Finish off the Attribute and check them
5231 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5233 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5234 CI->setTailCallKind(TCK);
5235 CI->setCallingConv(CC);
5236 CI->setAttributes(PAL);
5237 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5242 //===----------------------------------------------------------------------===//
5243 // Memory Instructions.
5244 //===----------------------------------------------------------------------===//
5247 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5248 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5249 Value *Size = nullptr;
5250 LocTy SizeLoc, TyLoc;
5251 unsigned Alignment = 0;
5254 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5256 if (ParseType(Ty, TyLoc)) return true;
5258 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5259 return Error(TyLoc, "invalid type for alloca");
5261 bool AteExtraComma = false;
5262 if (EatIfPresent(lltok::comma)) {
5263 if (Lex.getKind() == lltok::kw_align) {
5264 if (ParseOptionalAlignment(Alignment)) return true;
5265 } else if (Lex.getKind() == lltok::MetadataVar) {
5266 AteExtraComma = true;
5268 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5269 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5274 if (Size && !Size->getType()->isIntegerTy())
5275 return Error(SizeLoc, "element count must have integer type");
5277 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5278 AI->setUsedWithInAlloca(IsInAlloca);
5280 return AteExtraComma ? InstExtraComma : InstNormal;
5284 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5285 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5286 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5287 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5288 Value *Val; LocTy Loc;
5289 unsigned Alignment = 0;
5290 bool AteExtraComma = false;
5291 bool isAtomic = false;
5292 AtomicOrdering Ordering = NotAtomic;
5293 SynchronizationScope Scope = CrossThread;
5295 if (Lex.getKind() == lltok::kw_atomic) {
5300 bool isVolatile = false;
5301 if (Lex.getKind() == lltok::kw_volatile) {
5307 LocTy ExplicitTypeLoc = Lex.getLoc();
5308 if (ParseType(Ty) ||
5309 ParseToken(lltok::comma, "expected comma after load's type") ||
5310 ParseTypeAndValue(Val, Loc, PFS) ||
5311 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5312 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5315 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5316 return Error(Loc, "load operand must be a pointer to a first class type");
5317 if (isAtomic && !Alignment)
5318 return Error(Loc, "atomic load must have explicit non-zero alignment");
5319 if (Ordering == Release || Ordering == AcquireRelease)
5320 return Error(Loc, "atomic load cannot use Release ordering");
5322 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5323 return Error(ExplicitTypeLoc,
5324 "explicit pointee type doesn't match operand's pointee type");
5326 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5327 return AteExtraComma ? InstExtraComma : InstNormal;
5332 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5333 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5334 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5335 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5336 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5337 unsigned Alignment = 0;
5338 bool AteExtraComma = false;
5339 bool isAtomic = false;
5340 AtomicOrdering Ordering = NotAtomic;
5341 SynchronizationScope Scope = CrossThread;
5343 if (Lex.getKind() == lltok::kw_atomic) {
5348 bool isVolatile = false;
5349 if (Lex.getKind() == lltok::kw_volatile) {
5354 if (ParseTypeAndValue(Val, Loc, PFS) ||
5355 ParseToken(lltok::comma, "expected ',' after store operand") ||
5356 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5357 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5358 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5361 if (!Ptr->getType()->isPointerTy())
5362 return Error(PtrLoc, "store operand must be a pointer");
5363 if (!Val->getType()->isFirstClassType())
5364 return Error(Loc, "store operand must be a first class value");
5365 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5366 return Error(Loc, "stored value and pointer type do not match");
5367 if (isAtomic && !Alignment)
5368 return Error(Loc, "atomic store must have explicit non-zero alignment");
5369 if (Ordering == Acquire || Ordering == AcquireRelease)
5370 return Error(Loc, "atomic store cannot use Acquire ordering");
5372 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5373 return AteExtraComma ? InstExtraComma : InstNormal;
5377 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5378 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5379 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5380 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5381 bool AteExtraComma = false;
5382 AtomicOrdering SuccessOrdering = NotAtomic;
5383 AtomicOrdering FailureOrdering = NotAtomic;
5384 SynchronizationScope Scope = CrossThread;
5385 bool isVolatile = false;
5386 bool isWeak = false;
5388 if (EatIfPresent(lltok::kw_weak))
5391 if (EatIfPresent(lltok::kw_volatile))
5394 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5395 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5396 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5397 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5398 ParseTypeAndValue(New, NewLoc, PFS) ||
5399 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5400 ParseOrdering(FailureOrdering))
5403 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5404 return TokError("cmpxchg cannot be unordered");
5405 if (SuccessOrdering < FailureOrdering)
5406 return TokError("cmpxchg must be at least as ordered on success as failure");
5407 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5408 return TokError("cmpxchg failure ordering cannot include release semantics");
5409 if (!Ptr->getType()->isPointerTy())
5410 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5411 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5412 return Error(CmpLoc, "compare value and pointer type do not match");
5413 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5414 return Error(NewLoc, "new value and pointer type do not match");
5415 if (!New->getType()->isIntegerTy())
5416 return Error(NewLoc, "cmpxchg operand must be an integer");
5417 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5418 if (Size < 8 || (Size & (Size - 1)))
5419 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5422 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5423 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5424 CXI->setVolatile(isVolatile);
5425 CXI->setWeak(isWeak);
5427 return AteExtraComma ? InstExtraComma : InstNormal;
5431 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5432 /// 'singlethread'? AtomicOrdering
5433 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5434 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5435 bool AteExtraComma = false;
5436 AtomicOrdering Ordering = NotAtomic;
5437 SynchronizationScope Scope = CrossThread;
5438 bool isVolatile = false;
5439 AtomicRMWInst::BinOp Operation;
5441 if (EatIfPresent(lltok::kw_volatile))
5444 switch (Lex.getKind()) {
5445 default: return TokError("expected binary operation in atomicrmw");
5446 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5447 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5448 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5449 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5450 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5451 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5452 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5453 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5454 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5455 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5456 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5458 Lex.Lex(); // Eat the operation.
5460 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5461 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5462 ParseTypeAndValue(Val, ValLoc, PFS) ||
5463 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5466 if (Ordering == Unordered)
5467 return TokError("atomicrmw cannot be unordered");
5468 if (!Ptr->getType()->isPointerTy())
5469 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5470 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5471 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5472 if (!Val->getType()->isIntegerTy())
5473 return Error(ValLoc, "atomicrmw operand must be an integer");
5474 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5475 if (Size < 8 || (Size & (Size - 1)))
5476 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5479 AtomicRMWInst *RMWI =
5480 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5481 RMWI->setVolatile(isVolatile);
5483 return AteExtraComma ? InstExtraComma : InstNormal;
5487 /// ::= 'fence' 'singlethread'? AtomicOrdering
5488 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5489 AtomicOrdering Ordering = NotAtomic;
5490 SynchronizationScope Scope = CrossThread;
5491 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5494 if (Ordering == Unordered)
5495 return TokError("fence cannot be unordered");
5496 if (Ordering == Monotonic)
5497 return TokError("fence cannot be monotonic");
5499 Inst = new FenceInst(Context, Ordering, Scope);
5503 /// ParseGetElementPtr
5504 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5505 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5506 Value *Ptr = nullptr;
5507 Value *Val = nullptr;
5510 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5513 LocTy ExplicitTypeLoc = Lex.getLoc();
5514 if (ParseType(Ty) ||
5515 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5516 ParseTypeAndValue(Ptr, Loc, PFS))
5519 Type *BaseType = Ptr->getType();
5520 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5521 if (!BasePointerType)
5522 return Error(Loc, "base of getelementptr must be a pointer");
5524 if (Ty != BasePointerType->getElementType())
5525 return Error(ExplicitTypeLoc,
5526 "explicit pointee type doesn't match operand's pointee type");
5528 SmallVector<Value*, 16> Indices;
5529 bool AteExtraComma = false;
5530 while (EatIfPresent(lltok::comma)) {
5531 if (Lex.getKind() == lltok::MetadataVar) {
5532 AteExtraComma = true;
5535 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5536 if (!Val->getType()->getScalarType()->isIntegerTy())
5537 return Error(EltLoc, "getelementptr index must be an integer");
5538 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5539 return Error(EltLoc, "getelementptr index type missmatch");
5540 if (Val->getType()->isVectorTy()) {
5541 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5542 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5543 if (ValNumEl != PtrNumEl)
5544 return Error(EltLoc,
5545 "getelementptr vector index has a wrong number of elements");
5547 Indices.push_back(Val);
5550 SmallPtrSet<const Type*, 4> Visited;
5551 if (!Indices.empty() && !Ty->isSized(&Visited))
5552 return Error(Loc, "base element of getelementptr must be sized");
5554 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5555 return Error(Loc, "invalid getelementptr indices");
5556 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5558 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5559 return AteExtraComma ? InstExtraComma : InstNormal;
5562 /// ParseExtractValue
5563 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5564 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5565 Value *Val; LocTy Loc;
5566 SmallVector<unsigned, 4> Indices;
5568 if (ParseTypeAndValue(Val, Loc, PFS) ||
5569 ParseIndexList(Indices, AteExtraComma))
5572 if (!Val->getType()->isAggregateType())
5573 return Error(Loc, "extractvalue operand must be aggregate type");
5575 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5576 return Error(Loc, "invalid indices for extractvalue");
5577 Inst = ExtractValueInst::Create(Val, Indices);
5578 return AteExtraComma ? InstExtraComma : InstNormal;
5581 /// ParseInsertValue
5582 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5583 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5584 Value *Val0, *Val1; LocTy Loc0, Loc1;
5585 SmallVector<unsigned, 4> Indices;
5587 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5588 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5589 ParseTypeAndValue(Val1, Loc1, PFS) ||
5590 ParseIndexList(Indices, AteExtraComma))
5593 if (!Val0->getType()->isAggregateType())
5594 return Error(Loc0, "insertvalue operand must be aggregate type");
5596 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5598 return Error(Loc0, "invalid indices for insertvalue");
5599 if (IndexedType != Val1->getType())
5600 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5601 getTypeString(Val1->getType()) + "' instead of '" +
5602 getTypeString(IndexedType) + "'");
5603 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5604 return AteExtraComma ? InstExtraComma : InstNormal;
5607 //===----------------------------------------------------------------------===//
5608 // Embedded metadata.
5609 //===----------------------------------------------------------------------===//
5611 /// ParseMDNodeVector
5612 /// ::= { Element (',' Element)* }
5614 /// ::= 'null' | TypeAndValue
5615 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5616 if (ParseToken(lltok::lbrace, "expected '{' here"))
5619 // Check for an empty list.
5620 if (EatIfPresent(lltok::rbrace))
5624 // Null is a special case since it is typeless.
5625 if (EatIfPresent(lltok::kw_null)) {
5626 Elts.push_back(nullptr);
5631 if (ParseMetadata(MD, nullptr))
5634 } while (EatIfPresent(lltok::comma));
5636 return ParseToken(lltok::rbrace, "expected end of metadata node");
5639 //===----------------------------------------------------------------------===//
5640 // Use-list order directives.
5641 //===----------------------------------------------------------------------===//
5642 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5645 return Error(Loc, "value has no uses");
5647 unsigned NumUses = 0;
5648 SmallDenseMap<const Use *, unsigned, 16> Order;
5649 for (const Use &U : V->uses()) {
5650 if (++NumUses > Indexes.size())
5652 Order[&U] = Indexes[NumUses - 1];
5655 return Error(Loc, "value only has one use");
5656 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5657 return Error(Loc, "wrong number of indexes, expected " +
5658 Twine(std::distance(V->use_begin(), V->use_end())));
5660 V->sortUseList([&](const Use &L, const Use &R) {
5661 return Order.lookup(&L) < Order.lookup(&R);
5666 /// ParseUseListOrderIndexes
5667 /// ::= '{' uint32 (',' uint32)+ '}'
5668 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5669 SMLoc Loc = Lex.getLoc();
5670 if (ParseToken(lltok::lbrace, "expected '{' here"))
5672 if (Lex.getKind() == lltok::rbrace)
5673 return Lex.Error("expected non-empty list of uselistorder indexes");
5675 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5676 // indexes should be distinct numbers in the range [0, size-1], and should
5678 unsigned Offset = 0;
5680 bool IsOrdered = true;
5681 assert(Indexes.empty() && "Expected empty order vector");
5684 if (ParseUInt32(Index))
5687 // Update consistency checks.
5688 Offset += Index - Indexes.size();
5689 Max = std::max(Max, Index);
5690 IsOrdered &= Index == Indexes.size();
5692 Indexes.push_back(Index);
5693 } while (EatIfPresent(lltok::comma));
5695 if (ParseToken(lltok::rbrace, "expected '}' here"))
5698 if (Indexes.size() < 2)
5699 return Error(Loc, "expected >= 2 uselistorder indexes");
5700 if (Offset != 0 || Max >= Indexes.size())
5701 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5703 return Error(Loc, "expected uselistorder indexes to change the order");
5708 /// ParseUseListOrder
5709 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5710 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5711 SMLoc Loc = Lex.getLoc();
5712 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5716 SmallVector<unsigned, 16> Indexes;
5717 if (ParseTypeAndValue(V, PFS) ||
5718 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5719 ParseUseListOrderIndexes(Indexes))
5722 return sortUseListOrder(V, Indexes, Loc);
5725 /// ParseUseListOrderBB
5726 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5727 bool LLParser::ParseUseListOrderBB() {
5728 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5729 SMLoc Loc = Lex.getLoc();
5733 SmallVector<unsigned, 16> Indexes;
5734 if (ParseValID(Fn) ||
5735 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5736 ParseValID(Label) ||
5737 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5738 ParseUseListOrderIndexes(Indexes))
5741 // Check the function.
5743 if (Fn.Kind == ValID::t_GlobalName)
5744 GV = M->getNamedValue(Fn.StrVal);
5745 else if (Fn.Kind == ValID::t_GlobalID)
5746 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5748 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5750 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5751 auto *F = dyn_cast<Function>(GV);
5753 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5754 if (F->isDeclaration())
5755 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5757 // Check the basic block.
5758 if (Label.Kind == ValID::t_LocalID)
5759 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5760 if (Label.Kind != ValID::t_LocalName)
5761 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5762 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5764 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5765 if (!isa<BasicBlock>(V))
5766 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5768 return sortUseListOrder(V, Indexes, Loc);