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/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefComdats.empty())
167 return Error(ForwardRefComdats.begin()->second,
168 "use of undefined comdat '$" +
169 ForwardRefComdats.begin()->first + "'");
171 if (!ForwardRefVals.empty())
172 return Error(ForwardRefVals.begin()->second.second,
173 "use of undefined value '@" + ForwardRefVals.begin()->first +
176 if (!ForwardRefValIDs.empty())
177 return Error(ForwardRefValIDs.begin()->second.second,
178 "use of undefined value '@" +
179 Twine(ForwardRefValIDs.begin()->first) + "'");
181 if (!ForwardRefMDNodes.empty())
182 return Error(ForwardRefMDNodes.begin()->second.second,
183 "use of undefined metadata '!" +
184 Twine(ForwardRefMDNodes.begin()->first) + "'");
187 // Look for intrinsic functions and CallInst that need to be upgraded
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
189 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
191 UpgradeDebugInfo(*M);
196 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
197 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
198 PerFunctionState *PFS) {
199 // Loop over all the references, resolving them.
200 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
203 if (Refs[i].first.Kind == ValID::t_LocalName)
204 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
206 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
207 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
208 return Error(Refs[i].first.Loc,
209 "cannot take address of numeric label after the function is defined");
211 Res = dyn_cast_or_null<BasicBlock>(
212 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
216 return Error(Refs[i].first.Loc,
217 "referenced value is not a basic block");
219 // Get the BlockAddress for this and update references to use it.
220 BlockAddress *BA = BlockAddress::get(TheFn, Res);
221 Refs[i].second->replaceAllUsesWith(BA);
222 Refs[i].second->eraseFromParent();
228 //===----------------------------------------------------------------------===//
229 // Top-Level Entities
230 //===----------------------------------------------------------------------===//
232 bool LLParser::ParseTopLevelEntities() {
234 switch (Lex.getKind()) {
235 default: return TokError("expected top-level entity");
236 case lltok::Eof: return false;
237 case lltok::kw_declare: if (ParseDeclare()) return true; break;
238 case lltok::kw_define: if (ParseDefine()) return true; break;
239 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
240 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
241 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
242 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
243 case lltok::LocalVar: if (ParseNamedType()) return true; break;
244 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
245 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
246 case lltok::ComdatVar: if (parseComdat()) return true; break;
247 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
248 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
250 // The Global variable production with no name can have many different
251 // optional leading prefixes, the production is:
252 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
253 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
254 // ('constant'|'global') ...
255 case lltok::kw_private: // OptionalLinkage
256 case lltok::kw_internal: // OptionalLinkage
257 case lltok::kw_linker_private: // Obsolete OptionalLinkage
258 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
259 case lltok::kw_weak: // OptionalLinkage
260 case lltok::kw_weak_odr: // OptionalLinkage
261 case lltok::kw_linkonce: // OptionalLinkage
262 case lltok::kw_linkonce_odr: // OptionalLinkage
263 case lltok::kw_appending: // OptionalLinkage
264 case lltok::kw_common: // OptionalLinkage
265 case lltok::kw_extern_weak: // OptionalLinkage
266 case lltok::kw_external: // OptionalLinkage
267 case lltok::kw_default: // OptionalVisibility
268 case lltok::kw_hidden: // OptionalVisibility
269 case lltok::kw_protected: // OptionalVisibility
270 case lltok::kw_dllimport: // OptionalDLLStorageClass
271 case lltok::kw_dllexport: // OptionalDLLStorageClass
272 case lltok::kw_thread_local: // OptionalThreadLocal
273 case lltok::kw_addrspace: // OptionalAddrSpace
274 case lltok::kw_constant: // GlobalType
275 case lltok::kw_global: { // GlobalType
276 unsigned Linkage, Visibility, DLLStorageClass;
278 GlobalVariable::ThreadLocalMode TLM;
280 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
281 ParseOptionalVisibility(Visibility) ||
282 ParseOptionalDLLStorageClass(DLLStorageClass) ||
283 ParseOptionalThreadLocal(TLM) ||
284 parseOptionalUnnamedAddr(UnnamedAddr) ||
285 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
286 DLLStorageClass, TLM, UnnamedAddr))
291 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
298 /// ::= 'module' 'asm' STRINGCONSTANT
299 bool LLParser::ParseModuleAsm() {
300 assert(Lex.getKind() == lltok::kw_module);
304 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
305 ParseStringConstant(AsmStr)) return true;
307 M->appendModuleInlineAsm(AsmStr);
312 /// ::= 'target' 'triple' '=' STRINGCONSTANT
313 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
314 bool LLParser::ParseTargetDefinition() {
315 assert(Lex.getKind() == lltok::kw_target);
318 default: return TokError("unknown target property");
319 case lltok::kw_triple:
321 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
322 ParseStringConstant(Str))
324 M->setTargetTriple(Str);
326 case lltok::kw_datalayout:
328 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
329 ParseStringConstant(Str))
331 M->setDataLayout(Str);
337 /// ::= 'deplibs' '=' '[' ']'
338 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
339 /// FIXME: Remove in 4.0. Currently parse, but ignore.
340 bool LLParser::ParseDepLibs() {
341 assert(Lex.getKind() == lltok::kw_deplibs);
343 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
344 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
347 if (EatIfPresent(lltok::rsquare))
352 if (ParseStringConstant(Str)) return true;
353 } while (EatIfPresent(lltok::comma));
355 return ParseToken(lltok::rsquare, "expected ']' at end of list");
358 /// ParseUnnamedType:
359 /// ::= LocalVarID '=' 'type' type
360 bool LLParser::ParseUnnamedType() {
361 LocTy TypeLoc = Lex.getLoc();
362 unsigned TypeID = Lex.getUIntVal();
363 Lex.Lex(); // eat LocalVarID;
365 if (ParseToken(lltok::equal, "expected '=' after name") ||
366 ParseToken(lltok::kw_type, "expected 'type' after '='"))
369 if (TypeID >= NumberedTypes.size())
370 NumberedTypes.resize(TypeID+1);
372 Type *Result = nullptr;
373 if (ParseStructDefinition(TypeLoc, "",
374 NumberedTypes[TypeID], Result)) return true;
376 if (!isa<StructType>(Result)) {
377 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
379 return Error(TypeLoc, "non-struct types may not be recursive");
380 Entry.first = Result;
381 Entry.second = SMLoc();
389 /// ::= LocalVar '=' 'type' type
390 bool LLParser::ParseNamedType() {
391 std::string Name = Lex.getStrVal();
392 LocTy NameLoc = Lex.getLoc();
393 Lex.Lex(); // eat LocalVar.
395 if (ParseToken(lltok::equal, "expected '=' after name") ||
396 ParseToken(lltok::kw_type, "expected 'type' after name"))
399 Type *Result = nullptr;
400 if (ParseStructDefinition(NameLoc, Name,
401 NamedTypes[Name], Result)) return true;
403 if (!isa<StructType>(Result)) {
404 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
406 return Error(NameLoc, "non-struct types may not be recursive");
407 Entry.first = Result;
408 Entry.second = SMLoc();
416 /// ::= 'declare' FunctionHeader
417 bool LLParser::ParseDeclare() {
418 assert(Lex.getKind() == lltok::kw_declare);
422 return ParseFunctionHeader(F, false);
426 /// ::= 'define' FunctionHeader '{' ...
427 bool LLParser::ParseDefine() {
428 assert(Lex.getKind() == lltok::kw_define);
432 return ParseFunctionHeader(F, true) ||
433 ParseFunctionBody(*F);
439 bool LLParser::ParseGlobalType(bool &IsConstant) {
440 if (Lex.getKind() == lltok::kw_constant)
442 else if (Lex.getKind() == lltok::kw_global)
446 return TokError("expected 'global' or 'constant'");
452 /// ParseUnnamedGlobal:
453 /// OptionalVisibility ALIAS ...
454 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
455 /// ... -> global variable
456 /// GlobalID '=' OptionalVisibility ALIAS ...
457 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
458 /// ... -> global variable
459 bool LLParser::ParseUnnamedGlobal() {
460 unsigned VarID = NumberedVals.size();
462 LocTy NameLoc = Lex.getLoc();
464 // Handle the GlobalID form.
465 if (Lex.getKind() == lltok::GlobalID) {
466 if (Lex.getUIntVal() != VarID)
467 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
469 Lex.Lex(); // eat GlobalID;
471 if (ParseToken(lltok::equal, "expected '=' after name"))
476 unsigned Linkage, Visibility, DLLStorageClass;
477 GlobalVariable::ThreadLocalMode TLM;
479 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
480 ParseOptionalVisibility(Visibility) ||
481 ParseOptionalDLLStorageClass(DLLStorageClass) ||
482 ParseOptionalThreadLocal(TLM) ||
483 parseOptionalUnnamedAddr(UnnamedAddr))
486 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
487 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
488 DLLStorageClass, TLM, UnnamedAddr);
489 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
493 /// ParseNamedGlobal:
494 /// GlobalVar '=' OptionalVisibility ALIAS ...
495 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
496 /// ... -> global variable
497 bool LLParser::ParseNamedGlobal() {
498 assert(Lex.getKind() == lltok::GlobalVar);
499 LocTy NameLoc = Lex.getLoc();
500 std::string Name = Lex.getStrVal();
504 unsigned Linkage, Visibility, DLLStorageClass;
505 GlobalVariable::ThreadLocalMode TLM;
507 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
508 ParseOptionalLinkage(Linkage, HasLinkage) ||
509 ParseOptionalVisibility(Visibility) ||
510 ParseOptionalDLLStorageClass(DLLStorageClass) ||
511 ParseOptionalThreadLocal(TLM) ||
512 parseOptionalUnnamedAddr(UnnamedAddr))
515 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
516 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
517 DLLStorageClass, TLM, UnnamedAddr);
518 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
522 bool LLParser::parseComdat() {
523 assert(Lex.getKind() == lltok::ComdatVar);
524 std::string Name = Lex.getStrVal();
525 LocTy NameLoc = Lex.getLoc();
528 if (ParseToken(lltok::equal, "expected '=' here"))
531 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
532 return TokError("expected comdat type");
534 Comdat::SelectionKind SK;
535 switch (Lex.getKind()) {
537 return TokError("unknown selection kind");
541 case lltok::kw_exactmatch:
542 SK = Comdat::ExactMatch;
544 case lltok::kw_largest:
545 SK = Comdat::Largest;
547 case lltok::kw_noduplicates:
548 SK = Comdat::NoDuplicates;
550 case lltok::kw_samesize:
551 SK = Comdat::SameSize;
556 // See if the comdat was forward referenced, if so, use the comdat.
557 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
558 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
559 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
560 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
563 if (I != ComdatSymTab.end())
566 C = M->getOrInsertComdat(Name);
567 C->setSelectionKind(SK);
573 // ::= '!' STRINGCONSTANT
574 bool LLParser::ParseMDString(MDString *&Result) {
576 if (ParseStringConstant(Str)) return true;
577 llvm::UpgradeMDStringConstant(Str);
578 Result = MDString::get(Context, Str);
583 // ::= '!' MDNodeNumber
585 /// This version of ParseMDNodeID returns the slot number and null in the case
586 /// of a forward reference.
587 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
588 // !{ ..., !42, ... }
589 if (ParseUInt32(SlotNo)) return true;
591 // Check existing MDNode.
592 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
593 Result = NumberedMetadata[SlotNo];
599 bool LLParser::ParseMDNodeID(MDNode *&Result) {
600 // !{ ..., !42, ... }
602 if (ParseMDNodeID(Result, MID)) return true;
604 // If not a forward reference, just return it now.
605 if (Result) return false;
607 // Otherwise, create MDNode forward reference.
608 MDNode *FwdNode = MDNode::getTemporary(Context, None);
609 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
611 if (NumberedMetadata.size() <= MID)
612 NumberedMetadata.resize(MID+1);
613 NumberedMetadata[MID] = FwdNode;
618 /// ParseNamedMetadata:
619 /// !foo = !{ !1, !2 }
620 bool LLParser::ParseNamedMetadata() {
621 assert(Lex.getKind() == lltok::MetadataVar);
622 std::string Name = Lex.getStrVal();
625 if (ParseToken(lltok::equal, "expected '=' here") ||
626 ParseToken(lltok::exclaim, "Expected '!' here") ||
627 ParseToken(lltok::lbrace, "Expected '{' here"))
630 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
631 if (Lex.getKind() != lltok::rbrace)
633 if (ParseToken(lltok::exclaim, "Expected '!' here"))
637 if (ParseMDNodeID(N)) return true;
639 } while (EatIfPresent(lltok::comma));
641 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
647 /// ParseStandaloneMetadata:
649 bool LLParser::ParseStandaloneMetadata() {
650 assert(Lex.getKind() == lltok::exclaim);
652 unsigned MetadataID = 0;
656 SmallVector<Value *, 16> Elts;
657 if (ParseUInt32(MetadataID) ||
658 ParseToken(lltok::equal, "expected '=' here") ||
659 ParseType(Ty, TyLoc) ||
660 ParseToken(lltok::exclaim, "Expected '!' here") ||
661 ParseToken(lltok::lbrace, "Expected '{' here") ||
662 ParseMDNodeVector(Elts, nullptr) ||
663 ParseToken(lltok::rbrace, "expected end of metadata node"))
666 MDNode *Init = MDNode::get(Context, Elts);
668 // See if this was forward referenced, if so, handle it.
669 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
670 FI = ForwardRefMDNodes.find(MetadataID);
671 if (FI != ForwardRefMDNodes.end()) {
672 MDNode *Temp = FI->second.first;
673 Temp->replaceAllUsesWith(Init);
674 MDNode::deleteTemporary(Temp);
675 ForwardRefMDNodes.erase(FI);
677 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
679 if (MetadataID >= NumberedMetadata.size())
680 NumberedMetadata.resize(MetadataID+1);
682 if (NumberedMetadata[MetadataID] != nullptr)
683 return TokError("Metadata id is already used");
684 NumberedMetadata[MetadataID] = Init;
690 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
691 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
692 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
696 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
697 /// OptionalThreadLocal OptionalUnNammedAddr 'alias'
698 /// OptionalLinkage Aliasee
703 /// Everything through OptionalUnNammedAddr has already been parsed.
705 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
706 unsigned Visibility, unsigned DLLStorageClass,
707 GlobalVariable::ThreadLocalMode TLM,
709 assert(Lex.getKind() == lltok::kw_alias);
711 LocTy LinkageLoc = Lex.getLoc();
713 if (ParseOptionalLinkage(L))
716 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
718 if(!GlobalAlias::isValidLinkage(Linkage))
719 return Error(LinkageLoc, "invalid linkage type for alias");
721 if (!isValidVisibilityForLinkage(Visibility, L))
722 return Error(LinkageLoc,
723 "symbol with local linkage must have default visibility");
726 LocTy AliaseeLoc = Lex.getLoc();
727 if (Lex.getKind() != lltok::kw_bitcast &&
728 Lex.getKind() != lltok::kw_getelementptr &&
729 Lex.getKind() != lltok::kw_addrspacecast &&
730 Lex.getKind() != lltok::kw_inttoptr) {
731 if (ParseGlobalTypeAndValue(Aliasee))
734 // The bitcast dest type is not present, it is implied by the dest type.
738 if (ID.Kind != ValID::t_Constant)
739 return Error(AliaseeLoc, "invalid aliasee");
740 Aliasee = ID.ConstantVal;
743 Type *AliaseeType = Aliasee->getType();
744 auto *PTy = dyn_cast<PointerType>(AliaseeType);
746 return Error(AliaseeLoc, "An alias must have pointer type");
747 Type *Ty = PTy->getElementType();
748 unsigned AddrSpace = PTy->getAddressSpace();
750 // Okay, create the alias but do not insert it into the module yet.
751 std::unique_ptr<GlobalAlias> GA(
752 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
753 Name, Aliasee, /*Parent*/ nullptr));
754 GA->setThreadLocalMode(TLM);
755 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
756 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
757 GA->setUnnamedAddr(UnnamedAddr);
759 // See if this value already exists in the symbol table. If so, it is either
760 // a redefinition or a definition of a forward reference.
761 if (GlobalValue *Val = M->getNamedValue(Name)) {
762 // See if this was a redefinition. If so, there is no entry in
764 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
765 I = ForwardRefVals.find(Name);
766 if (I == ForwardRefVals.end())
767 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
769 // Otherwise, this was a definition of forward ref. Verify that types
771 if (Val->getType() != GA->getType())
772 return Error(NameLoc,
773 "forward reference and definition of alias have different types");
775 // If they agree, just RAUW the old value with the alias and remove the
777 Val->replaceAllUsesWith(GA.get());
778 Val->eraseFromParent();
779 ForwardRefVals.erase(I);
782 // Insert into the module, we know its name won't collide now.
783 M->getAliasList().push_back(GA.get());
784 assert(GA->getName() == Name && "Should not be a name conflict!");
786 // The module owns this now
793 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
794 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
795 /// OptionalExternallyInitialized GlobalType Type Const
796 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
797 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
798 /// OptionalExternallyInitialized GlobalType Type Const
800 /// Everything up to and including OptionalUnNammedAddr has been parsed
803 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
804 unsigned Linkage, bool HasLinkage,
805 unsigned Visibility, unsigned DLLStorageClass,
806 GlobalVariable::ThreadLocalMode TLM,
808 if (!isValidVisibilityForLinkage(Visibility, Linkage))
809 return Error(NameLoc,
810 "symbol with local linkage must have default visibility");
813 bool IsConstant, IsExternallyInitialized;
814 LocTy IsExternallyInitializedLoc;
818 if (ParseOptionalAddrSpace(AddrSpace) ||
819 ParseOptionalToken(lltok::kw_externally_initialized,
820 IsExternallyInitialized,
821 &IsExternallyInitializedLoc) ||
822 ParseGlobalType(IsConstant) ||
823 ParseType(Ty, TyLoc))
826 // If the linkage is specified and is external, then no initializer is
828 Constant *Init = nullptr;
829 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
830 Linkage != GlobalValue::ExternalLinkage)) {
831 if (ParseGlobalValue(Ty, Init))
835 if (Ty->isFunctionTy() || Ty->isLabelTy())
836 return Error(TyLoc, "invalid type for global variable");
838 GlobalVariable *GV = nullptr;
840 // See if the global was forward referenced, if so, use the global.
842 if (GlobalValue *GVal = M->getNamedValue(Name)) {
843 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
844 return Error(NameLoc, "redefinition of global '@" + Name + "'");
845 GV = cast<GlobalVariable>(GVal);
848 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
849 I = ForwardRefValIDs.find(NumberedVals.size());
850 if (I != ForwardRefValIDs.end()) {
851 GV = cast<GlobalVariable>(I->second.first);
852 ForwardRefValIDs.erase(I);
857 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
858 Name, nullptr, GlobalVariable::NotThreadLocal,
861 if (GV->getType()->getElementType() != Ty)
863 "forward reference and definition of global have different types");
865 // Move the forward-reference to the correct spot in the module.
866 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
870 NumberedVals.push_back(GV);
872 // Set the parsed properties on the global.
874 GV->setInitializer(Init);
875 GV->setConstant(IsConstant);
876 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
877 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
878 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
879 GV->setExternallyInitialized(IsExternallyInitialized);
880 GV->setThreadLocalMode(TLM);
881 GV->setUnnamedAddr(UnnamedAddr);
883 // Parse attributes on the global.
884 while (Lex.getKind() == lltok::comma) {
887 if (Lex.getKind() == lltok::kw_section) {
889 GV->setSection(Lex.getStrVal());
890 if (ParseToken(lltok::StringConstant, "expected global section string"))
892 } else if (Lex.getKind() == lltok::kw_align) {
894 if (ParseOptionalAlignment(Alignment)) return true;
895 GV->setAlignment(Alignment);
898 if (parseOptionalComdat(C))
903 return TokError("unknown global variable property!");
910 /// ParseUnnamedAttrGrp
911 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
912 bool LLParser::ParseUnnamedAttrGrp() {
913 assert(Lex.getKind() == lltok::kw_attributes);
914 LocTy AttrGrpLoc = Lex.getLoc();
917 assert(Lex.getKind() == lltok::AttrGrpID);
918 unsigned VarID = Lex.getUIntVal();
919 std::vector<unsigned> unused;
923 if (ParseToken(lltok::equal, "expected '=' here") ||
924 ParseToken(lltok::lbrace, "expected '{' here") ||
925 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
927 ParseToken(lltok::rbrace, "expected end of attribute group"))
930 if (!NumberedAttrBuilders[VarID].hasAttributes())
931 return Error(AttrGrpLoc, "attribute group has no attributes");
936 /// ParseFnAttributeValuePairs
937 /// ::= <attr> | <attr> '=' <value>
938 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
939 std::vector<unsigned> &FwdRefAttrGrps,
940 bool inAttrGrp, LocTy &BuiltinLoc) {
941 bool HaveError = false;
946 lltok::Kind Token = Lex.getKind();
947 if (Token == lltok::kw_builtin)
948 BuiltinLoc = Lex.getLoc();
951 if (!inAttrGrp) return HaveError;
952 return Error(Lex.getLoc(), "unterminated attribute group");
957 case lltok::AttrGrpID: {
958 // Allow a function to reference an attribute group:
960 // define void @foo() #1 { ... }
964 "cannot have an attribute group reference in an attribute group");
966 unsigned AttrGrpNum = Lex.getUIntVal();
967 if (inAttrGrp) break;
969 // Save the reference to the attribute group. We'll fill it in later.
970 FwdRefAttrGrps.push_back(AttrGrpNum);
973 // Target-dependent attributes:
974 case lltok::StringConstant: {
975 std::string Attr = Lex.getStrVal();
978 if (EatIfPresent(lltok::equal) &&
979 ParseStringConstant(Val))
982 B.addAttribute(Attr, Val);
986 // Target-independent attributes:
987 case lltok::kw_align: {
988 // As a hack, we allow function alignment to be initially parsed as an
989 // attribute on a function declaration/definition or added to an attribute
990 // group and later moved to the alignment field.
994 if (ParseToken(lltok::equal, "expected '=' here") ||
995 ParseUInt32(Alignment))
998 if (ParseOptionalAlignment(Alignment))
1001 B.addAlignmentAttr(Alignment);
1004 case lltok::kw_alignstack: {
1008 if (ParseToken(lltok::equal, "expected '=' here") ||
1009 ParseUInt32(Alignment))
1012 if (ParseOptionalStackAlignment(Alignment))
1015 B.addStackAlignmentAttr(Alignment);
1018 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1019 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1020 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1021 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1022 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1023 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1024 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1025 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1026 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1027 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
1028 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1029 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1030 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1031 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1032 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1033 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1034 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1035 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1036 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1037 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1038 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1039 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1040 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1041 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1042 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1043 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1044 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1047 case lltok::kw_inreg:
1048 case lltok::kw_signext:
1049 case lltok::kw_zeroext:
1052 "invalid use of attribute on a function");
1054 case lltok::kw_byval:
1055 case lltok::kw_inalloca:
1056 case lltok::kw_nest:
1057 case lltok::kw_noalias:
1058 case lltok::kw_nocapture:
1059 case lltok::kw_nonnull:
1060 case lltok::kw_returned:
1061 case lltok::kw_sret:
1064 "invalid use of parameter-only attribute on a function");
1072 //===----------------------------------------------------------------------===//
1073 // GlobalValue Reference/Resolution Routines.
1074 //===----------------------------------------------------------------------===//
1076 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1077 /// forward reference record if needed. This can return null if the value
1078 /// exists but does not have the right type.
1079 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1081 PointerType *PTy = dyn_cast<PointerType>(Ty);
1083 Error(Loc, "global variable reference must have pointer type");
1087 // Look this name up in the normal function symbol table.
1089 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1091 // If this is a forward reference for the value, see if we already created a
1092 // forward ref record.
1094 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1095 I = ForwardRefVals.find(Name);
1096 if (I != ForwardRefVals.end())
1097 Val = I->second.first;
1100 // If we have the value in the symbol table or fwd-ref table, return it.
1102 if (Val->getType() == Ty) return Val;
1103 Error(Loc, "'@" + Name + "' defined with type '" +
1104 getTypeString(Val->getType()) + "'");
1108 // Otherwise, create a new forward reference for this value and remember it.
1109 GlobalValue *FwdVal;
1110 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1111 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1113 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1114 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1115 nullptr, GlobalVariable::NotThreadLocal,
1116 PTy->getAddressSpace());
1118 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1122 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1123 PointerType *PTy = dyn_cast<PointerType>(Ty);
1125 Error(Loc, "global variable reference must have pointer type");
1129 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1131 // If this is a forward reference for the value, see if we already created a
1132 // forward ref record.
1134 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1135 I = ForwardRefValIDs.find(ID);
1136 if (I != ForwardRefValIDs.end())
1137 Val = I->second.first;
1140 // If we have the value in the symbol table or fwd-ref table, return it.
1142 if (Val->getType() == Ty) return Val;
1143 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1144 getTypeString(Val->getType()) + "'");
1148 // Otherwise, create a new forward reference for this value and remember it.
1149 GlobalValue *FwdVal;
1150 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1151 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1153 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1154 GlobalValue::ExternalWeakLinkage, nullptr, "");
1156 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1161 //===----------------------------------------------------------------------===//
1162 // Comdat Reference/Resolution Routines.
1163 //===----------------------------------------------------------------------===//
1165 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1166 // Look this name up in the comdat symbol table.
1167 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1168 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1169 if (I != ComdatSymTab.end())
1172 // Otherwise, create a new forward reference for this value and remember it.
1173 Comdat *C = M->getOrInsertComdat(Name);
1174 ForwardRefComdats[Name] = Loc;
1179 //===----------------------------------------------------------------------===//
1181 //===----------------------------------------------------------------------===//
1183 /// ParseToken - If the current token has the specified kind, eat it and return
1184 /// success. Otherwise, emit the specified error and return failure.
1185 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1186 if (Lex.getKind() != T)
1187 return TokError(ErrMsg);
1192 /// ParseStringConstant
1193 /// ::= StringConstant
1194 bool LLParser::ParseStringConstant(std::string &Result) {
1195 if (Lex.getKind() != lltok::StringConstant)
1196 return TokError("expected string constant");
1197 Result = Lex.getStrVal();
1204 bool LLParser::ParseUInt32(unsigned &Val) {
1205 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1206 return TokError("expected integer");
1207 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1208 if (Val64 != unsigned(Val64))
1209 return TokError("expected 32-bit integer (too large)");
1216 /// := 'localdynamic'
1217 /// := 'initialexec'
1219 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1220 switch (Lex.getKind()) {
1222 return TokError("expected localdynamic, initialexec or localexec");
1223 case lltok::kw_localdynamic:
1224 TLM = GlobalVariable::LocalDynamicTLSModel;
1226 case lltok::kw_initialexec:
1227 TLM = GlobalVariable::InitialExecTLSModel;
1229 case lltok::kw_localexec:
1230 TLM = GlobalVariable::LocalExecTLSModel;
1238 /// ParseOptionalThreadLocal
1240 /// := 'thread_local'
1241 /// := 'thread_local' '(' tlsmodel ')'
1242 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1243 TLM = GlobalVariable::NotThreadLocal;
1244 if (!EatIfPresent(lltok::kw_thread_local))
1247 TLM = GlobalVariable::GeneralDynamicTLSModel;
1248 if (Lex.getKind() == lltok::lparen) {
1250 return ParseTLSModel(TLM) ||
1251 ParseToken(lltok::rparen, "expected ')' after thread local model");
1256 /// ParseOptionalAddrSpace
1258 /// := 'addrspace' '(' uint32 ')'
1259 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1261 if (!EatIfPresent(lltok::kw_addrspace))
1263 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1264 ParseUInt32(AddrSpace) ||
1265 ParseToken(lltok::rparen, "expected ')' in address space");
1268 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1269 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1270 bool HaveError = false;
1275 lltok::Kind Token = Lex.getKind();
1277 default: // End of attributes.
1279 case lltok::kw_align: {
1281 if (ParseOptionalAlignment(Alignment))
1283 B.addAlignmentAttr(Alignment);
1286 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1287 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1288 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1289 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1290 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1291 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1292 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1293 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1294 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1295 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1296 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1297 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1298 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1300 case lltok::kw_alignstack:
1301 case lltok::kw_alwaysinline:
1302 case lltok::kw_builtin:
1303 case lltok::kw_inlinehint:
1304 case lltok::kw_jumptable:
1305 case lltok::kw_minsize:
1306 case lltok::kw_naked:
1307 case lltok::kw_nobuiltin:
1308 case lltok::kw_noduplicate:
1309 case lltok::kw_noimplicitfloat:
1310 case lltok::kw_noinline:
1311 case lltok::kw_nonlazybind:
1312 case lltok::kw_noredzone:
1313 case lltok::kw_noreturn:
1314 case lltok::kw_nounwind:
1315 case lltok::kw_optnone:
1316 case lltok::kw_optsize:
1317 case lltok::kw_returns_twice:
1318 case lltok::kw_sanitize_address:
1319 case lltok::kw_sanitize_memory:
1320 case lltok::kw_sanitize_thread:
1322 case lltok::kw_sspreq:
1323 case lltok::kw_sspstrong:
1324 case lltok::kw_uwtable:
1325 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1333 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1334 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1335 bool HaveError = false;
1340 lltok::Kind Token = Lex.getKind();
1342 default: // End of attributes.
1344 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1345 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1346 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1347 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1348 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1351 case lltok::kw_align:
1352 case lltok::kw_byval:
1353 case lltok::kw_inalloca:
1354 case lltok::kw_nest:
1355 case lltok::kw_nocapture:
1356 case lltok::kw_returned:
1357 case lltok::kw_sret:
1358 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1361 case lltok::kw_alignstack:
1362 case lltok::kw_alwaysinline:
1363 case lltok::kw_builtin:
1364 case lltok::kw_cold:
1365 case lltok::kw_inlinehint:
1366 case lltok::kw_jumptable:
1367 case lltok::kw_minsize:
1368 case lltok::kw_naked:
1369 case lltok::kw_nobuiltin:
1370 case lltok::kw_noduplicate:
1371 case lltok::kw_noimplicitfloat:
1372 case lltok::kw_noinline:
1373 case lltok::kw_nonlazybind:
1374 case lltok::kw_noredzone:
1375 case lltok::kw_noreturn:
1376 case lltok::kw_nounwind:
1377 case lltok::kw_optnone:
1378 case lltok::kw_optsize:
1379 case lltok::kw_returns_twice:
1380 case lltok::kw_sanitize_address:
1381 case lltok::kw_sanitize_memory:
1382 case lltok::kw_sanitize_thread:
1384 case lltok::kw_sspreq:
1385 case lltok::kw_sspstrong:
1386 case lltok::kw_uwtable:
1387 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1390 case lltok::kw_readnone:
1391 case lltok::kw_readonly:
1392 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1399 /// ParseOptionalLinkage
1406 /// ::= 'linkonce_odr'
1407 /// ::= 'available_externally'
1410 /// ::= 'extern_weak'
1413 /// Deprecated Values:
1414 /// ::= 'linker_private'
1415 /// ::= 'linker_private_weak'
1416 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1418 switch (Lex.getKind()) {
1419 default: Res=GlobalValue::ExternalLinkage; return false;
1420 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1421 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1422 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1423 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1424 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1425 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1426 case lltok::kw_available_externally:
1427 Res = GlobalValue::AvailableExternallyLinkage;
1429 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1430 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1431 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1432 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1434 case lltok::kw_linker_private:
1435 case lltok::kw_linker_private_weak:
1436 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1439 // treat linker_private and linker_private_weak as PrivateLinkage
1440 Res = GlobalValue::PrivateLinkage;
1448 /// ParseOptionalVisibility
1454 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1455 switch (Lex.getKind()) {
1456 default: Res = GlobalValue::DefaultVisibility; return false;
1457 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1458 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1459 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1465 /// ParseOptionalDLLStorageClass
1470 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1471 switch (Lex.getKind()) {
1472 default: Res = GlobalValue::DefaultStorageClass; return false;
1473 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1474 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1480 /// ParseOptionalCallingConv
1484 /// ::= 'kw_intel_ocl_bicc'
1486 /// ::= 'x86_stdcallcc'
1487 /// ::= 'x86_fastcallcc'
1488 /// ::= 'x86_thiscallcc'
1489 /// ::= 'arm_apcscc'
1490 /// ::= 'arm_aapcscc'
1491 /// ::= 'arm_aapcs_vfpcc'
1492 /// ::= 'msp430_intrcc'
1493 /// ::= 'ptx_kernel'
1494 /// ::= 'ptx_device'
1496 /// ::= 'spir_kernel'
1497 /// ::= 'x86_64_sysvcc'
1498 /// ::= 'x86_64_win64cc'
1499 /// ::= 'webkit_jscc'
1501 /// ::= 'preserve_mostcc'
1502 /// ::= 'preserve_allcc'
1505 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1506 switch (Lex.getKind()) {
1507 default: CC = CallingConv::C; return false;
1508 case lltok::kw_ccc: CC = CallingConv::C; break;
1509 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1510 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1511 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1512 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1513 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1514 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1515 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1516 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1517 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1518 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1519 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1520 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1521 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1522 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1523 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1524 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1525 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1526 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1527 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1528 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1529 case lltok::kw_cc: {
1530 unsigned ArbitraryCC;
1532 if (ParseUInt32(ArbitraryCC))
1534 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1543 /// ParseInstructionMetadata
1544 /// ::= !dbg !42 (',' !dbg !57)*
1545 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1546 PerFunctionState *PFS) {
1548 if (Lex.getKind() != lltok::MetadataVar)
1549 return TokError("expected metadata after comma");
1551 std::string Name = Lex.getStrVal();
1552 unsigned MDK = M->getMDKindID(Name);
1556 SMLoc Loc = Lex.getLoc();
1558 if (ParseToken(lltok::exclaim, "expected '!' here"))
1561 // This code is similar to that of ParseMetadataValue, however it needs to
1562 // have special-case code for a forward reference; see the comments on
1563 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1564 // at the top level here.
1565 if (Lex.getKind() == lltok::lbrace) {
1567 if (ParseMetadataListValue(ID, PFS))
1569 assert(ID.Kind == ValID::t_MDNode);
1570 Inst->setMetadata(MDK, ID.MDNodeVal);
1572 unsigned NodeID = 0;
1573 if (ParseMDNodeID(Node, NodeID))
1576 // If we got the node, add it to the instruction.
1577 Inst->setMetadata(MDK, Node);
1579 MDRef R = { Loc, MDK, NodeID };
1580 // Otherwise, remember that this should be resolved later.
1581 ForwardRefInstMetadata[Inst].push_back(R);
1585 if (MDK == LLVMContext::MD_tbaa)
1586 InstsWithTBAATag.push_back(Inst);
1588 // If this is the end of the list, we're done.
1589 } while (EatIfPresent(lltok::comma));
1593 /// ParseOptionalAlignment
1596 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1598 if (!EatIfPresent(lltok::kw_align))
1600 LocTy AlignLoc = Lex.getLoc();
1601 if (ParseUInt32(Alignment)) return true;
1602 if (!isPowerOf2_32(Alignment))
1603 return Error(AlignLoc, "alignment is not a power of two");
1604 if (Alignment > Value::MaximumAlignment)
1605 return Error(AlignLoc, "huge alignments are not supported yet");
1609 /// ParseOptionalCommaAlign
1613 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1615 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1616 bool &AteExtraComma) {
1617 AteExtraComma = false;
1618 while (EatIfPresent(lltok::comma)) {
1619 // Metadata at the end is an early exit.
1620 if (Lex.getKind() == lltok::MetadataVar) {
1621 AteExtraComma = true;
1625 if (Lex.getKind() != lltok::kw_align)
1626 return Error(Lex.getLoc(), "expected metadata or 'align'");
1628 if (ParseOptionalAlignment(Alignment)) return true;
1634 /// ParseScopeAndOrdering
1635 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1638 /// This sets Scope and Ordering to the parsed values.
1639 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1640 AtomicOrdering &Ordering) {
1644 Scope = CrossThread;
1645 if (EatIfPresent(lltok::kw_singlethread))
1646 Scope = SingleThread;
1648 return ParseOrdering(Ordering);
1652 /// ::= AtomicOrdering
1654 /// This sets Ordering to the parsed value.
1655 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1656 switch (Lex.getKind()) {
1657 default: return TokError("Expected ordering on atomic instruction");
1658 case lltok::kw_unordered: Ordering = Unordered; break;
1659 case lltok::kw_monotonic: Ordering = Monotonic; break;
1660 case lltok::kw_acquire: Ordering = Acquire; break;
1661 case lltok::kw_release: Ordering = Release; break;
1662 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1663 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1669 /// ParseOptionalStackAlignment
1671 /// ::= 'alignstack' '(' 4 ')'
1672 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1674 if (!EatIfPresent(lltok::kw_alignstack))
1676 LocTy ParenLoc = Lex.getLoc();
1677 if (!EatIfPresent(lltok::lparen))
1678 return Error(ParenLoc, "expected '('");
1679 LocTy AlignLoc = Lex.getLoc();
1680 if (ParseUInt32(Alignment)) return true;
1681 ParenLoc = Lex.getLoc();
1682 if (!EatIfPresent(lltok::rparen))
1683 return Error(ParenLoc, "expected ')'");
1684 if (!isPowerOf2_32(Alignment))
1685 return Error(AlignLoc, "stack alignment is not a power of two");
1689 /// ParseIndexList - This parses the index list for an insert/extractvalue
1690 /// instruction. This sets AteExtraComma in the case where we eat an extra
1691 /// comma at the end of the line and find that it is followed by metadata.
1692 /// Clients that don't allow metadata can call the version of this function that
1693 /// only takes one argument.
1696 /// ::= (',' uint32)+
1698 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1699 bool &AteExtraComma) {
1700 AteExtraComma = false;
1702 if (Lex.getKind() != lltok::comma)
1703 return TokError("expected ',' as start of index list");
1705 while (EatIfPresent(lltok::comma)) {
1706 if (Lex.getKind() == lltok::MetadataVar) {
1707 AteExtraComma = true;
1711 if (ParseUInt32(Idx)) return true;
1712 Indices.push_back(Idx);
1718 //===----------------------------------------------------------------------===//
1720 //===----------------------------------------------------------------------===//
1722 /// ParseType - Parse a type.
1723 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1724 SMLoc TypeLoc = Lex.getLoc();
1725 switch (Lex.getKind()) {
1727 return TokError("expected type");
1729 // Type ::= 'float' | 'void' (etc)
1730 Result = Lex.getTyVal();
1734 // Type ::= StructType
1735 if (ParseAnonStructType(Result, false))
1738 case lltok::lsquare:
1739 // Type ::= '[' ... ']'
1740 Lex.Lex(); // eat the lsquare.
1741 if (ParseArrayVectorType(Result, false))
1744 case lltok::less: // Either vector or packed struct.
1745 // Type ::= '<' ... '>'
1747 if (Lex.getKind() == lltok::lbrace) {
1748 if (ParseAnonStructType(Result, true) ||
1749 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1751 } else if (ParseArrayVectorType(Result, true))
1754 case lltok::LocalVar: {
1756 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1758 // If the type hasn't been defined yet, create a forward definition and
1759 // remember where that forward def'n was seen (in case it never is defined).
1761 Entry.first = StructType::create(Context, Lex.getStrVal());
1762 Entry.second = Lex.getLoc();
1764 Result = Entry.first;
1769 case lltok::LocalVarID: {
1771 if (Lex.getUIntVal() >= NumberedTypes.size())
1772 NumberedTypes.resize(Lex.getUIntVal()+1);
1773 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1775 // If the type hasn't been defined yet, create a forward definition and
1776 // remember where that forward def'n was seen (in case it never is defined).
1778 Entry.first = StructType::create(Context);
1779 Entry.second = Lex.getLoc();
1781 Result = Entry.first;
1787 // Parse the type suffixes.
1789 switch (Lex.getKind()) {
1792 if (!AllowVoid && Result->isVoidTy())
1793 return Error(TypeLoc, "void type only allowed for function results");
1796 // Type ::= Type '*'
1798 if (Result->isLabelTy())
1799 return TokError("basic block pointers are invalid");
1800 if (Result->isVoidTy())
1801 return TokError("pointers to void are invalid - use i8* instead");
1802 if (!PointerType::isValidElementType(Result))
1803 return TokError("pointer to this type is invalid");
1804 Result = PointerType::getUnqual(Result);
1808 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1809 case lltok::kw_addrspace: {
1810 if (Result->isLabelTy())
1811 return TokError("basic block pointers are invalid");
1812 if (Result->isVoidTy())
1813 return TokError("pointers to void are invalid; use i8* instead");
1814 if (!PointerType::isValidElementType(Result))
1815 return TokError("pointer to this type is invalid");
1817 if (ParseOptionalAddrSpace(AddrSpace) ||
1818 ParseToken(lltok::star, "expected '*' in address space"))
1821 Result = PointerType::get(Result, AddrSpace);
1825 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1827 if (ParseFunctionType(Result))
1834 /// ParseParameterList
1836 /// ::= '(' Arg (',' Arg)* ')'
1838 /// ::= Type OptionalAttributes Value OptionalAttributes
1839 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1840 PerFunctionState &PFS) {
1841 if (ParseToken(lltok::lparen, "expected '(' in call"))
1844 unsigned AttrIndex = 1;
1845 while (Lex.getKind() != lltok::rparen) {
1846 // If this isn't the first argument, we need a comma.
1847 if (!ArgList.empty() &&
1848 ParseToken(lltok::comma, "expected ',' in argument list"))
1851 // Parse the argument.
1853 Type *ArgTy = nullptr;
1854 AttrBuilder ArgAttrs;
1856 if (ParseType(ArgTy, ArgLoc))
1859 // Otherwise, handle normal operands.
1860 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1862 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1867 Lex.Lex(); // Lex the ')'.
1873 /// ParseArgumentList - Parse the argument list for a function type or function
1875 /// ::= '(' ArgTypeListI ')'
1879 /// ::= ArgTypeList ',' '...'
1880 /// ::= ArgType (',' ArgType)*
1882 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1885 assert(Lex.getKind() == lltok::lparen);
1886 Lex.Lex(); // eat the (.
1888 if (Lex.getKind() == lltok::rparen) {
1890 } else if (Lex.getKind() == lltok::dotdotdot) {
1894 LocTy TypeLoc = Lex.getLoc();
1895 Type *ArgTy = nullptr;
1899 if (ParseType(ArgTy) ||
1900 ParseOptionalParamAttrs(Attrs)) return true;
1902 if (ArgTy->isVoidTy())
1903 return Error(TypeLoc, "argument can not have void type");
1905 if (Lex.getKind() == lltok::LocalVar) {
1906 Name = Lex.getStrVal();
1910 if (!FunctionType::isValidArgumentType(ArgTy))
1911 return Error(TypeLoc, "invalid type for function argument");
1913 unsigned AttrIndex = 1;
1914 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1915 AttributeSet::get(ArgTy->getContext(),
1916 AttrIndex++, Attrs), Name));
1918 while (EatIfPresent(lltok::comma)) {
1919 // Handle ... at end of arg list.
1920 if (EatIfPresent(lltok::dotdotdot)) {
1925 // Otherwise must be an argument type.
1926 TypeLoc = Lex.getLoc();
1927 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1929 if (ArgTy->isVoidTy())
1930 return Error(TypeLoc, "argument can not have void type");
1932 if (Lex.getKind() == lltok::LocalVar) {
1933 Name = Lex.getStrVal();
1939 if (!ArgTy->isFirstClassType())
1940 return Error(TypeLoc, "invalid type for function argument");
1942 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1943 AttributeSet::get(ArgTy->getContext(),
1944 AttrIndex++, Attrs),
1949 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1952 /// ParseFunctionType
1953 /// ::= Type ArgumentList OptionalAttrs
1954 bool LLParser::ParseFunctionType(Type *&Result) {
1955 assert(Lex.getKind() == lltok::lparen);
1957 if (!FunctionType::isValidReturnType(Result))
1958 return TokError("invalid function return type");
1960 SmallVector<ArgInfo, 8> ArgList;
1962 if (ParseArgumentList(ArgList, isVarArg))
1965 // Reject names on the arguments lists.
1966 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1967 if (!ArgList[i].Name.empty())
1968 return Error(ArgList[i].Loc, "argument name invalid in function type");
1969 if (ArgList[i].Attrs.hasAttributes(i + 1))
1970 return Error(ArgList[i].Loc,
1971 "argument attributes invalid in function type");
1974 SmallVector<Type*, 16> ArgListTy;
1975 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1976 ArgListTy.push_back(ArgList[i].Ty);
1978 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1982 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1984 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1985 SmallVector<Type*, 8> Elts;
1986 if (ParseStructBody(Elts)) return true;
1988 Result = StructType::get(Context, Elts, Packed);
1992 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1993 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1994 std::pair<Type*, LocTy> &Entry,
1996 // If the type was already defined, diagnose the redefinition.
1997 if (Entry.first && !Entry.second.isValid())
1998 return Error(TypeLoc, "redefinition of type");
2000 // If we have opaque, just return without filling in the definition for the
2001 // struct. This counts as a definition as far as the .ll file goes.
2002 if (EatIfPresent(lltok::kw_opaque)) {
2003 // This type is being defined, so clear the location to indicate this.
2004 Entry.second = SMLoc();
2006 // If this type number has never been uttered, create it.
2008 Entry.first = StructType::create(Context, Name);
2009 ResultTy = Entry.first;
2013 // If the type starts with '<', then it is either a packed struct or a vector.
2014 bool isPacked = EatIfPresent(lltok::less);
2016 // If we don't have a struct, then we have a random type alias, which we
2017 // accept for compatibility with old files. These types are not allowed to be
2018 // forward referenced and not allowed to be recursive.
2019 if (Lex.getKind() != lltok::lbrace) {
2021 return Error(TypeLoc, "forward references to non-struct type");
2025 return ParseArrayVectorType(ResultTy, true);
2026 return ParseType(ResultTy);
2029 // This type is being defined, so clear the location to indicate this.
2030 Entry.second = SMLoc();
2032 // If this type number has never been uttered, create it.
2034 Entry.first = StructType::create(Context, Name);
2036 StructType *STy = cast<StructType>(Entry.first);
2038 SmallVector<Type*, 8> Body;
2039 if (ParseStructBody(Body) ||
2040 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2043 STy->setBody(Body, isPacked);
2049 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2052 /// ::= '{' Type (',' Type)* '}'
2053 /// ::= '<' '{' '}' '>'
2054 /// ::= '<' '{' Type (',' Type)* '}' '>'
2055 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2056 assert(Lex.getKind() == lltok::lbrace);
2057 Lex.Lex(); // Consume the '{'
2059 // Handle the empty struct.
2060 if (EatIfPresent(lltok::rbrace))
2063 LocTy EltTyLoc = Lex.getLoc();
2065 if (ParseType(Ty)) return true;
2068 if (!StructType::isValidElementType(Ty))
2069 return Error(EltTyLoc, "invalid element type for struct");
2071 while (EatIfPresent(lltok::comma)) {
2072 EltTyLoc = Lex.getLoc();
2073 if (ParseType(Ty)) return true;
2075 if (!StructType::isValidElementType(Ty))
2076 return Error(EltTyLoc, "invalid element type for struct");
2081 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2084 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2085 /// token has already been consumed.
2087 /// ::= '[' APSINTVAL 'x' Types ']'
2088 /// ::= '<' APSINTVAL 'x' Types '>'
2089 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2090 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2091 Lex.getAPSIntVal().getBitWidth() > 64)
2092 return TokError("expected number in address space");
2094 LocTy SizeLoc = Lex.getLoc();
2095 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2098 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2101 LocTy TypeLoc = Lex.getLoc();
2102 Type *EltTy = nullptr;
2103 if (ParseType(EltTy)) return true;
2105 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2106 "expected end of sequential type"))
2111 return Error(SizeLoc, "zero element vector is illegal");
2112 if ((unsigned)Size != Size)
2113 return Error(SizeLoc, "size too large for vector");
2114 if (!VectorType::isValidElementType(EltTy))
2115 return Error(TypeLoc, "invalid vector element type");
2116 Result = VectorType::get(EltTy, unsigned(Size));
2118 if (!ArrayType::isValidElementType(EltTy))
2119 return Error(TypeLoc, "invalid array element type");
2120 Result = ArrayType::get(EltTy, Size);
2125 //===----------------------------------------------------------------------===//
2126 // Function Semantic Analysis.
2127 //===----------------------------------------------------------------------===//
2129 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2131 : P(p), F(f), FunctionNumber(functionNumber) {
2133 // Insert unnamed arguments into the NumberedVals list.
2134 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2137 NumberedVals.push_back(AI);
2140 LLParser::PerFunctionState::~PerFunctionState() {
2141 // If there were any forward referenced non-basicblock values, delete them.
2142 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2143 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2144 if (!isa<BasicBlock>(I->second.first)) {
2145 I->second.first->replaceAllUsesWith(
2146 UndefValue::get(I->second.first->getType()));
2147 delete I->second.first;
2148 I->second.first = nullptr;
2151 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2152 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2153 if (!isa<BasicBlock>(I->second.first)) {
2154 I->second.first->replaceAllUsesWith(
2155 UndefValue::get(I->second.first->getType()));
2156 delete I->second.first;
2157 I->second.first = nullptr;
2161 bool LLParser::PerFunctionState::FinishFunction() {
2162 // Check to see if someone took the address of labels in this block.
2163 if (!P.ForwardRefBlockAddresses.empty()) {
2165 if (!F.getName().empty()) {
2166 FunctionID.Kind = ValID::t_GlobalName;
2167 FunctionID.StrVal = F.getName();
2169 FunctionID.Kind = ValID::t_GlobalID;
2170 FunctionID.UIntVal = FunctionNumber;
2173 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2174 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2175 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2176 // Resolve all these references.
2177 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2180 P.ForwardRefBlockAddresses.erase(FRBAI);
2184 if (!ForwardRefVals.empty())
2185 return P.Error(ForwardRefVals.begin()->second.second,
2186 "use of undefined value '%" + ForwardRefVals.begin()->first +
2188 if (!ForwardRefValIDs.empty())
2189 return P.Error(ForwardRefValIDs.begin()->second.second,
2190 "use of undefined value '%" +
2191 Twine(ForwardRefValIDs.begin()->first) + "'");
2196 /// GetVal - Get a value with the specified name or ID, creating a
2197 /// forward reference record if needed. This can return null if the value
2198 /// exists but does not have the right type.
2199 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2200 Type *Ty, LocTy Loc) {
2201 // Look this name up in the normal function symbol table.
2202 Value *Val = F.getValueSymbolTable().lookup(Name);
2204 // If this is a forward reference for the value, see if we already created a
2205 // forward ref record.
2207 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2208 I = ForwardRefVals.find(Name);
2209 if (I != ForwardRefVals.end())
2210 Val = I->second.first;
2213 // If we have the value in the symbol table or fwd-ref table, return it.
2215 if (Val->getType() == Ty) return Val;
2216 if (Ty->isLabelTy())
2217 P.Error(Loc, "'%" + Name + "' is not a basic block");
2219 P.Error(Loc, "'%" + Name + "' defined with type '" +
2220 getTypeString(Val->getType()) + "'");
2224 // Don't make placeholders with invalid type.
2225 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
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(), Name, &F);
2235 FwdVal = new Argument(Ty, Name);
2237 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2241 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2243 // Look this name up in the normal function symbol table.
2244 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2246 // If this is a forward reference for the value, see if we already created a
2247 // forward ref record.
2249 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2250 I = ForwardRefValIDs.find(ID);
2251 if (I != ForwardRefValIDs.end())
2252 Val = I->second.first;
2255 // If we have the value in the symbol table or fwd-ref table, return it.
2257 if (Val->getType() == Ty) return Val;
2258 if (Ty->isLabelTy())
2259 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2261 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2262 getTypeString(Val->getType()) + "'");
2266 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2267 P.Error(Loc, "invalid use of a non-first-class type");
2271 // Otherwise, create a new forward reference for this value and remember it.
2273 if (Ty->isLabelTy())
2274 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2276 FwdVal = new Argument(Ty);
2278 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2282 /// SetInstName - After an instruction is parsed and inserted into its
2283 /// basic block, this installs its name.
2284 bool LLParser::PerFunctionState::SetInstName(int NameID,
2285 const std::string &NameStr,
2286 LocTy NameLoc, Instruction *Inst) {
2287 // If this instruction has void type, it cannot have a name or ID specified.
2288 if (Inst->getType()->isVoidTy()) {
2289 if (NameID != -1 || !NameStr.empty())
2290 return P.Error(NameLoc, "instructions returning void cannot have a name");
2294 // If this was a numbered instruction, verify that the instruction is the
2295 // expected value and resolve any forward references.
2296 if (NameStr.empty()) {
2297 // If neither a name nor an ID was specified, just use the next ID.
2299 NameID = NumberedVals.size();
2301 if (unsigned(NameID) != NumberedVals.size())
2302 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2303 Twine(NumberedVals.size()) + "'");
2305 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2306 ForwardRefValIDs.find(NameID);
2307 if (FI != ForwardRefValIDs.end()) {
2308 if (FI->second.first->getType() != Inst->getType())
2309 return P.Error(NameLoc, "instruction forward referenced with type '" +
2310 getTypeString(FI->second.first->getType()) + "'");
2311 FI->second.first->replaceAllUsesWith(Inst);
2312 delete FI->second.first;
2313 ForwardRefValIDs.erase(FI);
2316 NumberedVals.push_back(Inst);
2320 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2321 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2322 FI = ForwardRefVals.find(NameStr);
2323 if (FI != ForwardRefVals.end()) {
2324 if (FI->second.first->getType() != Inst->getType())
2325 return P.Error(NameLoc, "instruction forward referenced with type '" +
2326 getTypeString(FI->second.first->getType()) + "'");
2327 FI->second.first->replaceAllUsesWith(Inst);
2328 delete FI->second.first;
2329 ForwardRefVals.erase(FI);
2332 // Set the name on the instruction.
2333 Inst->setName(NameStr);
2335 if (Inst->getName() != NameStr)
2336 return P.Error(NameLoc, "multiple definition of local value named '" +
2341 /// GetBB - Get a basic block with the specified name or ID, creating a
2342 /// forward reference record if needed.
2343 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2345 return cast_or_null<BasicBlock>(GetVal(Name,
2346 Type::getLabelTy(F.getContext()), Loc));
2349 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2350 return cast_or_null<BasicBlock>(GetVal(ID,
2351 Type::getLabelTy(F.getContext()), Loc));
2354 /// DefineBB - Define the specified basic block, which is either named or
2355 /// unnamed. If there is an error, this returns null otherwise it returns
2356 /// the block being defined.
2357 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2361 BB = GetBB(NumberedVals.size(), Loc);
2363 BB = GetBB(Name, Loc);
2364 if (!BB) return nullptr; // Already diagnosed error.
2366 // Move the block to the end of the function. Forward ref'd blocks are
2367 // inserted wherever they happen to be referenced.
2368 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2370 // Remove the block from forward ref sets.
2372 ForwardRefValIDs.erase(NumberedVals.size());
2373 NumberedVals.push_back(BB);
2375 // BB forward references are already in the function symbol table.
2376 ForwardRefVals.erase(Name);
2382 //===----------------------------------------------------------------------===//
2384 //===----------------------------------------------------------------------===//
2386 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2387 /// type implied. For example, if we parse "4" we don't know what integer type
2388 /// it has. The value will later be combined with its type and checked for
2389 /// sanity. PFS is used to convert function-local operands of metadata (since
2390 /// metadata operands are not just parsed here but also converted to values).
2391 /// PFS can be null when we are not parsing metadata values inside a function.
2392 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2393 ID.Loc = Lex.getLoc();
2394 switch (Lex.getKind()) {
2395 default: return TokError("expected value token");
2396 case lltok::GlobalID: // @42
2397 ID.UIntVal = Lex.getUIntVal();
2398 ID.Kind = ValID::t_GlobalID;
2400 case lltok::GlobalVar: // @foo
2401 ID.StrVal = Lex.getStrVal();
2402 ID.Kind = ValID::t_GlobalName;
2404 case lltok::LocalVarID: // %42
2405 ID.UIntVal = Lex.getUIntVal();
2406 ID.Kind = ValID::t_LocalID;
2408 case lltok::LocalVar: // %foo
2409 ID.StrVal = Lex.getStrVal();
2410 ID.Kind = ValID::t_LocalName;
2412 case lltok::exclaim: // !42, !{...}, or !"foo"
2413 return ParseMetadataValue(ID, PFS);
2415 ID.APSIntVal = Lex.getAPSIntVal();
2416 ID.Kind = ValID::t_APSInt;
2418 case lltok::APFloat:
2419 ID.APFloatVal = Lex.getAPFloatVal();
2420 ID.Kind = ValID::t_APFloat;
2422 case lltok::kw_true:
2423 ID.ConstantVal = ConstantInt::getTrue(Context);
2424 ID.Kind = ValID::t_Constant;
2426 case lltok::kw_false:
2427 ID.ConstantVal = ConstantInt::getFalse(Context);
2428 ID.Kind = ValID::t_Constant;
2430 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2431 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2432 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2434 case lltok::lbrace: {
2435 // ValID ::= '{' ConstVector '}'
2437 SmallVector<Constant*, 16> Elts;
2438 if (ParseGlobalValueVector(Elts) ||
2439 ParseToken(lltok::rbrace, "expected end of struct constant"))
2442 ID.ConstantStructElts = new Constant*[Elts.size()];
2443 ID.UIntVal = Elts.size();
2444 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2445 ID.Kind = ValID::t_ConstantStruct;
2449 // ValID ::= '<' ConstVector '>' --> Vector.
2450 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2452 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2454 SmallVector<Constant*, 16> Elts;
2455 LocTy FirstEltLoc = Lex.getLoc();
2456 if (ParseGlobalValueVector(Elts) ||
2458 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2459 ParseToken(lltok::greater, "expected end of constant"))
2462 if (isPackedStruct) {
2463 ID.ConstantStructElts = new Constant*[Elts.size()];
2464 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2465 ID.UIntVal = Elts.size();
2466 ID.Kind = ValID::t_PackedConstantStruct;
2471 return Error(ID.Loc, "constant vector must not be empty");
2473 if (!Elts[0]->getType()->isIntegerTy() &&
2474 !Elts[0]->getType()->isFloatingPointTy() &&
2475 !Elts[0]->getType()->isPointerTy())
2476 return Error(FirstEltLoc,
2477 "vector elements must have integer, pointer or floating point type");
2479 // Verify that all the vector elements have the same type.
2480 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2481 if (Elts[i]->getType() != Elts[0]->getType())
2482 return Error(FirstEltLoc,
2483 "vector element #" + Twine(i) +
2484 " is not of type '" + getTypeString(Elts[0]->getType()));
2486 ID.ConstantVal = ConstantVector::get(Elts);
2487 ID.Kind = ValID::t_Constant;
2490 case lltok::lsquare: { // Array Constant
2492 SmallVector<Constant*, 16> Elts;
2493 LocTy FirstEltLoc = Lex.getLoc();
2494 if (ParseGlobalValueVector(Elts) ||
2495 ParseToken(lltok::rsquare, "expected end of array constant"))
2498 // Handle empty element.
2500 // Use undef instead of an array because it's inconvenient to determine
2501 // the element type at this point, there being no elements to examine.
2502 ID.Kind = ValID::t_EmptyArray;
2506 if (!Elts[0]->getType()->isFirstClassType())
2507 return Error(FirstEltLoc, "invalid array element type: " +
2508 getTypeString(Elts[0]->getType()));
2510 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2512 // Verify all elements are correct type!
2513 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2514 if (Elts[i]->getType() != Elts[0]->getType())
2515 return Error(FirstEltLoc,
2516 "array element #" + Twine(i) +
2517 " is not of type '" + getTypeString(Elts[0]->getType()));
2520 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2521 ID.Kind = ValID::t_Constant;
2524 case lltok::kw_c: // c "foo"
2526 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2528 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2529 ID.Kind = ValID::t_Constant;
2532 case lltok::kw_asm: {
2533 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2535 bool HasSideEffect, AlignStack, AsmDialect;
2537 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2538 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2539 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2540 ParseStringConstant(ID.StrVal) ||
2541 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2542 ParseToken(lltok::StringConstant, "expected constraint string"))
2544 ID.StrVal2 = Lex.getStrVal();
2545 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2546 (unsigned(AsmDialect)<<2);
2547 ID.Kind = ValID::t_InlineAsm;
2551 case lltok::kw_blockaddress: {
2552 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2557 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2559 ParseToken(lltok::comma, "expected comma in block address expression")||
2560 ParseValID(Label) ||
2561 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2564 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2565 return Error(Fn.Loc, "expected function name in blockaddress");
2566 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2567 return Error(Label.Loc, "expected basic block name in blockaddress");
2569 // Make a global variable as a placeholder for this reference.
2570 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2571 false, GlobalValue::InternalLinkage,
2573 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2574 ID.ConstantVal = FwdRef;
2575 ID.Kind = ValID::t_Constant;
2579 case lltok::kw_trunc:
2580 case lltok::kw_zext:
2581 case lltok::kw_sext:
2582 case lltok::kw_fptrunc:
2583 case lltok::kw_fpext:
2584 case lltok::kw_bitcast:
2585 case lltok::kw_addrspacecast:
2586 case lltok::kw_uitofp:
2587 case lltok::kw_sitofp:
2588 case lltok::kw_fptoui:
2589 case lltok::kw_fptosi:
2590 case lltok::kw_inttoptr:
2591 case lltok::kw_ptrtoint: {
2592 unsigned Opc = Lex.getUIntVal();
2593 Type *DestTy = nullptr;
2596 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2597 ParseGlobalTypeAndValue(SrcVal) ||
2598 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2599 ParseType(DestTy) ||
2600 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2602 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2603 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2604 getTypeString(SrcVal->getType()) + "' to '" +
2605 getTypeString(DestTy) + "'");
2606 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2608 ID.Kind = ValID::t_Constant;
2611 case lltok::kw_extractvalue: {
2614 SmallVector<unsigned, 4> Indices;
2615 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2616 ParseGlobalTypeAndValue(Val) ||
2617 ParseIndexList(Indices) ||
2618 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2621 if (!Val->getType()->isAggregateType())
2622 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2623 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2624 return Error(ID.Loc, "invalid indices for extractvalue");
2625 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2626 ID.Kind = ValID::t_Constant;
2629 case lltok::kw_insertvalue: {
2631 Constant *Val0, *Val1;
2632 SmallVector<unsigned, 4> Indices;
2633 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2634 ParseGlobalTypeAndValue(Val0) ||
2635 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2636 ParseGlobalTypeAndValue(Val1) ||
2637 ParseIndexList(Indices) ||
2638 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2640 if (!Val0->getType()->isAggregateType())
2641 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2642 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2643 return Error(ID.Loc, "invalid indices for insertvalue");
2644 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2645 ID.Kind = ValID::t_Constant;
2648 case lltok::kw_icmp:
2649 case lltok::kw_fcmp: {
2650 unsigned PredVal, Opc = Lex.getUIntVal();
2651 Constant *Val0, *Val1;
2653 if (ParseCmpPredicate(PredVal, Opc) ||
2654 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2655 ParseGlobalTypeAndValue(Val0) ||
2656 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2657 ParseGlobalTypeAndValue(Val1) ||
2658 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2661 if (Val0->getType() != Val1->getType())
2662 return Error(ID.Loc, "compare operands must have the same type");
2664 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2666 if (Opc == Instruction::FCmp) {
2667 if (!Val0->getType()->isFPOrFPVectorTy())
2668 return Error(ID.Loc, "fcmp requires floating point operands");
2669 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2671 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2672 if (!Val0->getType()->isIntOrIntVectorTy() &&
2673 !Val0->getType()->getScalarType()->isPointerTy())
2674 return Error(ID.Loc, "icmp requires pointer or integer operands");
2675 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2677 ID.Kind = ValID::t_Constant;
2681 // Binary Operators.
2683 case lltok::kw_fadd:
2685 case lltok::kw_fsub:
2687 case lltok::kw_fmul:
2688 case lltok::kw_udiv:
2689 case lltok::kw_sdiv:
2690 case lltok::kw_fdiv:
2691 case lltok::kw_urem:
2692 case lltok::kw_srem:
2693 case lltok::kw_frem:
2695 case lltok::kw_lshr:
2696 case lltok::kw_ashr: {
2700 unsigned Opc = Lex.getUIntVal();
2701 Constant *Val0, *Val1;
2703 LocTy ModifierLoc = Lex.getLoc();
2704 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2705 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2706 if (EatIfPresent(lltok::kw_nuw))
2708 if (EatIfPresent(lltok::kw_nsw)) {
2710 if (EatIfPresent(lltok::kw_nuw))
2713 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2714 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2715 if (EatIfPresent(lltok::kw_exact))
2718 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2719 ParseGlobalTypeAndValue(Val0) ||
2720 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2721 ParseGlobalTypeAndValue(Val1) ||
2722 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2724 if (Val0->getType() != Val1->getType())
2725 return Error(ID.Loc, "operands of constexpr must have same type");
2726 if (!Val0->getType()->isIntOrIntVectorTy()) {
2728 return Error(ModifierLoc, "nuw only applies to integer operations");
2730 return Error(ModifierLoc, "nsw only applies to integer operations");
2732 // Check that the type is valid for the operator.
2734 case Instruction::Add:
2735 case Instruction::Sub:
2736 case Instruction::Mul:
2737 case Instruction::UDiv:
2738 case Instruction::SDiv:
2739 case Instruction::URem:
2740 case Instruction::SRem:
2741 case Instruction::Shl:
2742 case Instruction::AShr:
2743 case Instruction::LShr:
2744 if (!Val0->getType()->isIntOrIntVectorTy())
2745 return Error(ID.Loc, "constexpr requires integer operands");
2747 case Instruction::FAdd:
2748 case Instruction::FSub:
2749 case Instruction::FMul:
2750 case Instruction::FDiv:
2751 case Instruction::FRem:
2752 if (!Val0->getType()->isFPOrFPVectorTy())
2753 return Error(ID.Loc, "constexpr requires fp operands");
2755 default: llvm_unreachable("Unknown binary operator!");
2758 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2759 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2760 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2761 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2763 ID.Kind = ValID::t_Constant;
2767 // Logical Operations
2770 case lltok::kw_xor: {
2771 unsigned Opc = Lex.getUIntVal();
2772 Constant *Val0, *Val1;
2774 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2775 ParseGlobalTypeAndValue(Val0) ||
2776 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2777 ParseGlobalTypeAndValue(Val1) ||
2778 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2780 if (Val0->getType() != Val1->getType())
2781 return Error(ID.Loc, "operands of constexpr must have same type");
2782 if (!Val0->getType()->isIntOrIntVectorTy())
2783 return Error(ID.Loc,
2784 "constexpr requires integer or integer vector operands");
2785 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2786 ID.Kind = ValID::t_Constant;
2790 case lltok::kw_getelementptr:
2791 case lltok::kw_shufflevector:
2792 case lltok::kw_insertelement:
2793 case lltok::kw_extractelement:
2794 case lltok::kw_select: {
2795 unsigned Opc = Lex.getUIntVal();
2796 SmallVector<Constant*, 16> Elts;
2797 bool InBounds = false;
2799 if (Opc == Instruction::GetElementPtr)
2800 InBounds = EatIfPresent(lltok::kw_inbounds);
2801 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2802 ParseGlobalValueVector(Elts) ||
2803 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2806 if (Opc == Instruction::GetElementPtr) {
2807 if (Elts.size() == 0 ||
2808 !Elts[0]->getType()->getScalarType()->isPointerTy())
2809 return Error(ID.Loc, "getelementptr requires pointer operand");
2811 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2812 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2813 return Error(ID.Loc, "invalid indices for getelementptr");
2814 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2816 } else if (Opc == Instruction::Select) {
2817 if (Elts.size() != 3)
2818 return Error(ID.Loc, "expected three operands to select");
2819 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2821 return Error(ID.Loc, Reason);
2822 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2823 } else if (Opc == Instruction::ShuffleVector) {
2824 if (Elts.size() != 3)
2825 return Error(ID.Loc, "expected three operands to shufflevector");
2826 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2827 return Error(ID.Loc, "invalid operands to shufflevector");
2829 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2830 } else if (Opc == Instruction::ExtractElement) {
2831 if (Elts.size() != 2)
2832 return Error(ID.Loc, "expected two operands to extractelement");
2833 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2834 return Error(ID.Loc, "invalid extractelement operands");
2835 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2837 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2838 if (Elts.size() != 3)
2839 return Error(ID.Loc, "expected three operands to insertelement");
2840 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2841 return Error(ID.Loc, "invalid insertelement operands");
2843 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2846 ID.Kind = ValID::t_Constant;
2855 /// ParseGlobalValue - Parse a global value with the specified type.
2856 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2860 bool Parsed = ParseValID(ID) ||
2861 ConvertValIDToValue(Ty, ID, V, nullptr);
2862 if (V && !(C = dyn_cast<Constant>(V)))
2863 return Error(ID.Loc, "global values must be constants");
2867 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2869 return ParseType(Ty) ||
2870 ParseGlobalValue(Ty, V);
2873 bool LLParser::parseOptionalComdat(Comdat *&C) {
2875 if (!EatIfPresent(lltok::kw_comdat))
2877 if (Lex.getKind() != lltok::ComdatVar)
2878 return TokError("expected comdat variable");
2879 LocTy Loc = Lex.getLoc();
2880 StringRef Name = Lex.getStrVal();
2881 C = getComdat(Name, Loc);
2886 /// ParseGlobalValueVector
2888 /// ::= TypeAndValue (',' TypeAndValue)*
2889 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2891 if (Lex.getKind() == lltok::rbrace ||
2892 Lex.getKind() == lltok::rsquare ||
2893 Lex.getKind() == lltok::greater ||
2894 Lex.getKind() == lltok::rparen)
2898 if (ParseGlobalTypeAndValue(C)) return true;
2901 while (EatIfPresent(lltok::comma)) {
2902 if (ParseGlobalTypeAndValue(C)) return true;
2909 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2910 assert(Lex.getKind() == lltok::lbrace);
2913 SmallVector<Value*, 16> Elts;
2914 if (ParseMDNodeVector(Elts, PFS) ||
2915 ParseToken(lltok::rbrace, "expected end of metadata node"))
2918 ID.MDNodeVal = MDNode::get(Context, Elts);
2919 ID.Kind = ValID::t_MDNode;
2923 /// ParseMetadataValue
2927 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2928 assert(Lex.getKind() == lltok::exclaim);
2933 if (Lex.getKind() == lltok::lbrace)
2934 return ParseMetadataListValue(ID, PFS);
2936 // Standalone metadata reference
2938 if (Lex.getKind() == lltok::APSInt) {
2939 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2940 ID.Kind = ValID::t_MDNode;
2945 // ::= '!' STRINGCONSTANT
2946 if (ParseMDString(ID.MDStringVal)) return true;
2947 ID.Kind = ValID::t_MDString;
2952 //===----------------------------------------------------------------------===//
2953 // Function Parsing.
2954 //===----------------------------------------------------------------------===//
2956 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2957 PerFunctionState *PFS) {
2958 if (Ty->isFunctionTy())
2959 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2962 case ValID::t_LocalID:
2963 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2964 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2965 return V == nullptr;
2966 case ValID::t_LocalName:
2967 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2968 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2969 return V == nullptr;
2970 case ValID::t_InlineAsm: {
2971 PointerType *PTy = dyn_cast<PointerType>(Ty);
2973 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2974 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2975 return Error(ID.Loc, "invalid type for inline asm constraint string");
2976 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2977 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2980 case ValID::t_MDNode:
2981 if (!Ty->isMetadataTy())
2982 return Error(ID.Loc, "metadata value must have metadata type");
2985 case ValID::t_MDString:
2986 if (!Ty->isMetadataTy())
2987 return Error(ID.Loc, "metadata value must have metadata type");
2990 case ValID::t_GlobalName:
2991 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2992 return V == nullptr;
2993 case ValID::t_GlobalID:
2994 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2995 return V == nullptr;
2996 case ValID::t_APSInt:
2997 if (!Ty->isIntegerTy())
2998 return Error(ID.Loc, "integer constant must have integer type");
2999 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3000 V = ConstantInt::get(Context, ID.APSIntVal);
3002 case ValID::t_APFloat:
3003 if (!Ty->isFloatingPointTy() ||
3004 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3005 return Error(ID.Loc, "floating point constant invalid for type");
3007 // The lexer has no type info, so builds all half, float, and double FP
3008 // constants as double. Fix this here. Long double does not need this.
3009 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3012 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3014 else if (Ty->isFloatTy())
3015 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3018 V = ConstantFP::get(Context, ID.APFloatVal);
3020 if (V->getType() != Ty)
3021 return Error(ID.Loc, "floating point constant does not have type '" +
3022 getTypeString(Ty) + "'");
3026 if (!Ty->isPointerTy())
3027 return Error(ID.Loc, "null must be a pointer type");
3028 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3030 case ValID::t_Undef:
3031 // FIXME: LabelTy should not be a first-class type.
3032 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3033 return Error(ID.Loc, "invalid type for undef constant");
3034 V = UndefValue::get(Ty);
3036 case ValID::t_EmptyArray:
3037 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3038 return Error(ID.Loc, "invalid empty array initializer");
3039 V = UndefValue::get(Ty);
3042 // FIXME: LabelTy should not be a first-class type.
3043 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3044 return Error(ID.Loc, "invalid type for null constant");
3045 V = Constant::getNullValue(Ty);
3047 case ValID::t_Constant:
3048 if (ID.ConstantVal->getType() != Ty)
3049 return Error(ID.Loc, "constant expression type mismatch");
3053 case ValID::t_ConstantStruct:
3054 case ValID::t_PackedConstantStruct:
3055 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3056 if (ST->getNumElements() != ID.UIntVal)
3057 return Error(ID.Loc,
3058 "initializer with struct type has wrong # elements");
3059 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3060 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3062 // Verify that the elements are compatible with the structtype.
3063 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3064 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3065 return Error(ID.Loc, "element " + Twine(i) +
3066 " of struct initializer doesn't match struct element type");
3068 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3071 return Error(ID.Loc, "constant expression type mismatch");
3074 llvm_unreachable("Invalid ValID");
3077 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3080 return ParseValID(ID, PFS) ||
3081 ConvertValIDToValue(Ty, ID, V, PFS);
3084 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3086 return ParseType(Ty) ||
3087 ParseValue(Ty, V, PFS);
3090 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3091 PerFunctionState &PFS) {
3094 if (ParseTypeAndValue(V, PFS)) return true;
3095 if (!isa<BasicBlock>(V))
3096 return Error(Loc, "expected a basic block");
3097 BB = cast<BasicBlock>(V);
3103 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3104 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3105 /// OptionalAlign OptGC OptionalPrefix
3106 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3107 // Parse the linkage.
3108 LocTy LinkageLoc = Lex.getLoc();
3111 unsigned Visibility;
3112 unsigned DLLStorageClass;
3113 AttrBuilder RetAttrs;
3115 Type *RetType = nullptr;
3116 LocTy RetTypeLoc = Lex.getLoc();
3117 if (ParseOptionalLinkage(Linkage) ||
3118 ParseOptionalVisibility(Visibility) ||
3119 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3120 ParseOptionalCallingConv(CC) ||
3121 ParseOptionalReturnAttrs(RetAttrs) ||
3122 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3125 // Verify that the linkage is ok.
3126 switch ((GlobalValue::LinkageTypes)Linkage) {
3127 case GlobalValue::ExternalLinkage:
3128 break; // always ok.
3129 case GlobalValue::ExternalWeakLinkage:
3131 return Error(LinkageLoc, "invalid linkage for function definition");
3133 case GlobalValue::PrivateLinkage:
3134 case GlobalValue::InternalLinkage:
3135 case GlobalValue::AvailableExternallyLinkage:
3136 case GlobalValue::LinkOnceAnyLinkage:
3137 case GlobalValue::LinkOnceODRLinkage:
3138 case GlobalValue::WeakAnyLinkage:
3139 case GlobalValue::WeakODRLinkage:
3141 return Error(LinkageLoc, "invalid linkage for function declaration");
3143 case GlobalValue::AppendingLinkage:
3144 case GlobalValue::CommonLinkage:
3145 return Error(LinkageLoc, "invalid function linkage type");
3148 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3149 return Error(LinkageLoc,
3150 "symbol with local linkage must have default visibility");
3152 if (!FunctionType::isValidReturnType(RetType))
3153 return Error(RetTypeLoc, "invalid function return type");
3155 LocTy NameLoc = Lex.getLoc();
3157 std::string FunctionName;
3158 if (Lex.getKind() == lltok::GlobalVar) {
3159 FunctionName = Lex.getStrVal();
3160 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3161 unsigned NameID = Lex.getUIntVal();
3163 if (NameID != NumberedVals.size())
3164 return TokError("function expected to be numbered '%" +
3165 Twine(NumberedVals.size()) + "'");
3167 return TokError("expected function name");
3172 if (Lex.getKind() != lltok::lparen)
3173 return TokError("expected '(' in function argument list");
3175 SmallVector<ArgInfo, 8> ArgList;
3177 AttrBuilder FuncAttrs;
3178 std::vector<unsigned> FwdRefAttrGrps;
3180 std::string Section;
3184 LocTy UnnamedAddrLoc;
3185 Constant *Prefix = nullptr;
3188 if (ParseArgumentList(ArgList, isVarArg) ||
3189 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3191 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3193 (EatIfPresent(lltok::kw_section) &&
3194 ParseStringConstant(Section)) ||
3195 parseOptionalComdat(C) ||
3196 ParseOptionalAlignment(Alignment) ||
3197 (EatIfPresent(lltok::kw_gc) &&
3198 ParseStringConstant(GC)) ||
3199 (EatIfPresent(lltok::kw_prefix) &&
3200 ParseGlobalTypeAndValue(Prefix)))
3203 if (FuncAttrs.contains(Attribute::Builtin))
3204 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3206 // If the alignment was parsed as an attribute, move to the alignment field.
3207 if (FuncAttrs.hasAlignmentAttr()) {
3208 Alignment = FuncAttrs.getAlignment();
3209 FuncAttrs.removeAttribute(Attribute::Alignment);
3212 // Okay, if we got here, the function is syntactically valid. Convert types
3213 // and do semantic checks.
3214 std::vector<Type*> ParamTypeList;
3215 SmallVector<AttributeSet, 8> Attrs;
3217 if (RetAttrs.hasAttributes())
3218 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3219 AttributeSet::ReturnIndex,
3222 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3223 ParamTypeList.push_back(ArgList[i].Ty);
3224 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3225 AttrBuilder B(ArgList[i].Attrs, i + 1);
3226 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3230 if (FuncAttrs.hasAttributes())
3231 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3232 AttributeSet::FunctionIndex,
3235 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3237 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3238 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3241 FunctionType::get(RetType, ParamTypeList, isVarArg);
3242 PointerType *PFT = PointerType::getUnqual(FT);
3245 if (!FunctionName.empty()) {
3246 // If this was a definition of a forward reference, remove the definition
3247 // from the forward reference table and fill in the forward ref.
3248 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3249 ForwardRefVals.find(FunctionName);
3250 if (FRVI != ForwardRefVals.end()) {
3251 Fn = M->getFunction(FunctionName);
3253 return Error(FRVI->second.second, "invalid forward reference to "
3254 "function as global value!");
3255 if (Fn->getType() != PFT)
3256 return Error(FRVI->second.second, "invalid forward reference to "
3257 "function '" + FunctionName + "' with wrong type!");
3259 ForwardRefVals.erase(FRVI);
3260 } else if ((Fn = M->getFunction(FunctionName))) {
3261 // Reject redefinitions.
3262 return Error(NameLoc, "invalid redefinition of function '" +
3263 FunctionName + "'");
3264 } else if (M->getNamedValue(FunctionName)) {
3265 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3269 // If this is a definition of a forward referenced function, make sure the
3271 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3272 = ForwardRefValIDs.find(NumberedVals.size());
3273 if (I != ForwardRefValIDs.end()) {
3274 Fn = cast<Function>(I->second.first);
3275 if (Fn->getType() != PFT)
3276 return Error(NameLoc, "type of definition and forward reference of '@" +
3277 Twine(NumberedVals.size()) + "' disagree");
3278 ForwardRefValIDs.erase(I);
3283 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3284 else // Move the forward-reference to the correct spot in the module.
3285 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3287 if (FunctionName.empty())
3288 NumberedVals.push_back(Fn);
3290 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3291 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3292 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3293 Fn->setCallingConv(CC);
3294 Fn->setAttributes(PAL);
3295 Fn->setUnnamedAddr(UnnamedAddr);
3296 Fn->setAlignment(Alignment);
3297 Fn->setSection(Section);
3299 if (!GC.empty()) Fn->setGC(GC.c_str());
3300 Fn->setPrefixData(Prefix);
3301 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3303 // Add all of the arguments we parsed to the function.
3304 Function::arg_iterator ArgIt = Fn->arg_begin();
3305 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3306 // If the argument has a name, insert it into the argument symbol table.
3307 if (ArgList[i].Name.empty()) continue;
3309 // Set the name, if it conflicted, it will be auto-renamed.
3310 ArgIt->setName(ArgList[i].Name);
3312 if (ArgIt->getName() != ArgList[i].Name)
3313 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3314 ArgList[i].Name + "'");
3321 /// ParseFunctionBody
3322 /// ::= '{' BasicBlock+ '}'
3324 bool LLParser::ParseFunctionBody(Function &Fn) {
3325 if (Lex.getKind() != lltok::lbrace)
3326 return TokError("expected '{' in function body");
3327 Lex.Lex(); // eat the {.
3329 int FunctionNumber = -1;
3330 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3332 PerFunctionState PFS(*this, Fn, FunctionNumber);
3334 // We need at least one basic block.
3335 if (Lex.getKind() == lltok::rbrace)
3336 return TokError("function body requires at least one basic block");
3338 while (Lex.getKind() != lltok::rbrace)
3339 if (ParseBasicBlock(PFS)) return true;
3344 // Verify function is ok.
3345 return PFS.FinishFunction();
3349 /// ::= LabelStr? Instruction*
3350 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3351 // If this basic block starts out with a name, remember it.
3353 LocTy NameLoc = Lex.getLoc();
3354 if (Lex.getKind() == lltok::LabelStr) {
3355 Name = Lex.getStrVal();
3359 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3360 if (!BB) return true;
3362 std::string NameStr;
3364 // Parse the instructions in this block until we get a terminator.
3367 // This instruction may have three possibilities for a name: a) none
3368 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3369 LocTy NameLoc = Lex.getLoc();
3373 if (Lex.getKind() == lltok::LocalVarID) {
3374 NameID = Lex.getUIntVal();
3376 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3378 } else if (Lex.getKind() == lltok::LocalVar) {
3379 NameStr = Lex.getStrVal();
3381 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3385 switch (ParseInstruction(Inst, BB, PFS)) {
3386 default: llvm_unreachable("Unknown ParseInstruction result!");
3387 case InstError: return true;
3389 BB->getInstList().push_back(Inst);
3391 // With a normal result, we check to see if the instruction is followed by
3392 // a comma and metadata.
3393 if (EatIfPresent(lltok::comma))
3394 if (ParseInstructionMetadata(Inst, &PFS))
3397 case InstExtraComma:
3398 BB->getInstList().push_back(Inst);
3400 // If the instruction parser ate an extra comma at the end of it, it
3401 // *must* be followed by metadata.
3402 if (ParseInstructionMetadata(Inst, &PFS))
3407 // Set the name on the instruction.
3408 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3409 } while (!isa<TerminatorInst>(Inst));
3414 //===----------------------------------------------------------------------===//
3415 // Instruction Parsing.
3416 //===----------------------------------------------------------------------===//
3418 /// ParseInstruction - Parse one of the many different instructions.
3420 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3421 PerFunctionState &PFS) {
3422 lltok::Kind Token = Lex.getKind();
3423 if (Token == lltok::Eof)
3424 return TokError("found end of file when expecting more instructions");
3425 LocTy Loc = Lex.getLoc();
3426 unsigned KeywordVal = Lex.getUIntVal();
3427 Lex.Lex(); // Eat the keyword.
3430 default: return Error(Loc, "expected instruction opcode");
3431 // Terminator Instructions.
3432 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3433 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3434 case lltok::kw_br: return ParseBr(Inst, PFS);
3435 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3436 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3437 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3438 case lltok::kw_resume: return ParseResume(Inst, PFS);
3439 // Binary Operators.
3443 case lltok::kw_shl: {
3444 bool NUW = EatIfPresent(lltok::kw_nuw);
3445 bool NSW = EatIfPresent(lltok::kw_nsw);
3446 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3448 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3450 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3451 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3454 case lltok::kw_fadd:
3455 case lltok::kw_fsub:
3456 case lltok::kw_fmul:
3457 case lltok::kw_fdiv:
3458 case lltok::kw_frem: {
3459 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3460 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3464 Inst->setFastMathFlags(FMF);
3468 case lltok::kw_sdiv:
3469 case lltok::kw_udiv:
3470 case lltok::kw_lshr:
3471 case lltok::kw_ashr: {
3472 bool Exact = EatIfPresent(lltok::kw_exact);
3474 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3475 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3479 case lltok::kw_urem:
3480 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3483 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3484 case lltok::kw_icmp:
3485 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3487 case lltok::kw_trunc:
3488 case lltok::kw_zext:
3489 case lltok::kw_sext:
3490 case lltok::kw_fptrunc:
3491 case lltok::kw_fpext:
3492 case lltok::kw_bitcast:
3493 case lltok::kw_addrspacecast:
3494 case lltok::kw_uitofp:
3495 case lltok::kw_sitofp:
3496 case lltok::kw_fptoui:
3497 case lltok::kw_fptosi:
3498 case lltok::kw_inttoptr:
3499 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3501 case lltok::kw_select: return ParseSelect(Inst, PFS);
3502 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3503 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3504 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3505 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3506 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3507 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3509 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3510 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3511 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3513 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3514 case lltok::kw_load: return ParseLoad(Inst, PFS);
3515 case lltok::kw_store: return ParseStore(Inst, PFS);
3516 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3517 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3518 case lltok::kw_fence: return ParseFence(Inst, PFS);
3519 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3520 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3521 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3525 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3526 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3527 if (Opc == Instruction::FCmp) {
3528 switch (Lex.getKind()) {
3529 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3530 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3531 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3532 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3533 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3534 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3535 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3536 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3537 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3538 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3539 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3540 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3541 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3542 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3543 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3544 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3545 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3548 switch (Lex.getKind()) {
3549 default: return TokError("expected icmp predicate (e.g. 'eq')");
3550 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3551 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3552 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3553 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3554 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3555 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3556 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3557 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3558 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3559 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3566 //===----------------------------------------------------------------------===//
3567 // Terminator Instructions.
3568 //===----------------------------------------------------------------------===//
3570 /// ParseRet - Parse a return instruction.
3571 /// ::= 'ret' void (',' !dbg, !1)*
3572 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3573 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3574 PerFunctionState &PFS) {
3575 SMLoc TypeLoc = Lex.getLoc();
3577 if (ParseType(Ty, true /*void allowed*/)) return true;
3579 Type *ResType = PFS.getFunction().getReturnType();
3581 if (Ty->isVoidTy()) {
3582 if (!ResType->isVoidTy())
3583 return Error(TypeLoc, "value doesn't match function result type '" +
3584 getTypeString(ResType) + "'");
3586 Inst = ReturnInst::Create(Context);
3591 if (ParseValue(Ty, RV, PFS)) return true;
3593 if (ResType != RV->getType())
3594 return Error(TypeLoc, "value doesn't match function result type '" +
3595 getTypeString(ResType) + "'");
3597 Inst = ReturnInst::Create(Context, RV);
3603 /// ::= 'br' TypeAndValue
3604 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3605 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3608 BasicBlock *Op1, *Op2;
3609 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3611 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3612 Inst = BranchInst::Create(BB);
3616 if (Op0->getType() != Type::getInt1Ty(Context))
3617 return Error(Loc, "branch condition must have 'i1' type");
3619 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3620 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3621 ParseToken(lltok::comma, "expected ',' after true destination") ||
3622 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3625 Inst = BranchInst::Create(Op1, Op2, Op0);
3631 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3633 /// ::= (TypeAndValue ',' TypeAndValue)*
3634 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3635 LocTy CondLoc, BBLoc;
3637 BasicBlock *DefaultBB;
3638 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3639 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3640 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3641 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3644 if (!Cond->getType()->isIntegerTy())
3645 return Error(CondLoc, "switch condition must have integer type");
3647 // Parse the jump table pairs.
3648 SmallPtrSet<Value*, 32> SeenCases;
3649 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3650 while (Lex.getKind() != lltok::rsquare) {
3654 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3655 ParseToken(lltok::comma, "expected ',' after case value") ||
3656 ParseTypeAndBasicBlock(DestBB, PFS))
3659 if (!SeenCases.insert(Constant))
3660 return Error(CondLoc, "duplicate case value in switch");
3661 if (!isa<ConstantInt>(Constant))
3662 return Error(CondLoc, "case value is not a constant integer");
3664 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3667 Lex.Lex(); // Eat the ']'.
3669 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3670 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3671 SI->addCase(Table[i].first, Table[i].second);
3678 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3679 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3682 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3683 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3684 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3687 if (!Address->getType()->isPointerTy())
3688 return Error(AddrLoc, "indirectbr address must have pointer type");
3690 // Parse the destination list.
3691 SmallVector<BasicBlock*, 16> DestList;
3693 if (Lex.getKind() != lltok::rsquare) {
3695 if (ParseTypeAndBasicBlock(DestBB, PFS))
3697 DestList.push_back(DestBB);
3699 while (EatIfPresent(lltok::comma)) {
3700 if (ParseTypeAndBasicBlock(DestBB, PFS))
3702 DestList.push_back(DestBB);
3706 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3709 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3710 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3711 IBI->addDestination(DestList[i]);
3718 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3719 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3720 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3721 LocTy CallLoc = Lex.getLoc();
3722 AttrBuilder RetAttrs, FnAttrs;
3723 std::vector<unsigned> FwdRefAttrGrps;
3726 Type *RetType = nullptr;
3729 SmallVector<ParamInfo, 16> ArgList;
3731 BasicBlock *NormalBB, *UnwindBB;
3732 if (ParseOptionalCallingConv(CC) ||
3733 ParseOptionalReturnAttrs(RetAttrs) ||
3734 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3735 ParseValID(CalleeID) ||
3736 ParseParameterList(ArgList, PFS) ||
3737 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3739 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3740 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3741 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3742 ParseTypeAndBasicBlock(UnwindBB, PFS))
3745 // If RetType is a non-function pointer type, then this is the short syntax
3746 // for the call, which means that RetType is just the return type. Infer the
3747 // rest of the function argument types from the arguments that are present.
3748 PointerType *PFTy = nullptr;
3749 FunctionType *Ty = nullptr;
3750 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3751 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3752 // Pull out the types of all of the arguments...
3753 std::vector<Type*> ParamTypes;
3754 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3755 ParamTypes.push_back(ArgList[i].V->getType());
3757 if (!FunctionType::isValidReturnType(RetType))
3758 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3760 Ty = FunctionType::get(RetType, ParamTypes, false);
3761 PFTy = PointerType::getUnqual(Ty);
3764 // Look up the callee.
3766 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3768 // Set up the Attribute for the function.
3769 SmallVector<AttributeSet, 8> Attrs;
3770 if (RetAttrs.hasAttributes())
3771 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3772 AttributeSet::ReturnIndex,
3775 SmallVector<Value*, 8> Args;
3777 // Loop through FunctionType's arguments and ensure they are specified
3778 // correctly. Also, gather any parameter attributes.
3779 FunctionType::param_iterator I = Ty->param_begin();
3780 FunctionType::param_iterator E = Ty->param_end();
3781 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3782 Type *ExpectedTy = nullptr;
3785 } else if (!Ty->isVarArg()) {
3786 return Error(ArgList[i].Loc, "too many arguments specified");
3789 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3790 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3791 getTypeString(ExpectedTy) + "'");
3792 Args.push_back(ArgList[i].V);
3793 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3794 AttrBuilder B(ArgList[i].Attrs, i + 1);
3795 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3800 return Error(CallLoc, "not enough parameters specified for call");
3802 if (FnAttrs.hasAttributes())
3803 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3804 AttributeSet::FunctionIndex,
3807 // Finish off the Attribute and check them
3808 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3810 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3811 II->setCallingConv(CC);
3812 II->setAttributes(PAL);
3813 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3819 /// ::= 'resume' TypeAndValue
3820 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3821 Value *Exn; LocTy ExnLoc;
3822 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3825 ResumeInst *RI = ResumeInst::Create(Exn);
3830 //===----------------------------------------------------------------------===//
3831 // Binary Operators.
3832 //===----------------------------------------------------------------------===//
3835 /// ::= ArithmeticOps TypeAndValue ',' Value
3837 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3838 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3839 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3840 unsigned Opc, unsigned OperandType) {
3841 LocTy Loc; Value *LHS, *RHS;
3842 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3843 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3844 ParseValue(LHS->getType(), RHS, PFS))
3848 switch (OperandType) {
3849 default: llvm_unreachable("Unknown operand type!");
3850 case 0: // int or FP.
3851 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3852 LHS->getType()->isFPOrFPVectorTy();
3854 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3855 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3859 return Error(Loc, "invalid operand type for instruction");
3861 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3866 /// ::= ArithmeticOps TypeAndValue ',' Value {
3867 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3869 LocTy Loc; Value *LHS, *RHS;
3870 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3871 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3872 ParseValue(LHS->getType(), RHS, PFS))
3875 if (!LHS->getType()->isIntOrIntVectorTy())
3876 return Error(Loc,"instruction requires integer or integer vector operands");
3878 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3884 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3885 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3886 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3888 // Parse the integer/fp comparison predicate.
3892 if (ParseCmpPredicate(Pred, Opc) ||
3893 ParseTypeAndValue(LHS, Loc, PFS) ||
3894 ParseToken(lltok::comma, "expected ',' after compare value") ||
3895 ParseValue(LHS->getType(), RHS, PFS))
3898 if (Opc == Instruction::FCmp) {
3899 if (!LHS->getType()->isFPOrFPVectorTy())
3900 return Error(Loc, "fcmp requires floating point operands");
3901 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3903 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3904 if (!LHS->getType()->isIntOrIntVectorTy() &&
3905 !LHS->getType()->getScalarType()->isPointerTy())
3906 return Error(Loc, "icmp requires integer operands");
3907 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3912 //===----------------------------------------------------------------------===//
3913 // Other Instructions.
3914 //===----------------------------------------------------------------------===//
3918 /// ::= CastOpc TypeAndValue 'to' Type
3919 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3923 Type *DestTy = nullptr;
3924 if (ParseTypeAndValue(Op, Loc, PFS) ||
3925 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3929 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3930 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3931 return Error(Loc, "invalid cast opcode for cast from '" +
3932 getTypeString(Op->getType()) + "' to '" +
3933 getTypeString(DestTy) + "'");
3935 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3940 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3941 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3943 Value *Op0, *Op1, *Op2;
3944 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3945 ParseToken(lltok::comma, "expected ',' after select condition") ||
3946 ParseTypeAndValue(Op1, PFS) ||
3947 ParseToken(lltok::comma, "expected ',' after select value") ||
3948 ParseTypeAndValue(Op2, PFS))
3951 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3952 return Error(Loc, Reason);
3954 Inst = SelectInst::Create(Op0, Op1, Op2);
3959 /// ::= 'va_arg' TypeAndValue ',' Type
3960 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3962 Type *EltTy = nullptr;
3964 if (ParseTypeAndValue(Op, PFS) ||
3965 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3966 ParseType(EltTy, TypeLoc))
3969 if (!EltTy->isFirstClassType())
3970 return Error(TypeLoc, "va_arg requires operand with first class type");
3972 Inst = new VAArgInst(Op, EltTy);
3976 /// ParseExtractElement
3977 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3978 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3981 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3982 ParseToken(lltok::comma, "expected ',' after extract value") ||
3983 ParseTypeAndValue(Op1, PFS))
3986 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3987 return Error(Loc, "invalid extractelement operands");
3989 Inst = ExtractElementInst::Create(Op0, Op1);
3993 /// ParseInsertElement
3994 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3995 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3997 Value *Op0, *Op1, *Op2;
3998 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3999 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4000 ParseTypeAndValue(Op1, PFS) ||
4001 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4002 ParseTypeAndValue(Op2, PFS))
4005 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4006 return Error(Loc, "invalid insertelement operands");
4008 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4012 /// ParseShuffleVector
4013 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4014 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4016 Value *Op0, *Op1, *Op2;
4017 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4018 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4019 ParseTypeAndValue(Op1, PFS) ||
4020 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4021 ParseTypeAndValue(Op2, PFS))
4024 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4025 return Error(Loc, "invalid shufflevector operands");
4027 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4032 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4033 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4034 Type *Ty = nullptr; LocTy TypeLoc;
4037 if (ParseType(Ty, TypeLoc) ||
4038 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4039 ParseValue(Ty, Op0, PFS) ||
4040 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4041 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4042 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4045 bool AteExtraComma = false;
4046 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4048 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4050 if (!EatIfPresent(lltok::comma))
4053 if (Lex.getKind() == lltok::MetadataVar) {
4054 AteExtraComma = true;
4058 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4059 ParseValue(Ty, Op0, PFS) ||
4060 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4061 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4062 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4066 if (!Ty->isFirstClassType())
4067 return Error(TypeLoc, "phi node must have first class type");
4069 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4070 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4071 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4073 return AteExtraComma ? InstExtraComma : InstNormal;
4077 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4079 /// ::= 'catch' TypeAndValue
4081 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4082 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4083 Type *Ty = nullptr; LocTy TyLoc;
4084 Value *PersFn; LocTy PersFnLoc;
4086 if (ParseType(Ty, TyLoc) ||
4087 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4088 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4091 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4092 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4094 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4095 LandingPadInst::ClauseType CT;
4096 if (EatIfPresent(lltok::kw_catch))
4097 CT = LandingPadInst::Catch;
4098 else if (EatIfPresent(lltok::kw_filter))
4099 CT = LandingPadInst::Filter;
4101 return TokError("expected 'catch' or 'filter' clause type");
4105 if (ParseTypeAndValue(V, VLoc, PFS)) {
4110 // A 'catch' type expects a non-array constant. A filter clause expects an
4112 if (CT == LandingPadInst::Catch) {
4113 if (isa<ArrayType>(V->getType()))
4114 Error(VLoc, "'catch' clause has an invalid type");
4116 if (!isa<ArrayType>(V->getType()))
4117 Error(VLoc, "'filter' clause has an invalid type");
4120 LP->addClause(cast<Constant>(V));
4128 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4129 /// ParameterList OptionalAttrs
4130 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4131 /// ParameterList OptionalAttrs
4132 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4133 /// ParameterList OptionalAttrs
4134 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4135 CallInst::TailCallKind TCK) {
4136 AttrBuilder RetAttrs, FnAttrs;
4137 std::vector<unsigned> FwdRefAttrGrps;
4140 Type *RetType = nullptr;
4143 SmallVector<ParamInfo, 16> ArgList;
4144 LocTy CallLoc = Lex.getLoc();
4146 if ((TCK != CallInst::TCK_None &&
4147 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4148 ParseOptionalCallingConv(CC) ||
4149 ParseOptionalReturnAttrs(RetAttrs) ||
4150 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4151 ParseValID(CalleeID) ||
4152 ParseParameterList(ArgList, PFS) ||
4153 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4157 // If RetType is a non-function pointer type, then this is the short syntax
4158 // for the call, which means that RetType is just the return type. Infer the
4159 // rest of the function argument types from the arguments that are present.
4160 PointerType *PFTy = nullptr;
4161 FunctionType *Ty = nullptr;
4162 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4163 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4164 // Pull out the types of all of the arguments...
4165 std::vector<Type*> ParamTypes;
4166 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4167 ParamTypes.push_back(ArgList[i].V->getType());
4169 if (!FunctionType::isValidReturnType(RetType))
4170 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4172 Ty = FunctionType::get(RetType, ParamTypes, false);
4173 PFTy = PointerType::getUnqual(Ty);
4176 // Look up the callee.
4178 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4180 // Set up the Attribute for the function.
4181 SmallVector<AttributeSet, 8> Attrs;
4182 if (RetAttrs.hasAttributes())
4183 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4184 AttributeSet::ReturnIndex,
4187 SmallVector<Value*, 8> Args;
4189 // Loop through FunctionType's arguments and ensure they are specified
4190 // correctly. Also, gather any parameter attributes.
4191 FunctionType::param_iterator I = Ty->param_begin();
4192 FunctionType::param_iterator E = Ty->param_end();
4193 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4194 Type *ExpectedTy = nullptr;
4197 } else if (!Ty->isVarArg()) {
4198 return Error(ArgList[i].Loc, "too many arguments specified");
4201 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4202 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4203 getTypeString(ExpectedTy) + "'");
4204 Args.push_back(ArgList[i].V);
4205 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4206 AttrBuilder B(ArgList[i].Attrs, i + 1);
4207 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4212 return Error(CallLoc, "not enough parameters specified for call");
4214 if (FnAttrs.hasAttributes())
4215 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4216 AttributeSet::FunctionIndex,
4219 // Finish off the Attribute and check them
4220 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4222 CallInst *CI = CallInst::Create(Callee, Args);
4223 CI->setTailCallKind(TCK);
4224 CI->setCallingConv(CC);
4225 CI->setAttributes(PAL);
4226 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4231 //===----------------------------------------------------------------------===//
4232 // Memory Instructions.
4233 //===----------------------------------------------------------------------===//
4236 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4237 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4238 Value *Size = nullptr;
4240 unsigned Alignment = 0;
4243 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4245 if (ParseType(Ty)) return true;
4247 bool AteExtraComma = false;
4248 if (EatIfPresent(lltok::comma)) {
4249 if (Lex.getKind() == lltok::kw_align) {
4250 if (ParseOptionalAlignment(Alignment)) return true;
4251 } else if (Lex.getKind() == lltok::MetadataVar) {
4252 AteExtraComma = true;
4254 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4255 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4260 if (Size && !Size->getType()->isIntegerTy())
4261 return Error(SizeLoc, "element count must have integer type");
4263 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4264 AI->setUsedWithInAlloca(IsInAlloca);
4266 return AteExtraComma ? InstExtraComma : InstNormal;
4270 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4271 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4272 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4273 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4274 Value *Val; LocTy Loc;
4275 unsigned Alignment = 0;
4276 bool AteExtraComma = false;
4277 bool isAtomic = false;
4278 AtomicOrdering Ordering = NotAtomic;
4279 SynchronizationScope Scope = CrossThread;
4281 if (Lex.getKind() == lltok::kw_atomic) {
4286 bool isVolatile = false;
4287 if (Lex.getKind() == lltok::kw_volatile) {
4292 if (ParseTypeAndValue(Val, Loc, PFS) ||
4293 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4294 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4297 if (!Val->getType()->isPointerTy() ||
4298 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4299 return Error(Loc, "load operand must be a pointer to a first class type");
4300 if (isAtomic && !Alignment)
4301 return Error(Loc, "atomic load must have explicit non-zero alignment");
4302 if (Ordering == Release || Ordering == AcquireRelease)
4303 return Error(Loc, "atomic load cannot use Release ordering");
4305 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4306 return AteExtraComma ? InstExtraComma : InstNormal;
4311 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4312 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4313 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4314 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4315 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4316 unsigned Alignment = 0;
4317 bool AteExtraComma = false;
4318 bool isAtomic = false;
4319 AtomicOrdering Ordering = NotAtomic;
4320 SynchronizationScope Scope = CrossThread;
4322 if (Lex.getKind() == lltok::kw_atomic) {
4327 bool isVolatile = false;
4328 if (Lex.getKind() == lltok::kw_volatile) {
4333 if (ParseTypeAndValue(Val, Loc, PFS) ||
4334 ParseToken(lltok::comma, "expected ',' after store operand") ||
4335 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4336 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4337 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4340 if (!Ptr->getType()->isPointerTy())
4341 return Error(PtrLoc, "store operand must be a pointer");
4342 if (!Val->getType()->isFirstClassType())
4343 return Error(Loc, "store operand must be a first class value");
4344 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4345 return Error(Loc, "stored value and pointer type do not match");
4346 if (isAtomic && !Alignment)
4347 return Error(Loc, "atomic store must have explicit non-zero alignment");
4348 if (Ordering == Acquire || Ordering == AcquireRelease)
4349 return Error(Loc, "atomic store cannot use Acquire ordering");
4351 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4352 return AteExtraComma ? InstExtraComma : InstNormal;
4356 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4357 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4358 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4359 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4360 bool AteExtraComma = false;
4361 AtomicOrdering SuccessOrdering = NotAtomic;
4362 AtomicOrdering FailureOrdering = NotAtomic;
4363 SynchronizationScope Scope = CrossThread;
4364 bool isVolatile = false;
4365 bool isWeak = false;
4367 if (EatIfPresent(lltok::kw_weak))
4370 if (EatIfPresent(lltok::kw_volatile))
4373 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4374 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4375 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4376 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4377 ParseTypeAndValue(New, NewLoc, PFS) ||
4378 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4379 ParseOrdering(FailureOrdering))
4382 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4383 return TokError("cmpxchg cannot be unordered");
4384 if (SuccessOrdering < FailureOrdering)
4385 return TokError("cmpxchg must be at least as ordered on success as failure");
4386 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4387 return TokError("cmpxchg failure ordering cannot include release semantics");
4388 if (!Ptr->getType()->isPointerTy())
4389 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4390 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4391 return Error(CmpLoc, "compare value and pointer type do not match");
4392 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4393 return Error(NewLoc, "new value and pointer type do not match");
4394 if (!New->getType()->isIntegerTy())
4395 return Error(NewLoc, "cmpxchg operand must be an integer");
4396 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4397 if (Size < 8 || (Size & (Size - 1)))
4398 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4401 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4402 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4403 CXI->setVolatile(isVolatile);
4404 CXI->setWeak(isWeak);
4406 return AteExtraComma ? InstExtraComma : InstNormal;
4410 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4411 /// 'singlethread'? AtomicOrdering
4412 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4413 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4414 bool AteExtraComma = false;
4415 AtomicOrdering Ordering = NotAtomic;
4416 SynchronizationScope Scope = CrossThread;
4417 bool isVolatile = false;
4418 AtomicRMWInst::BinOp Operation;
4420 if (EatIfPresent(lltok::kw_volatile))
4423 switch (Lex.getKind()) {
4424 default: return TokError("expected binary operation in atomicrmw");
4425 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4426 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4427 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4428 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4429 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4430 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4431 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4432 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4433 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4434 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4435 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4437 Lex.Lex(); // Eat the operation.
4439 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4440 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4441 ParseTypeAndValue(Val, ValLoc, PFS) ||
4442 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4445 if (Ordering == Unordered)
4446 return TokError("atomicrmw cannot be unordered");
4447 if (!Ptr->getType()->isPointerTy())
4448 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4449 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4450 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4451 if (!Val->getType()->isIntegerTy())
4452 return Error(ValLoc, "atomicrmw operand must be an integer");
4453 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4454 if (Size < 8 || (Size & (Size - 1)))
4455 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4458 AtomicRMWInst *RMWI =
4459 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4460 RMWI->setVolatile(isVolatile);
4462 return AteExtraComma ? InstExtraComma : InstNormal;
4466 /// ::= 'fence' 'singlethread'? AtomicOrdering
4467 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4468 AtomicOrdering Ordering = NotAtomic;
4469 SynchronizationScope Scope = CrossThread;
4470 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4473 if (Ordering == Unordered)
4474 return TokError("fence cannot be unordered");
4475 if (Ordering == Monotonic)
4476 return TokError("fence cannot be monotonic");
4478 Inst = new FenceInst(Context, Ordering, Scope);
4482 /// ParseGetElementPtr
4483 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4484 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4485 Value *Ptr = nullptr;
4486 Value *Val = nullptr;
4489 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4491 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4493 Type *BaseType = Ptr->getType();
4494 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4495 if (!BasePointerType)
4496 return Error(Loc, "base of getelementptr must be a pointer");
4498 SmallVector<Value*, 16> Indices;
4499 bool AteExtraComma = false;
4500 while (EatIfPresent(lltok::comma)) {
4501 if (Lex.getKind() == lltok::MetadataVar) {
4502 AteExtraComma = true;
4505 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4506 if (!Val->getType()->getScalarType()->isIntegerTy())
4507 return Error(EltLoc, "getelementptr index must be an integer");
4508 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4509 return Error(EltLoc, "getelementptr index type missmatch");
4510 if (Val->getType()->isVectorTy()) {
4511 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4512 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4513 if (ValNumEl != PtrNumEl)
4514 return Error(EltLoc,
4515 "getelementptr vector index has a wrong number of elements");
4517 Indices.push_back(Val);
4520 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4521 return Error(Loc, "base element of getelementptr must be sized");
4523 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4524 return Error(Loc, "invalid getelementptr indices");
4525 Inst = GetElementPtrInst::Create(Ptr, Indices);
4527 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4528 return AteExtraComma ? InstExtraComma : InstNormal;
4531 /// ParseExtractValue
4532 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4533 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4534 Value *Val; LocTy Loc;
4535 SmallVector<unsigned, 4> Indices;
4537 if (ParseTypeAndValue(Val, Loc, PFS) ||
4538 ParseIndexList(Indices, AteExtraComma))
4541 if (!Val->getType()->isAggregateType())
4542 return Error(Loc, "extractvalue operand must be aggregate type");
4544 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4545 return Error(Loc, "invalid indices for extractvalue");
4546 Inst = ExtractValueInst::Create(Val, Indices);
4547 return AteExtraComma ? InstExtraComma : InstNormal;
4550 /// ParseInsertValue
4551 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4552 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4553 Value *Val0, *Val1; LocTy Loc0, Loc1;
4554 SmallVector<unsigned, 4> Indices;
4556 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4557 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4558 ParseTypeAndValue(Val1, Loc1, PFS) ||
4559 ParseIndexList(Indices, AteExtraComma))
4562 if (!Val0->getType()->isAggregateType())
4563 return Error(Loc0, "insertvalue operand must be aggregate type");
4565 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4566 return Error(Loc0, "invalid indices for insertvalue");
4567 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4568 return AteExtraComma ? InstExtraComma : InstNormal;
4571 //===----------------------------------------------------------------------===//
4572 // Embedded metadata.
4573 //===----------------------------------------------------------------------===//
4575 /// ParseMDNodeVector
4576 /// ::= Element (',' Element)*
4578 /// ::= 'null' | TypeAndValue
4579 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4580 PerFunctionState *PFS) {
4581 // Check for an empty list.
4582 if (Lex.getKind() == lltok::rbrace)
4586 // Null is a special case since it is typeless.
4587 if (EatIfPresent(lltok::kw_null)) {
4588 Elts.push_back(nullptr);
4593 if (ParseTypeAndValue(V, PFS)) return true;
4595 } while (EatIfPresent(lltok::comma));