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_dereferenceable:
1056 case lltok::kw_inalloca:
1057 case lltok::kw_nest:
1058 case lltok::kw_noalias:
1059 case lltok::kw_nocapture:
1060 case lltok::kw_nonnull:
1061 case lltok::kw_returned:
1062 case lltok::kw_sret:
1065 "invalid use of parameter-only attribute on a function");
1073 //===----------------------------------------------------------------------===//
1074 // GlobalValue Reference/Resolution Routines.
1075 //===----------------------------------------------------------------------===//
1077 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1078 /// forward reference record if needed. This can return null if the value
1079 /// exists but does not have the right type.
1080 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1082 PointerType *PTy = dyn_cast<PointerType>(Ty);
1084 Error(Loc, "global variable reference must have pointer type");
1088 // Look this name up in the normal function symbol table.
1090 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1092 // If this is a forward reference for the value, see if we already created a
1093 // forward ref record.
1095 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1096 I = ForwardRefVals.find(Name);
1097 if (I != ForwardRefVals.end())
1098 Val = I->second.first;
1101 // If we have the value in the symbol table or fwd-ref table, return it.
1103 if (Val->getType() == Ty) return Val;
1104 Error(Loc, "'@" + Name + "' defined with type '" +
1105 getTypeString(Val->getType()) + "'");
1109 // Otherwise, create a new forward reference for this value and remember it.
1110 GlobalValue *FwdVal;
1111 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1112 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1114 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1115 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1116 nullptr, GlobalVariable::NotThreadLocal,
1117 PTy->getAddressSpace());
1119 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1123 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1124 PointerType *PTy = dyn_cast<PointerType>(Ty);
1126 Error(Loc, "global variable reference must have pointer type");
1130 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1132 // If this is a forward reference for the value, see if we already created a
1133 // forward ref record.
1135 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1136 I = ForwardRefValIDs.find(ID);
1137 if (I != ForwardRefValIDs.end())
1138 Val = I->second.first;
1141 // If we have the value in the symbol table or fwd-ref table, return it.
1143 if (Val->getType() == Ty) return Val;
1144 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1145 getTypeString(Val->getType()) + "'");
1149 // Otherwise, create a new forward reference for this value and remember it.
1150 GlobalValue *FwdVal;
1151 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1152 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1154 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1155 GlobalValue::ExternalWeakLinkage, nullptr, "");
1157 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1162 //===----------------------------------------------------------------------===//
1163 // Comdat Reference/Resolution Routines.
1164 //===----------------------------------------------------------------------===//
1166 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1167 // Look this name up in the comdat symbol table.
1168 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1169 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1170 if (I != ComdatSymTab.end())
1173 // Otherwise, create a new forward reference for this value and remember it.
1174 Comdat *C = M->getOrInsertComdat(Name);
1175 ForwardRefComdats[Name] = Loc;
1180 //===----------------------------------------------------------------------===//
1182 //===----------------------------------------------------------------------===//
1184 /// ParseToken - If the current token has the specified kind, eat it and return
1185 /// success. Otherwise, emit the specified error and return failure.
1186 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1187 if (Lex.getKind() != T)
1188 return TokError(ErrMsg);
1193 /// ParseStringConstant
1194 /// ::= StringConstant
1195 bool LLParser::ParseStringConstant(std::string &Result) {
1196 if (Lex.getKind() != lltok::StringConstant)
1197 return TokError("expected string constant");
1198 Result = Lex.getStrVal();
1205 bool LLParser::ParseUInt32(unsigned &Val) {
1206 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1207 return TokError("expected integer");
1208 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1209 if (Val64 != unsigned(Val64))
1210 return TokError("expected 32-bit integer (too large)");
1218 bool LLParser::ParseUInt64(uint64_t &Val) {
1219 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1220 return TokError("expected integer");
1221 Val = Lex.getAPSIntVal().getLimitedValue();
1227 /// := 'localdynamic'
1228 /// := 'initialexec'
1230 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1231 switch (Lex.getKind()) {
1233 return TokError("expected localdynamic, initialexec or localexec");
1234 case lltok::kw_localdynamic:
1235 TLM = GlobalVariable::LocalDynamicTLSModel;
1237 case lltok::kw_initialexec:
1238 TLM = GlobalVariable::InitialExecTLSModel;
1240 case lltok::kw_localexec:
1241 TLM = GlobalVariable::LocalExecTLSModel;
1249 /// ParseOptionalThreadLocal
1251 /// := 'thread_local'
1252 /// := 'thread_local' '(' tlsmodel ')'
1253 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1254 TLM = GlobalVariable::NotThreadLocal;
1255 if (!EatIfPresent(lltok::kw_thread_local))
1258 TLM = GlobalVariable::GeneralDynamicTLSModel;
1259 if (Lex.getKind() == lltok::lparen) {
1261 return ParseTLSModel(TLM) ||
1262 ParseToken(lltok::rparen, "expected ')' after thread local model");
1267 /// ParseOptionalAddrSpace
1269 /// := 'addrspace' '(' uint32 ')'
1270 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1272 if (!EatIfPresent(lltok::kw_addrspace))
1274 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1275 ParseUInt32(AddrSpace) ||
1276 ParseToken(lltok::rparen, "expected ')' in address space");
1279 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1280 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1281 bool HaveError = false;
1286 lltok::Kind Token = Lex.getKind();
1288 default: // End of attributes.
1290 case lltok::kw_align: {
1292 if (ParseOptionalAlignment(Alignment))
1294 B.addAlignmentAttr(Alignment);
1297 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1298 case lltok::kw_dereferenceable: {
1300 if (ParseOptionalDereferenceableBytes(Bytes))
1302 B.addDereferenceableAttr(Bytes);
1305 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1306 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1307 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1308 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1309 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1310 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1311 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1312 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1313 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1314 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1315 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1316 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1318 case lltok::kw_alignstack:
1319 case lltok::kw_alwaysinline:
1320 case lltok::kw_builtin:
1321 case lltok::kw_inlinehint:
1322 case lltok::kw_jumptable:
1323 case lltok::kw_minsize:
1324 case lltok::kw_naked:
1325 case lltok::kw_nobuiltin:
1326 case lltok::kw_noduplicate:
1327 case lltok::kw_noimplicitfloat:
1328 case lltok::kw_noinline:
1329 case lltok::kw_nonlazybind:
1330 case lltok::kw_noredzone:
1331 case lltok::kw_noreturn:
1332 case lltok::kw_nounwind:
1333 case lltok::kw_optnone:
1334 case lltok::kw_optsize:
1335 case lltok::kw_returns_twice:
1336 case lltok::kw_sanitize_address:
1337 case lltok::kw_sanitize_memory:
1338 case lltok::kw_sanitize_thread:
1340 case lltok::kw_sspreq:
1341 case lltok::kw_sspstrong:
1342 case lltok::kw_uwtable:
1343 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1351 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1352 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1353 bool HaveError = false;
1358 lltok::Kind Token = Lex.getKind();
1360 default: // End of attributes.
1362 case lltok::kw_dereferenceable: {
1364 if (ParseOptionalDereferenceableBytes(Bytes))
1366 B.addDereferenceableAttr(Bytes);
1369 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1370 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1371 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1372 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1373 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1376 case lltok::kw_align:
1377 case lltok::kw_byval:
1378 case lltok::kw_inalloca:
1379 case lltok::kw_nest:
1380 case lltok::kw_nocapture:
1381 case lltok::kw_returned:
1382 case lltok::kw_sret:
1383 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1386 case lltok::kw_alignstack:
1387 case lltok::kw_alwaysinline:
1388 case lltok::kw_builtin:
1389 case lltok::kw_cold:
1390 case lltok::kw_inlinehint:
1391 case lltok::kw_jumptable:
1392 case lltok::kw_minsize:
1393 case lltok::kw_naked:
1394 case lltok::kw_nobuiltin:
1395 case lltok::kw_noduplicate:
1396 case lltok::kw_noimplicitfloat:
1397 case lltok::kw_noinline:
1398 case lltok::kw_nonlazybind:
1399 case lltok::kw_noredzone:
1400 case lltok::kw_noreturn:
1401 case lltok::kw_nounwind:
1402 case lltok::kw_optnone:
1403 case lltok::kw_optsize:
1404 case lltok::kw_returns_twice:
1405 case lltok::kw_sanitize_address:
1406 case lltok::kw_sanitize_memory:
1407 case lltok::kw_sanitize_thread:
1409 case lltok::kw_sspreq:
1410 case lltok::kw_sspstrong:
1411 case lltok::kw_uwtable:
1412 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1415 case lltok::kw_readnone:
1416 case lltok::kw_readonly:
1417 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1424 /// ParseOptionalLinkage
1431 /// ::= 'linkonce_odr'
1432 /// ::= 'available_externally'
1435 /// ::= 'extern_weak'
1438 /// Deprecated Values:
1439 /// ::= 'linker_private'
1440 /// ::= 'linker_private_weak'
1441 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1443 switch (Lex.getKind()) {
1444 default: Res=GlobalValue::ExternalLinkage; return false;
1445 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1446 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1447 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1448 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1449 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1450 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1451 case lltok::kw_available_externally:
1452 Res = GlobalValue::AvailableExternallyLinkage;
1454 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1455 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1456 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1457 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1459 case lltok::kw_linker_private:
1460 case lltok::kw_linker_private_weak:
1461 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1464 // treat linker_private and linker_private_weak as PrivateLinkage
1465 Res = GlobalValue::PrivateLinkage;
1473 /// ParseOptionalVisibility
1479 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1480 switch (Lex.getKind()) {
1481 default: Res = GlobalValue::DefaultVisibility; return false;
1482 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1483 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1484 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1490 /// ParseOptionalDLLStorageClass
1495 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1496 switch (Lex.getKind()) {
1497 default: Res = GlobalValue::DefaultStorageClass; return false;
1498 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1499 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1505 /// ParseOptionalCallingConv
1509 /// ::= 'kw_intel_ocl_bicc'
1511 /// ::= 'x86_stdcallcc'
1512 /// ::= 'x86_fastcallcc'
1513 /// ::= 'x86_thiscallcc'
1514 /// ::= 'arm_apcscc'
1515 /// ::= 'arm_aapcscc'
1516 /// ::= 'arm_aapcs_vfpcc'
1517 /// ::= 'msp430_intrcc'
1518 /// ::= 'ptx_kernel'
1519 /// ::= 'ptx_device'
1521 /// ::= 'spir_kernel'
1522 /// ::= 'x86_64_sysvcc'
1523 /// ::= 'x86_64_win64cc'
1524 /// ::= 'webkit_jscc'
1526 /// ::= 'preserve_mostcc'
1527 /// ::= 'preserve_allcc'
1530 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1531 switch (Lex.getKind()) {
1532 default: CC = CallingConv::C; return false;
1533 case lltok::kw_ccc: CC = CallingConv::C; break;
1534 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1535 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1536 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1537 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1538 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1539 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1540 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1541 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1542 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1543 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1544 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1545 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1546 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1547 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1548 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1549 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1550 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1551 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1552 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1553 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1554 case lltok::kw_cc: {
1555 unsigned ArbitraryCC;
1557 if (ParseUInt32(ArbitraryCC))
1559 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1568 /// ParseInstructionMetadata
1569 /// ::= !dbg !42 (',' !dbg !57)*
1570 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1571 PerFunctionState *PFS) {
1573 if (Lex.getKind() != lltok::MetadataVar)
1574 return TokError("expected metadata after comma");
1576 std::string Name = Lex.getStrVal();
1577 unsigned MDK = M->getMDKindID(Name);
1581 SMLoc Loc = Lex.getLoc();
1583 if (ParseToken(lltok::exclaim, "expected '!' here"))
1586 // This code is similar to that of ParseMetadataValue, however it needs to
1587 // have special-case code for a forward reference; see the comments on
1588 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1589 // at the top level here.
1590 if (Lex.getKind() == lltok::lbrace) {
1592 if (ParseMetadataListValue(ID, PFS))
1594 assert(ID.Kind == ValID::t_MDNode);
1595 Inst->setMetadata(MDK, ID.MDNodeVal);
1597 unsigned NodeID = 0;
1598 if (ParseMDNodeID(Node, NodeID))
1601 // If we got the node, add it to the instruction.
1602 Inst->setMetadata(MDK, Node);
1604 MDRef R = { Loc, MDK, NodeID };
1605 // Otherwise, remember that this should be resolved later.
1606 ForwardRefInstMetadata[Inst].push_back(R);
1610 if (MDK == LLVMContext::MD_tbaa)
1611 InstsWithTBAATag.push_back(Inst);
1613 // If this is the end of the list, we're done.
1614 } while (EatIfPresent(lltok::comma));
1618 /// ParseOptionalAlignment
1621 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1623 if (!EatIfPresent(lltok::kw_align))
1625 LocTy AlignLoc = Lex.getLoc();
1626 if (ParseUInt32(Alignment)) return true;
1627 if (!isPowerOf2_32(Alignment))
1628 return Error(AlignLoc, "alignment is not a power of two");
1629 if (Alignment > Value::MaximumAlignment)
1630 return Error(AlignLoc, "huge alignments are not supported yet");
1634 /// ParseOptionalDereferenceableBytes
1636 /// ::= 'dereferenceable' '(' 4 ')'
1637 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1639 if (!EatIfPresent(lltok::kw_dereferenceable))
1641 LocTy ParenLoc = Lex.getLoc();
1642 if (!EatIfPresent(lltok::lparen))
1643 return Error(ParenLoc, "expected '('");
1644 LocTy DerefLoc = Lex.getLoc();
1645 if (ParseUInt64(Bytes)) return true;
1646 ParenLoc = Lex.getLoc();
1647 if (!EatIfPresent(lltok::rparen))
1648 return Error(ParenLoc, "expected ')'");
1650 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1654 /// ParseOptionalCommaAlign
1658 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1660 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1661 bool &AteExtraComma) {
1662 AteExtraComma = false;
1663 while (EatIfPresent(lltok::comma)) {
1664 // Metadata at the end is an early exit.
1665 if (Lex.getKind() == lltok::MetadataVar) {
1666 AteExtraComma = true;
1670 if (Lex.getKind() != lltok::kw_align)
1671 return Error(Lex.getLoc(), "expected metadata or 'align'");
1673 if (ParseOptionalAlignment(Alignment)) return true;
1679 /// ParseScopeAndOrdering
1680 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1683 /// This sets Scope and Ordering to the parsed values.
1684 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1685 AtomicOrdering &Ordering) {
1689 Scope = CrossThread;
1690 if (EatIfPresent(lltok::kw_singlethread))
1691 Scope = SingleThread;
1693 return ParseOrdering(Ordering);
1697 /// ::= AtomicOrdering
1699 /// This sets Ordering to the parsed value.
1700 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1701 switch (Lex.getKind()) {
1702 default: return TokError("Expected ordering on atomic instruction");
1703 case lltok::kw_unordered: Ordering = Unordered; break;
1704 case lltok::kw_monotonic: Ordering = Monotonic; break;
1705 case lltok::kw_acquire: Ordering = Acquire; break;
1706 case lltok::kw_release: Ordering = Release; break;
1707 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1708 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1714 /// ParseOptionalStackAlignment
1716 /// ::= 'alignstack' '(' 4 ')'
1717 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1719 if (!EatIfPresent(lltok::kw_alignstack))
1721 LocTy ParenLoc = Lex.getLoc();
1722 if (!EatIfPresent(lltok::lparen))
1723 return Error(ParenLoc, "expected '('");
1724 LocTy AlignLoc = Lex.getLoc();
1725 if (ParseUInt32(Alignment)) return true;
1726 ParenLoc = Lex.getLoc();
1727 if (!EatIfPresent(lltok::rparen))
1728 return Error(ParenLoc, "expected ')'");
1729 if (!isPowerOf2_32(Alignment))
1730 return Error(AlignLoc, "stack alignment is not a power of two");
1734 /// ParseIndexList - This parses the index list for an insert/extractvalue
1735 /// instruction. This sets AteExtraComma in the case where we eat an extra
1736 /// comma at the end of the line and find that it is followed by metadata.
1737 /// Clients that don't allow metadata can call the version of this function that
1738 /// only takes one argument.
1741 /// ::= (',' uint32)+
1743 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1744 bool &AteExtraComma) {
1745 AteExtraComma = false;
1747 if (Lex.getKind() != lltok::comma)
1748 return TokError("expected ',' as start of index list");
1750 while (EatIfPresent(lltok::comma)) {
1751 if (Lex.getKind() == lltok::MetadataVar) {
1752 AteExtraComma = true;
1756 if (ParseUInt32(Idx)) return true;
1757 Indices.push_back(Idx);
1763 //===----------------------------------------------------------------------===//
1765 //===----------------------------------------------------------------------===//
1767 /// ParseType - Parse a type.
1768 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1769 SMLoc TypeLoc = Lex.getLoc();
1770 switch (Lex.getKind()) {
1772 return TokError("expected type");
1774 // Type ::= 'float' | 'void' (etc)
1775 Result = Lex.getTyVal();
1779 // Type ::= StructType
1780 if (ParseAnonStructType(Result, false))
1783 case lltok::lsquare:
1784 // Type ::= '[' ... ']'
1785 Lex.Lex(); // eat the lsquare.
1786 if (ParseArrayVectorType(Result, false))
1789 case lltok::less: // Either vector or packed struct.
1790 // Type ::= '<' ... '>'
1792 if (Lex.getKind() == lltok::lbrace) {
1793 if (ParseAnonStructType(Result, true) ||
1794 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1796 } else if (ParseArrayVectorType(Result, true))
1799 case lltok::LocalVar: {
1801 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1803 // If the type hasn't been defined yet, create a forward definition and
1804 // remember where that forward def'n was seen (in case it never is defined).
1806 Entry.first = StructType::create(Context, Lex.getStrVal());
1807 Entry.second = Lex.getLoc();
1809 Result = Entry.first;
1814 case lltok::LocalVarID: {
1816 if (Lex.getUIntVal() >= NumberedTypes.size())
1817 NumberedTypes.resize(Lex.getUIntVal()+1);
1818 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1820 // If the type hasn't been defined yet, create a forward definition and
1821 // remember where that forward def'n was seen (in case it never is defined).
1823 Entry.first = StructType::create(Context);
1824 Entry.second = Lex.getLoc();
1826 Result = Entry.first;
1832 // Parse the type suffixes.
1834 switch (Lex.getKind()) {
1837 if (!AllowVoid && Result->isVoidTy())
1838 return Error(TypeLoc, "void type only allowed for function results");
1841 // Type ::= Type '*'
1843 if (Result->isLabelTy())
1844 return TokError("basic block pointers are invalid");
1845 if (Result->isVoidTy())
1846 return TokError("pointers to void are invalid - use i8* instead");
1847 if (!PointerType::isValidElementType(Result))
1848 return TokError("pointer to this type is invalid");
1849 Result = PointerType::getUnqual(Result);
1853 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1854 case lltok::kw_addrspace: {
1855 if (Result->isLabelTy())
1856 return TokError("basic block pointers are invalid");
1857 if (Result->isVoidTy())
1858 return TokError("pointers to void are invalid; use i8* instead");
1859 if (!PointerType::isValidElementType(Result))
1860 return TokError("pointer to this type is invalid");
1862 if (ParseOptionalAddrSpace(AddrSpace) ||
1863 ParseToken(lltok::star, "expected '*' in address space"))
1866 Result = PointerType::get(Result, AddrSpace);
1870 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1872 if (ParseFunctionType(Result))
1879 /// ParseParameterList
1881 /// ::= '(' Arg (',' Arg)* ')'
1883 /// ::= Type OptionalAttributes Value OptionalAttributes
1884 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1885 PerFunctionState &PFS) {
1886 if (ParseToken(lltok::lparen, "expected '(' in call"))
1889 unsigned AttrIndex = 1;
1890 while (Lex.getKind() != lltok::rparen) {
1891 // If this isn't the first argument, we need a comma.
1892 if (!ArgList.empty() &&
1893 ParseToken(lltok::comma, "expected ',' in argument list"))
1896 // Parse the argument.
1898 Type *ArgTy = nullptr;
1899 AttrBuilder ArgAttrs;
1901 if (ParseType(ArgTy, ArgLoc))
1904 // Otherwise, handle normal operands.
1905 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1907 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1912 Lex.Lex(); // Lex the ')'.
1918 /// ParseArgumentList - Parse the argument list for a function type or function
1920 /// ::= '(' ArgTypeListI ')'
1924 /// ::= ArgTypeList ',' '...'
1925 /// ::= ArgType (',' ArgType)*
1927 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1930 assert(Lex.getKind() == lltok::lparen);
1931 Lex.Lex(); // eat the (.
1933 if (Lex.getKind() == lltok::rparen) {
1935 } else if (Lex.getKind() == lltok::dotdotdot) {
1939 LocTy TypeLoc = Lex.getLoc();
1940 Type *ArgTy = nullptr;
1944 if (ParseType(ArgTy) ||
1945 ParseOptionalParamAttrs(Attrs)) return true;
1947 if (ArgTy->isVoidTy())
1948 return Error(TypeLoc, "argument can not have void type");
1950 if (Lex.getKind() == lltok::LocalVar) {
1951 Name = Lex.getStrVal();
1955 if (!FunctionType::isValidArgumentType(ArgTy))
1956 return Error(TypeLoc, "invalid type for function argument");
1958 unsigned AttrIndex = 1;
1959 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1960 AttributeSet::get(ArgTy->getContext(),
1961 AttrIndex++, Attrs), Name));
1963 while (EatIfPresent(lltok::comma)) {
1964 // Handle ... at end of arg list.
1965 if (EatIfPresent(lltok::dotdotdot)) {
1970 // Otherwise must be an argument type.
1971 TypeLoc = Lex.getLoc();
1972 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1974 if (ArgTy->isVoidTy())
1975 return Error(TypeLoc, "argument can not have void type");
1977 if (Lex.getKind() == lltok::LocalVar) {
1978 Name = Lex.getStrVal();
1984 if (!ArgTy->isFirstClassType())
1985 return Error(TypeLoc, "invalid type for function argument");
1987 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1988 AttributeSet::get(ArgTy->getContext(),
1989 AttrIndex++, Attrs),
1994 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1997 /// ParseFunctionType
1998 /// ::= Type ArgumentList OptionalAttrs
1999 bool LLParser::ParseFunctionType(Type *&Result) {
2000 assert(Lex.getKind() == lltok::lparen);
2002 if (!FunctionType::isValidReturnType(Result))
2003 return TokError("invalid function return type");
2005 SmallVector<ArgInfo, 8> ArgList;
2007 if (ParseArgumentList(ArgList, isVarArg))
2010 // Reject names on the arguments lists.
2011 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2012 if (!ArgList[i].Name.empty())
2013 return Error(ArgList[i].Loc, "argument name invalid in function type");
2014 if (ArgList[i].Attrs.hasAttributes(i + 1))
2015 return Error(ArgList[i].Loc,
2016 "argument attributes invalid in function type");
2019 SmallVector<Type*, 16> ArgListTy;
2020 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2021 ArgListTy.push_back(ArgList[i].Ty);
2023 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2027 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2029 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2030 SmallVector<Type*, 8> Elts;
2031 if (ParseStructBody(Elts)) return true;
2033 Result = StructType::get(Context, Elts, Packed);
2037 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2038 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2039 std::pair<Type*, LocTy> &Entry,
2041 // If the type was already defined, diagnose the redefinition.
2042 if (Entry.first && !Entry.second.isValid())
2043 return Error(TypeLoc, "redefinition of type");
2045 // If we have opaque, just return without filling in the definition for the
2046 // struct. This counts as a definition as far as the .ll file goes.
2047 if (EatIfPresent(lltok::kw_opaque)) {
2048 // This type is being defined, so clear the location to indicate this.
2049 Entry.second = SMLoc();
2051 // If this type number has never been uttered, create it.
2053 Entry.first = StructType::create(Context, Name);
2054 ResultTy = Entry.first;
2058 // If the type starts with '<', then it is either a packed struct or a vector.
2059 bool isPacked = EatIfPresent(lltok::less);
2061 // If we don't have a struct, then we have a random type alias, which we
2062 // accept for compatibility with old files. These types are not allowed to be
2063 // forward referenced and not allowed to be recursive.
2064 if (Lex.getKind() != lltok::lbrace) {
2066 return Error(TypeLoc, "forward references to non-struct type");
2070 return ParseArrayVectorType(ResultTy, true);
2071 return ParseType(ResultTy);
2074 // This type is being defined, so clear the location to indicate this.
2075 Entry.second = SMLoc();
2077 // If this type number has never been uttered, create it.
2079 Entry.first = StructType::create(Context, Name);
2081 StructType *STy = cast<StructType>(Entry.first);
2083 SmallVector<Type*, 8> Body;
2084 if (ParseStructBody(Body) ||
2085 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2088 STy->setBody(Body, isPacked);
2094 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2097 /// ::= '{' Type (',' Type)* '}'
2098 /// ::= '<' '{' '}' '>'
2099 /// ::= '<' '{' Type (',' Type)* '}' '>'
2100 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2101 assert(Lex.getKind() == lltok::lbrace);
2102 Lex.Lex(); // Consume the '{'
2104 // Handle the empty struct.
2105 if (EatIfPresent(lltok::rbrace))
2108 LocTy EltTyLoc = Lex.getLoc();
2110 if (ParseType(Ty)) return true;
2113 if (!StructType::isValidElementType(Ty))
2114 return Error(EltTyLoc, "invalid element type for struct");
2116 while (EatIfPresent(lltok::comma)) {
2117 EltTyLoc = Lex.getLoc();
2118 if (ParseType(Ty)) return true;
2120 if (!StructType::isValidElementType(Ty))
2121 return Error(EltTyLoc, "invalid element type for struct");
2126 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2129 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2130 /// token has already been consumed.
2132 /// ::= '[' APSINTVAL 'x' Types ']'
2133 /// ::= '<' APSINTVAL 'x' Types '>'
2134 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2135 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2136 Lex.getAPSIntVal().getBitWidth() > 64)
2137 return TokError("expected number in address space");
2139 LocTy SizeLoc = Lex.getLoc();
2140 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2143 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2146 LocTy TypeLoc = Lex.getLoc();
2147 Type *EltTy = nullptr;
2148 if (ParseType(EltTy)) return true;
2150 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2151 "expected end of sequential type"))
2156 return Error(SizeLoc, "zero element vector is illegal");
2157 if ((unsigned)Size != Size)
2158 return Error(SizeLoc, "size too large for vector");
2159 if (!VectorType::isValidElementType(EltTy))
2160 return Error(TypeLoc, "invalid vector element type");
2161 Result = VectorType::get(EltTy, unsigned(Size));
2163 if (!ArrayType::isValidElementType(EltTy))
2164 return Error(TypeLoc, "invalid array element type");
2165 Result = ArrayType::get(EltTy, Size);
2170 //===----------------------------------------------------------------------===//
2171 // Function Semantic Analysis.
2172 //===----------------------------------------------------------------------===//
2174 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2176 : P(p), F(f), FunctionNumber(functionNumber) {
2178 // Insert unnamed arguments into the NumberedVals list.
2179 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2182 NumberedVals.push_back(AI);
2185 LLParser::PerFunctionState::~PerFunctionState() {
2186 // If there were any forward referenced non-basicblock values, delete them.
2187 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2188 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2189 if (!isa<BasicBlock>(I->second.first)) {
2190 I->second.first->replaceAllUsesWith(
2191 UndefValue::get(I->second.first->getType()));
2192 delete I->second.first;
2193 I->second.first = nullptr;
2196 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2197 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2198 if (!isa<BasicBlock>(I->second.first)) {
2199 I->second.first->replaceAllUsesWith(
2200 UndefValue::get(I->second.first->getType()));
2201 delete I->second.first;
2202 I->second.first = nullptr;
2206 bool LLParser::PerFunctionState::FinishFunction() {
2207 // Check to see if someone took the address of labels in this block.
2208 if (!P.ForwardRefBlockAddresses.empty()) {
2210 if (!F.getName().empty()) {
2211 FunctionID.Kind = ValID::t_GlobalName;
2212 FunctionID.StrVal = F.getName();
2214 FunctionID.Kind = ValID::t_GlobalID;
2215 FunctionID.UIntVal = FunctionNumber;
2218 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2219 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2220 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2221 // Resolve all these references.
2222 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2225 P.ForwardRefBlockAddresses.erase(FRBAI);
2229 if (!ForwardRefVals.empty())
2230 return P.Error(ForwardRefVals.begin()->second.second,
2231 "use of undefined value '%" + ForwardRefVals.begin()->first +
2233 if (!ForwardRefValIDs.empty())
2234 return P.Error(ForwardRefValIDs.begin()->second.second,
2235 "use of undefined value '%" +
2236 Twine(ForwardRefValIDs.begin()->first) + "'");
2241 /// GetVal - Get a value with the specified name or ID, creating a
2242 /// forward reference record if needed. This can return null if the value
2243 /// exists but does not have the right type.
2244 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2245 Type *Ty, LocTy Loc) {
2246 // Look this name up in the normal function symbol table.
2247 Value *Val = F.getValueSymbolTable().lookup(Name);
2249 // If this is a forward reference for the value, see if we already created a
2250 // forward ref record.
2252 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2253 I = ForwardRefVals.find(Name);
2254 if (I != ForwardRefVals.end())
2255 Val = I->second.first;
2258 // If we have the value in the symbol table or fwd-ref table, return it.
2260 if (Val->getType() == Ty) return Val;
2261 if (Ty->isLabelTy())
2262 P.Error(Loc, "'%" + Name + "' is not a basic block");
2264 P.Error(Loc, "'%" + Name + "' defined with type '" +
2265 getTypeString(Val->getType()) + "'");
2269 // Don't make placeholders with invalid type.
2270 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2271 P.Error(Loc, "invalid use of a non-first-class type");
2275 // Otherwise, create a new forward reference for this value and remember it.
2277 if (Ty->isLabelTy())
2278 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2280 FwdVal = new Argument(Ty, Name);
2282 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2286 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2288 // Look this name up in the normal function symbol table.
2289 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2291 // If this is a forward reference for the value, see if we already created a
2292 // forward ref record.
2294 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2295 I = ForwardRefValIDs.find(ID);
2296 if (I != ForwardRefValIDs.end())
2297 Val = I->second.first;
2300 // If we have the value in the symbol table or fwd-ref table, return it.
2302 if (Val->getType() == Ty) return Val;
2303 if (Ty->isLabelTy())
2304 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2306 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2307 getTypeString(Val->getType()) + "'");
2311 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2312 P.Error(Loc, "invalid use of a non-first-class type");
2316 // Otherwise, create a new forward reference for this value and remember it.
2318 if (Ty->isLabelTy())
2319 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2321 FwdVal = new Argument(Ty);
2323 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2327 /// SetInstName - After an instruction is parsed and inserted into its
2328 /// basic block, this installs its name.
2329 bool LLParser::PerFunctionState::SetInstName(int NameID,
2330 const std::string &NameStr,
2331 LocTy NameLoc, Instruction *Inst) {
2332 // If this instruction has void type, it cannot have a name or ID specified.
2333 if (Inst->getType()->isVoidTy()) {
2334 if (NameID != -1 || !NameStr.empty())
2335 return P.Error(NameLoc, "instructions returning void cannot have a name");
2339 // If this was a numbered instruction, verify that the instruction is the
2340 // expected value and resolve any forward references.
2341 if (NameStr.empty()) {
2342 // If neither a name nor an ID was specified, just use the next ID.
2344 NameID = NumberedVals.size();
2346 if (unsigned(NameID) != NumberedVals.size())
2347 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2348 Twine(NumberedVals.size()) + "'");
2350 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2351 ForwardRefValIDs.find(NameID);
2352 if (FI != ForwardRefValIDs.end()) {
2353 if (FI->second.first->getType() != Inst->getType())
2354 return P.Error(NameLoc, "instruction forward referenced with type '" +
2355 getTypeString(FI->second.first->getType()) + "'");
2356 FI->second.first->replaceAllUsesWith(Inst);
2357 delete FI->second.first;
2358 ForwardRefValIDs.erase(FI);
2361 NumberedVals.push_back(Inst);
2365 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2366 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2367 FI = ForwardRefVals.find(NameStr);
2368 if (FI != ForwardRefVals.end()) {
2369 if (FI->second.first->getType() != Inst->getType())
2370 return P.Error(NameLoc, "instruction forward referenced with type '" +
2371 getTypeString(FI->second.first->getType()) + "'");
2372 FI->second.first->replaceAllUsesWith(Inst);
2373 delete FI->second.first;
2374 ForwardRefVals.erase(FI);
2377 // Set the name on the instruction.
2378 Inst->setName(NameStr);
2380 if (Inst->getName() != NameStr)
2381 return P.Error(NameLoc, "multiple definition of local value named '" +
2386 /// GetBB - Get a basic block with the specified name or ID, creating a
2387 /// forward reference record if needed.
2388 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2390 return cast_or_null<BasicBlock>(GetVal(Name,
2391 Type::getLabelTy(F.getContext()), Loc));
2394 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2395 return cast_or_null<BasicBlock>(GetVal(ID,
2396 Type::getLabelTy(F.getContext()), Loc));
2399 /// DefineBB - Define the specified basic block, which is either named or
2400 /// unnamed. If there is an error, this returns null otherwise it returns
2401 /// the block being defined.
2402 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2406 BB = GetBB(NumberedVals.size(), Loc);
2408 BB = GetBB(Name, Loc);
2409 if (!BB) return nullptr; // Already diagnosed error.
2411 // Move the block to the end of the function. Forward ref'd blocks are
2412 // inserted wherever they happen to be referenced.
2413 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2415 // Remove the block from forward ref sets.
2417 ForwardRefValIDs.erase(NumberedVals.size());
2418 NumberedVals.push_back(BB);
2420 // BB forward references are already in the function symbol table.
2421 ForwardRefVals.erase(Name);
2427 //===----------------------------------------------------------------------===//
2429 //===----------------------------------------------------------------------===//
2431 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2432 /// type implied. For example, if we parse "4" we don't know what integer type
2433 /// it has. The value will later be combined with its type and checked for
2434 /// sanity. PFS is used to convert function-local operands of metadata (since
2435 /// metadata operands are not just parsed here but also converted to values).
2436 /// PFS can be null when we are not parsing metadata values inside a function.
2437 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2438 ID.Loc = Lex.getLoc();
2439 switch (Lex.getKind()) {
2440 default: return TokError("expected value token");
2441 case lltok::GlobalID: // @42
2442 ID.UIntVal = Lex.getUIntVal();
2443 ID.Kind = ValID::t_GlobalID;
2445 case lltok::GlobalVar: // @foo
2446 ID.StrVal = Lex.getStrVal();
2447 ID.Kind = ValID::t_GlobalName;
2449 case lltok::LocalVarID: // %42
2450 ID.UIntVal = Lex.getUIntVal();
2451 ID.Kind = ValID::t_LocalID;
2453 case lltok::LocalVar: // %foo
2454 ID.StrVal = Lex.getStrVal();
2455 ID.Kind = ValID::t_LocalName;
2457 case lltok::exclaim: // !42, !{...}, or !"foo"
2458 return ParseMetadataValue(ID, PFS);
2460 ID.APSIntVal = Lex.getAPSIntVal();
2461 ID.Kind = ValID::t_APSInt;
2463 case lltok::APFloat:
2464 ID.APFloatVal = Lex.getAPFloatVal();
2465 ID.Kind = ValID::t_APFloat;
2467 case lltok::kw_true:
2468 ID.ConstantVal = ConstantInt::getTrue(Context);
2469 ID.Kind = ValID::t_Constant;
2471 case lltok::kw_false:
2472 ID.ConstantVal = ConstantInt::getFalse(Context);
2473 ID.Kind = ValID::t_Constant;
2475 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2476 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2477 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2479 case lltok::lbrace: {
2480 // ValID ::= '{' ConstVector '}'
2482 SmallVector<Constant*, 16> Elts;
2483 if (ParseGlobalValueVector(Elts) ||
2484 ParseToken(lltok::rbrace, "expected end of struct constant"))
2487 ID.ConstantStructElts = new Constant*[Elts.size()];
2488 ID.UIntVal = Elts.size();
2489 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2490 ID.Kind = ValID::t_ConstantStruct;
2494 // ValID ::= '<' ConstVector '>' --> Vector.
2495 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2497 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2499 SmallVector<Constant*, 16> Elts;
2500 LocTy FirstEltLoc = Lex.getLoc();
2501 if (ParseGlobalValueVector(Elts) ||
2503 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2504 ParseToken(lltok::greater, "expected end of constant"))
2507 if (isPackedStruct) {
2508 ID.ConstantStructElts = new Constant*[Elts.size()];
2509 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2510 ID.UIntVal = Elts.size();
2511 ID.Kind = ValID::t_PackedConstantStruct;
2516 return Error(ID.Loc, "constant vector must not be empty");
2518 if (!Elts[0]->getType()->isIntegerTy() &&
2519 !Elts[0]->getType()->isFloatingPointTy() &&
2520 !Elts[0]->getType()->isPointerTy())
2521 return Error(FirstEltLoc,
2522 "vector elements must have integer, pointer or floating point type");
2524 // Verify that all the vector elements have the same type.
2525 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2526 if (Elts[i]->getType() != Elts[0]->getType())
2527 return Error(FirstEltLoc,
2528 "vector element #" + Twine(i) +
2529 " is not of type '" + getTypeString(Elts[0]->getType()));
2531 ID.ConstantVal = ConstantVector::get(Elts);
2532 ID.Kind = ValID::t_Constant;
2535 case lltok::lsquare: { // Array Constant
2537 SmallVector<Constant*, 16> Elts;
2538 LocTy FirstEltLoc = Lex.getLoc();
2539 if (ParseGlobalValueVector(Elts) ||
2540 ParseToken(lltok::rsquare, "expected end of array constant"))
2543 // Handle empty element.
2545 // Use undef instead of an array because it's inconvenient to determine
2546 // the element type at this point, there being no elements to examine.
2547 ID.Kind = ValID::t_EmptyArray;
2551 if (!Elts[0]->getType()->isFirstClassType())
2552 return Error(FirstEltLoc, "invalid array element type: " +
2553 getTypeString(Elts[0]->getType()));
2555 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2557 // Verify all elements are correct type!
2558 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2559 if (Elts[i]->getType() != Elts[0]->getType())
2560 return Error(FirstEltLoc,
2561 "array element #" + Twine(i) +
2562 " is not of type '" + getTypeString(Elts[0]->getType()));
2565 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2566 ID.Kind = ValID::t_Constant;
2569 case lltok::kw_c: // c "foo"
2571 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2573 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2574 ID.Kind = ValID::t_Constant;
2577 case lltok::kw_asm: {
2578 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2580 bool HasSideEffect, AlignStack, AsmDialect;
2582 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2583 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2584 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2585 ParseStringConstant(ID.StrVal) ||
2586 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2587 ParseToken(lltok::StringConstant, "expected constraint string"))
2589 ID.StrVal2 = Lex.getStrVal();
2590 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2591 (unsigned(AsmDialect)<<2);
2592 ID.Kind = ValID::t_InlineAsm;
2596 case lltok::kw_blockaddress: {
2597 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2602 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2604 ParseToken(lltok::comma, "expected comma in block address expression")||
2605 ParseValID(Label) ||
2606 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2609 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2610 return Error(Fn.Loc, "expected function name in blockaddress");
2611 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2612 return Error(Label.Loc, "expected basic block name in blockaddress");
2614 // Make a global variable as a placeholder for this reference.
2615 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2616 false, GlobalValue::InternalLinkage,
2618 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2619 ID.ConstantVal = FwdRef;
2620 ID.Kind = ValID::t_Constant;
2624 case lltok::kw_trunc:
2625 case lltok::kw_zext:
2626 case lltok::kw_sext:
2627 case lltok::kw_fptrunc:
2628 case lltok::kw_fpext:
2629 case lltok::kw_bitcast:
2630 case lltok::kw_addrspacecast:
2631 case lltok::kw_uitofp:
2632 case lltok::kw_sitofp:
2633 case lltok::kw_fptoui:
2634 case lltok::kw_fptosi:
2635 case lltok::kw_inttoptr:
2636 case lltok::kw_ptrtoint: {
2637 unsigned Opc = Lex.getUIntVal();
2638 Type *DestTy = nullptr;
2641 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2642 ParseGlobalTypeAndValue(SrcVal) ||
2643 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2644 ParseType(DestTy) ||
2645 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2647 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2648 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2649 getTypeString(SrcVal->getType()) + "' to '" +
2650 getTypeString(DestTy) + "'");
2651 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2653 ID.Kind = ValID::t_Constant;
2656 case lltok::kw_extractvalue: {
2659 SmallVector<unsigned, 4> Indices;
2660 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2661 ParseGlobalTypeAndValue(Val) ||
2662 ParseIndexList(Indices) ||
2663 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2666 if (!Val->getType()->isAggregateType())
2667 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2668 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2669 return Error(ID.Loc, "invalid indices for extractvalue");
2670 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2671 ID.Kind = ValID::t_Constant;
2674 case lltok::kw_insertvalue: {
2676 Constant *Val0, *Val1;
2677 SmallVector<unsigned, 4> Indices;
2678 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2679 ParseGlobalTypeAndValue(Val0) ||
2680 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2681 ParseGlobalTypeAndValue(Val1) ||
2682 ParseIndexList(Indices) ||
2683 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2685 if (!Val0->getType()->isAggregateType())
2686 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2687 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2688 return Error(ID.Loc, "invalid indices for insertvalue");
2689 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2690 ID.Kind = ValID::t_Constant;
2693 case lltok::kw_icmp:
2694 case lltok::kw_fcmp: {
2695 unsigned PredVal, Opc = Lex.getUIntVal();
2696 Constant *Val0, *Val1;
2698 if (ParseCmpPredicate(PredVal, Opc) ||
2699 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2700 ParseGlobalTypeAndValue(Val0) ||
2701 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2702 ParseGlobalTypeAndValue(Val1) ||
2703 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2706 if (Val0->getType() != Val1->getType())
2707 return Error(ID.Loc, "compare operands must have the same type");
2709 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2711 if (Opc == Instruction::FCmp) {
2712 if (!Val0->getType()->isFPOrFPVectorTy())
2713 return Error(ID.Loc, "fcmp requires floating point operands");
2714 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2716 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2717 if (!Val0->getType()->isIntOrIntVectorTy() &&
2718 !Val0->getType()->getScalarType()->isPointerTy())
2719 return Error(ID.Loc, "icmp requires pointer or integer operands");
2720 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2722 ID.Kind = ValID::t_Constant;
2726 // Binary Operators.
2728 case lltok::kw_fadd:
2730 case lltok::kw_fsub:
2732 case lltok::kw_fmul:
2733 case lltok::kw_udiv:
2734 case lltok::kw_sdiv:
2735 case lltok::kw_fdiv:
2736 case lltok::kw_urem:
2737 case lltok::kw_srem:
2738 case lltok::kw_frem:
2740 case lltok::kw_lshr:
2741 case lltok::kw_ashr: {
2745 unsigned Opc = Lex.getUIntVal();
2746 Constant *Val0, *Val1;
2748 LocTy ModifierLoc = Lex.getLoc();
2749 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2750 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2751 if (EatIfPresent(lltok::kw_nuw))
2753 if (EatIfPresent(lltok::kw_nsw)) {
2755 if (EatIfPresent(lltok::kw_nuw))
2758 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2759 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2760 if (EatIfPresent(lltok::kw_exact))
2763 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2764 ParseGlobalTypeAndValue(Val0) ||
2765 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2766 ParseGlobalTypeAndValue(Val1) ||
2767 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2769 if (Val0->getType() != Val1->getType())
2770 return Error(ID.Loc, "operands of constexpr must have same type");
2771 if (!Val0->getType()->isIntOrIntVectorTy()) {
2773 return Error(ModifierLoc, "nuw only applies to integer operations");
2775 return Error(ModifierLoc, "nsw only applies to integer operations");
2777 // Check that the type is valid for the operator.
2779 case Instruction::Add:
2780 case Instruction::Sub:
2781 case Instruction::Mul:
2782 case Instruction::UDiv:
2783 case Instruction::SDiv:
2784 case Instruction::URem:
2785 case Instruction::SRem:
2786 case Instruction::Shl:
2787 case Instruction::AShr:
2788 case Instruction::LShr:
2789 if (!Val0->getType()->isIntOrIntVectorTy())
2790 return Error(ID.Loc, "constexpr requires integer operands");
2792 case Instruction::FAdd:
2793 case Instruction::FSub:
2794 case Instruction::FMul:
2795 case Instruction::FDiv:
2796 case Instruction::FRem:
2797 if (!Val0->getType()->isFPOrFPVectorTy())
2798 return Error(ID.Loc, "constexpr requires fp operands");
2800 default: llvm_unreachable("Unknown binary operator!");
2803 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2804 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2805 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2806 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2808 ID.Kind = ValID::t_Constant;
2812 // Logical Operations
2815 case lltok::kw_xor: {
2816 unsigned Opc = Lex.getUIntVal();
2817 Constant *Val0, *Val1;
2819 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2820 ParseGlobalTypeAndValue(Val0) ||
2821 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2822 ParseGlobalTypeAndValue(Val1) ||
2823 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2825 if (Val0->getType() != Val1->getType())
2826 return Error(ID.Loc, "operands of constexpr must have same type");
2827 if (!Val0->getType()->isIntOrIntVectorTy())
2828 return Error(ID.Loc,
2829 "constexpr requires integer or integer vector operands");
2830 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2831 ID.Kind = ValID::t_Constant;
2835 case lltok::kw_getelementptr:
2836 case lltok::kw_shufflevector:
2837 case lltok::kw_insertelement:
2838 case lltok::kw_extractelement:
2839 case lltok::kw_select: {
2840 unsigned Opc = Lex.getUIntVal();
2841 SmallVector<Constant*, 16> Elts;
2842 bool InBounds = false;
2844 if (Opc == Instruction::GetElementPtr)
2845 InBounds = EatIfPresent(lltok::kw_inbounds);
2846 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2847 ParseGlobalValueVector(Elts) ||
2848 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2851 if (Opc == Instruction::GetElementPtr) {
2852 if (Elts.size() == 0 ||
2853 !Elts[0]->getType()->getScalarType()->isPointerTy())
2854 return Error(ID.Loc, "getelementptr requires pointer operand");
2856 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2857 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2858 return Error(ID.Loc, "invalid indices for getelementptr");
2859 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2861 } else if (Opc == Instruction::Select) {
2862 if (Elts.size() != 3)
2863 return Error(ID.Loc, "expected three operands to select");
2864 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2866 return Error(ID.Loc, Reason);
2867 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2868 } else if (Opc == Instruction::ShuffleVector) {
2869 if (Elts.size() != 3)
2870 return Error(ID.Loc, "expected three operands to shufflevector");
2871 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2872 return Error(ID.Loc, "invalid operands to shufflevector");
2874 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2875 } else if (Opc == Instruction::ExtractElement) {
2876 if (Elts.size() != 2)
2877 return Error(ID.Loc, "expected two operands to extractelement");
2878 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2879 return Error(ID.Loc, "invalid extractelement operands");
2880 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2882 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2883 if (Elts.size() != 3)
2884 return Error(ID.Loc, "expected three operands to insertelement");
2885 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2886 return Error(ID.Loc, "invalid insertelement operands");
2888 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2891 ID.Kind = ValID::t_Constant;
2900 /// ParseGlobalValue - Parse a global value with the specified type.
2901 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2905 bool Parsed = ParseValID(ID) ||
2906 ConvertValIDToValue(Ty, ID, V, nullptr);
2907 if (V && !(C = dyn_cast<Constant>(V)))
2908 return Error(ID.Loc, "global values must be constants");
2912 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2914 return ParseType(Ty) ||
2915 ParseGlobalValue(Ty, V);
2918 bool LLParser::parseOptionalComdat(Comdat *&C) {
2920 if (!EatIfPresent(lltok::kw_comdat))
2922 if (Lex.getKind() != lltok::ComdatVar)
2923 return TokError("expected comdat variable");
2924 LocTy Loc = Lex.getLoc();
2925 StringRef Name = Lex.getStrVal();
2926 C = getComdat(Name, Loc);
2931 /// ParseGlobalValueVector
2933 /// ::= TypeAndValue (',' TypeAndValue)*
2934 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2936 if (Lex.getKind() == lltok::rbrace ||
2937 Lex.getKind() == lltok::rsquare ||
2938 Lex.getKind() == lltok::greater ||
2939 Lex.getKind() == lltok::rparen)
2943 if (ParseGlobalTypeAndValue(C)) return true;
2946 while (EatIfPresent(lltok::comma)) {
2947 if (ParseGlobalTypeAndValue(C)) return true;
2954 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2955 assert(Lex.getKind() == lltok::lbrace);
2958 SmallVector<Value*, 16> Elts;
2959 if (ParseMDNodeVector(Elts, PFS) ||
2960 ParseToken(lltok::rbrace, "expected end of metadata node"))
2963 ID.MDNodeVal = MDNode::get(Context, Elts);
2964 ID.Kind = ValID::t_MDNode;
2968 /// ParseMetadataValue
2972 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2973 assert(Lex.getKind() == lltok::exclaim);
2978 if (Lex.getKind() == lltok::lbrace)
2979 return ParseMetadataListValue(ID, PFS);
2981 // Standalone metadata reference
2983 if (Lex.getKind() == lltok::APSInt) {
2984 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2985 ID.Kind = ValID::t_MDNode;
2990 // ::= '!' STRINGCONSTANT
2991 if (ParseMDString(ID.MDStringVal)) return true;
2992 ID.Kind = ValID::t_MDString;
2997 //===----------------------------------------------------------------------===//
2998 // Function Parsing.
2999 //===----------------------------------------------------------------------===//
3001 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3002 PerFunctionState *PFS) {
3003 if (Ty->isFunctionTy())
3004 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3007 case ValID::t_LocalID:
3008 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3009 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3010 return V == nullptr;
3011 case ValID::t_LocalName:
3012 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3013 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3014 return V == nullptr;
3015 case ValID::t_InlineAsm: {
3016 PointerType *PTy = dyn_cast<PointerType>(Ty);
3018 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3019 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3020 return Error(ID.Loc, "invalid type for inline asm constraint string");
3021 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3022 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3025 case ValID::t_MDNode:
3026 if (!Ty->isMetadataTy())
3027 return Error(ID.Loc, "metadata value must have metadata type");
3030 case ValID::t_MDString:
3031 if (!Ty->isMetadataTy())
3032 return Error(ID.Loc, "metadata value must have metadata type");
3035 case ValID::t_GlobalName:
3036 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3037 return V == nullptr;
3038 case ValID::t_GlobalID:
3039 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3040 return V == nullptr;
3041 case ValID::t_APSInt:
3042 if (!Ty->isIntegerTy())
3043 return Error(ID.Loc, "integer constant must have integer type");
3044 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3045 V = ConstantInt::get(Context, ID.APSIntVal);
3047 case ValID::t_APFloat:
3048 if (!Ty->isFloatingPointTy() ||
3049 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3050 return Error(ID.Loc, "floating point constant invalid for type");
3052 // The lexer has no type info, so builds all half, float, and double FP
3053 // constants as double. Fix this here. Long double does not need this.
3054 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3057 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3059 else if (Ty->isFloatTy())
3060 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3063 V = ConstantFP::get(Context, ID.APFloatVal);
3065 if (V->getType() != Ty)
3066 return Error(ID.Loc, "floating point constant does not have type '" +
3067 getTypeString(Ty) + "'");
3071 if (!Ty->isPointerTy())
3072 return Error(ID.Loc, "null must be a pointer type");
3073 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3075 case ValID::t_Undef:
3076 // FIXME: LabelTy should not be a first-class type.
3077 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3078 return Error(ID.Loc, "invalid type for undef constant");
3079 V = UndefValue::get(Ty);
3081 case ValID::t_EmptyArray:
3082 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3083 return Error(ID.Loc, "invalid empty array initializer");
3084 V = UndefValue::get(Ty);
3087 // FIXME: LabelTy should not be a first-class type.
3088 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3089 return Error(ID.Loc, "invalid type for null constant");
3090 V = Constant::getNullValue(Ty);
3092 case ValID::t_Constant:
3093 if (ID.ConstantVal->getType() != Ty)
3094 return Error(ID.Loc, "constant expression type mismatch");
3098 case ValID::t_ConstantStruct:
3099 case ValID::t_PackedConstantStruct:
3100 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3101 if (ST->getNumElements() != ID.UIntVal)
3102 return Error(ID.Loc,
3103 "initializer with struct type has wrong # elements");
3104 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3105 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3107 // Verify that the elements are compatible with the structtype.
3108 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3109 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3110 return Error(ID.Loc, "element " + Twine(i) +
3111 " of struct initializer doesn't match struct element type");
3113 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3116 return Error(ID.Loc, "constant expression type mismatch");
3119 llvm_unreachable("Invalid ValID");
3122 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3125 return ParseValID(ID, PFS) ||
3126 ConvertValIDToValue(Ty, ID, V, PFS);
3129 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3131 return ParseType(Ty) ||
3132 ParseValue(Ty, V, PFS);
3135 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3136 PerFunctionState &PFS) {
3139 if (ParseTypeAndValue(V, PFS)) return true;
3140 if (!isa<BasicBlock>(V))
3141 return Error(Loc, "expected a basic block");
3142 BB = cast<BasicBlock>(V);
3148 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3149 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3150 /// OptionalAlign OptGC OptionalPrefix
3151 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3152 // Parse the linkage.
3153 LocTy LinkageLoc = Lex.getLoc();
3156 unsigned Visibility;
3157 unsigned DLLStorageClass;
3158 AttrBuilder RetAttrs;
3160 Type *RetType = nullptr;
3161 LocTy RetTypeLoc = Lex.getLoc();
3162 if (ParseOptionalLinkage(Linkage) ||
3163 ParseOptionalVisibility(Visibility) ||
3164 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3165 ParseOptionalCallingConv(CC) ||
3166 ParseOptionalReturnAttrs(RetAttrs) ||
3167 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3170 // Verify that the linkage is ok.
3171 switch ((GlobalValue::LinkageTypes)Linkage) {
3172 case GlobalValue::ExternalLinkage:
3173 break; // always ok.
3174 case GlobalValue::ExternalWeakLinkage:
3176 return Error(LinkageLoc, "invalid linkage for function definition");
3178 case GlobalValue::PrivateLinkage:
3179 case GlobalValue::InternalLinkage:
3180 case GlobalValue::AvailableExternallyLinkage:
3181 case GlobalValue::LinkOnceAnyLinkage:
3182 case GlobalValue::LinkOnceODRLinkage:
3183 case GlobalValue::WeakAnyLinkage:
3184 case GlobalValue::WeakODRLinkage:
3186 return Error(LinkageLoc, "invalid linkage for function declaration");
3188 case GlobalValue::AppendingLinkage:
3189 case GlobalValue::CommonLinkage:
3190 return Error(LinkageLoc, "invalid function linkage type");
3193 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3194 return Error(LinkageLoc,
3195 "symbol with local linkage must have default visibility");
3197 if (!FunctionType::isValidReturnType(RetType))
3198 return Error(RetTypeLoc, "invalid function return type");
3200 LocTy NameLoc = Lex.getLoc();
3202 std::string FunctionName;
3203 if (Lex.getKind() == lltok::GlobalVar) {
3204 FunctionName = Lex.getStrVal();
3205 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3206 unsigned NameID = Lex.getUIntVal();
3208 if (NameID != NumberedVals.size())
3209 return TokError("function expected to be numbered '%" +
3210 Twine(NumberedVals.size()) + "'");
3212 return TokError("expected function name");
3217 if (Lex.getKind() != lltok::lparen)
3218 return TokError("expected '(' in function argument list");
3220 SmallVector<ArgInfo, 8> ArgList;
3222 AttrBuilder FuncAttrs;
3223 std::vector<unsigned> FwdRefAttrGrps;
3225 std::string Section;
3229 LocTy UnnamedAddrLoc;
3230 Constant *Prefix = nullptr;
3233 if (ParseArgumentList(ArgList, isVarArg) ||
3234 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3236 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3238 (EatIfPresent(lltok::kw_section) &&
3239 ParseStringConstant(Section)) ||
3240 parseOptionalComdat(C) ||
3241 ParseOptionalAlignment(Alignment) ||
3242 (EatIfPresent(lltok::kw_gc) &&
3243 ParseStringConstant(GC)) ||
3244 (EatIfPresent(lltok::kw_prefix) &&
3245 ParseGlobalTypeAndValue(Prefix)))
3248 if (FuncAttrs.contains(Attribute::Builtin))
3249 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3251 // If the alignment was parsed as an attribute, move to the alignment field.
3252 if (FuncAttrs.hasAlignmentAttr()) {
3253 Alignment = FuncAttrs.getAlignment();
3254 FuncAttrs.removeAttribute(Attribute::Alignment);
3257 // Okay, if we got here, the function is syntactically valid. Convert types
3258 // and do semantic checks.
3259 std::vector<Type*> ParamTypeList;
3260 SmallVector<AttributeSet, 8> Attrs;
3262 if (RetAttrs.hasAttributes())
3263 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3264 AttributeSet::ReturnIndex,
3267 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3268 ParamTypeList.push_back(ArgList[i].Ty);
3269 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3270 AttrBuilder B(ArgList[i].Attrs, i + 1);
3271 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3275 if (FuncAttrs.hasAttributes())
3276 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3277 AttributeSet::FunctionIndex,
3280 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3282 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3283 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3286 FunctionType::get(RetType, ParamTypeList, isVarArg);
3287 PointerType *PFT = PointerType::getUnqual(FT);
3290 if (!FunctionName.empty()) {
3291 // If this was a definition of a forward reference, remove the definition
3292 // from the forward reference table and fill in the forward ref.
3293 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3294 ForwardRefVals.find(FunctionName);
3295 if (FRVI != ForwardRefVals.end()) {
3296 Fn = M->getFunction(FunctionName);
3298 return Error(FRVI->second.second, "invalid forward reference to "
3299 "function as global value!");
3300 if (Fn->getType() != PFT)
3301 return Error(FRVI->second.second, "invalid forward reference to "
3302 "function '" + FunctionName + "' with wrong type!");
3304 ForwardRefVals.erase(FRVI);
3305 } else if ((Fn = M->getFunction(FunctionName))) {
3306 // Reject redefinitions.
3307 return Error(NameLoc, "invalid redefinition of function '" +
3308 FunctionName + "'");
3309 } else if (M->getNamedValue(FunctionName)) {
3310 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3314 // If this is a definition of a forward referenced function, make sure the
3316 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3317 = ForwardRefValIDs.find(NumberedVals.size());
3318 if (I != ForwardRefValIDs.end()) {
3319 Fn = cast<Function>(I->second.first);
3320 if (Fn->getType() != PFT)
3321 return Error(NameLoc, "type of definition and forward reference of '@" +
3322 Twine(NumberedVals.size()) + "' disagree");
3323 ForwardRefValIDs.erase(I);
3328 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3329 else // Move the forward-reference to the correct spot in the module.
3330 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3332 if (FunctionName.empty())
3333 NumberedVals.push_back(Fn);
3335 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3336 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3337 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3338 Fn->setCallingConv(CC);
3339 Fn->setAttributes(PAL);
3340 Fn->setUnnamedAddr(UnnamedAddr);
3341 Fn->setAlignment(Alignment);
3342 Fn->setSection(Section);
3344 if (!GC.empty()) Fn->setGC(GC.c_str());
3345 Fn->setPrefixData(Prefix);
3346 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3348 // Add all of the arguments we parsed to the function.
3349 Function::arg_iterator ArgIt = Fn->arg_begin();
3350 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3351 // If the argument has a name, insert it into the argument symbol table.
3352 if (ArgList[i].Name.empty()) continue;
3354 // Set the name, if it conflicted, it will be auto-renamed.
3355 ArgIt->setName(ArgList[i].Name);
3357 if (ArgIt->getName() != ArgList[i].Name)
3358 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3359 ArgList[i].Name + "'");
3366 /// ParseFunctionBody
3367 /// ::= '{' BasicBlock+ '}'
3369 bool LLParser::ParseFunctionBody(Function &Fn) {
3370 if (Lex.getKind() != lltok::lbrace)
3371 return TokError("expected '{' in function body");
3372 Lex.Lex(); // eat the {.
3374 int FunctionNumber = -1;
3375 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3377 PerFunctionState PFS(*this, Fn, FunctionNumber);
3379 // We need at least one basic block.
3380 if (Lex.getKind() == lltok::rbrace)
3381 return TokError("function body requires at least one basic block");
3383 while (Lex.getKind() != lltok::rbrace)
3384 if (ParseBasicBlock(PFS)) return true;
3389 // Verify function is ok.
3390 return PFS.FinishFunction();
3394 /// ::= LabelStr? Instruction*
3395 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3396 // If this basic block starts out with a name, remember it.
3398 LocTy NameLoc = Lex.getLoc();
3399 if (Lex.getKind() == lltok::LabelStr) {
3400 Name = Lex.getStrVal();
3404 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3405 if (!BB) return true;
3407 std::string NameStr;
3409 // Parse the instructions in this block until we get a terminator.
3412 // This instruction may have three possibilities for a name: a) none
3413 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3414 LocTy NameLoc = Lex.getLoc();
3418 if (Lex.getKind() == lltok::LocalVarID) {
3419 NameID = Lex.getUIntVal();
3421 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3423 } else if (Lex.getKind() == lltok::LocalVar) {
3424 NameStr = Lex.getStrVal();
3426 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3430 switch (ParseInstruction(Inst, BB, PFS)) {
3431 default: llvm_unreachable("Unknown ParseInstruction result!");
3432 case InstError: return true;
3434 BB->getInstList().push_back(Inst);
3436 // With a normal result, we check to see if the instruction is followed by
3437 // a comma and metadata.
3438 if (EatIfPresent(lltok::comma))
3439 if (ParseInstructionMetadata(Inst, &PFS))
3442 case InstExtraComma:
3443 BB->getInstList().push_back(Inst);
3445 // If the instruction parser ate an extra comma at the end of it, it
3446 // *must* be followed by metadata.
3447 if (ParseInstructionMetadata(Inst, &PFS))
3452 // Set the name on the instruction.
3453 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3454 } while (!isa<TerminatorInst>(Inst));
3459 //===----------------------------------------------------------------------===//
3460 // Instruction Parsing.
3461 //===----------------------------------------------------------------------===//
3463 /// ParseInstruction - Parse one of the many different instructions.
3465 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3466 PerFunctionState &PFS) {
3467 lltok::Kind Token = Lex.getKind();
3468 if (Token == lltok::Eof)
3469 return TokError("found end of file when expecting more instructions");
3470 LocTy Loc = Lex.getLoc();
3471 unsigned KeywordVal = Lex.getUIntVal();
3472 Lex.Lex(); // Eat the keyword.
3475 default: return Error(Loc, "expected instruction opcode");
3476 // Terminator Instructions.
3477 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3478 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3479 case lltok::kw_br: return ParseBr(Inst, PFS);
3480 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3481 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3482 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3483 case lltok::kw_resume: return ParseResume(Inst, PFS);
3484 // Binary Operators.
3488 case lltok::kw_shl: {
3489 bool NUW = EatIfPresent(lltok::kw_nuw);
3490 bool NSW = EatIfPresent(lltok::kw_nsw);
3491 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3493 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3495 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3496 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3499 case lltok::kw_fadd:
3500 case lltok::kw_fsub:
3501 case lltok::kw_fmul:
3502 case lltok::kw_fdiv:
3503 case lltok::kw_frem: {
3504 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3505 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3509 Inst->setFastMathFlags(FMF);
3513 case lltok::kw_sdiv:
3514 case lltok::kw_udiv:
3515 case lltok::kw_lshr:
3516 case lltok::kw_ashr: {
3517 bool Exact = EatIfPresent(lltok::kw_exact);
3519 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3520 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3524 case lltok::kw_urem:
3525 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3528 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3529 case lltok::kw_icmp:
3530 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3532 case lltok::kw_trunc:
3533 case lltok::kw_zext:
3534 case lltok::kw_sext:
3535 case lltok::kw_fptrunc:
3536 case lltok::kw_fpext:
3537 case lltok::kw_bitcast:
3538 case lltok::kw_addrspacecast:
3539 case lltok::kw_uitofp:
3540 case lltok::kw_sitofp:
3541 case lltok::kw_fptoui:
3542 case lltok::kw_fptosi:
3543 case lltok::kw_inttoptr:
3544 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3546 case lltok::kw_select: return ParseSelect(Inst, PFS);
3547 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3548 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3549 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3550 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3551 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3552 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3554 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3555 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3556 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3558 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3559 case lltok::kw_load: return ParseLoad(Inst, PFS);
3560 case lltok::kw_store: return ParseStore(Inst, PFS);
3561 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3562 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3563 case lltok::kw_fence: return ParseFence(Inst, PFS);
3564 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3565 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3566 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3570 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3571 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3572 if (Opc == Instruction::FCmp) {
3573 switch (Lex.getKind()) {
3574 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3575 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3576 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3577 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3578 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3579 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3580 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3581 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3582 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3583 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3584 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3585 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3586 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3587 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3588 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3589 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3590 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3593 switch (Lex.getKind()) {
3594 default: return TokError("expected icmp predicate (e.g. 'eq')");
3595 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3596 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3597 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3598 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3599 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3600 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3601 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3602 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3603 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3604 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3611 //===----------------------------------------------------------------------===//
3612 // Terminator Instructions.
3613 //===----------------------------------------------------------------------===//
3615 /// ParseRet - Parse a return instruction.
3616 /// ::= 'ret' void (',' !dbg, !1)*
3617 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3618 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3619 PerFunctionState &PFS) {
3620 SMLoc TypeLoc = Lex.getLoc();
3622 if (ParseType(Ty, true /*void allowed*/)) return true;
3624 Type *ResType = PFS.getFunction().getReturnType();
3626 if (Ty->isVoidTy()) {
3627 if (!ResType->isVoidTy())
3628 return Error(TypeLoc, "value doesn't match function result type '" +
3629 getTypeString(ResType) + "'");
3631 Inst = ReturnInst::Create(Context);
3636 if (ParseValue(Ty, RV, PFS)) return true;
3638 if (ResType != RV->getType())
3639 return Error(TypeLoc, "value doesn't match function result type '" +
3640 getTypeString(ResType) + "'");
3642 Inst = ReturnInst::Create(Context, RV);
3648 /// ::= 'br' TypeAndValue
3649 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3650 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3653 BasicBlock *Op1, *Op2;
3654 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3656 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3657 Inst = BranchInst::Create(BB);
3661 if (Op0->getType() != Type::getInt1Ty(Context))
3662 return Error(Loc, "branch condition must have 'i1' type");
3664 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3665 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3666 ParseToken(lltok::comma, "expected ',' after true destination") ||
3667 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3670 Inst = BranchInst::Create(Op1, Op2, Op0);
3676 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3678 /// ::= (TypeAndValue ',' TypeAndValue)*
3679 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3680 LocTy CondLoc, BBLoc;
3682 BasicBlock *DefaultBB;
3683 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3684 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3685 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3686 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3689 if (!Cond->getType()->isIntegerTy())
3690 return Error(CondLoc, "switch condition must have integer type");
3692 // Parse the jump table pairs.
3693 SmallPtrSet<Value*, 32> SeenCases;
3694 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3695 while (Lex.getKind() != lltok::rsquare) {
3699 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3700 ParseToken(lltok::comma, "expected ',' after case value") ||
3701 ParseTypeAndBasicBlock(DestBB, PFS))
3704 if (!SeenCases.insert(Constant))
3705 return Error(CondLoc, "duplicate case value in switch");
3706 if (!isa<ConstantInt>(Constant))
3707 return Error(CondLoc, "case value is not a constant integer");
3709 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3712 Lex.Lex(); // Eat the ']'.
3714 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3715 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3716 SI->addCase(Table[i].first, Table[i].second);
3723 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3724 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3727 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3728 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3729 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3732 if (!Address->getType()->isPointerTy())
3733 return Error(AddrLoc, "indirectbr address must have pointer type");
3735 // Parse the destination list.
3736 SmallVector<BasicBlock*, 16> DestList;
3738 if (Lex.getKind() != lltok::rsquare) {
3740 if (ParseTypeAndBasicBlock(DestBB, PFS))
3742 DestList.push_back(DestBB);
3744 while (EatIfPresent(lltok::comma)) {
3745 if (ParseTypeAndBasicBlock(DestBB, PFS))
3747 DestList.push_back(DestBB);
3751 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3754 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3755 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3756 IBI->addDestination(DestList[i]);
3763 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3764 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3765 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3766 LocTy CallLoc = Lex.getLoc();
3767 AttrBuilder RetAttrs, FnAttrs;
3768 std::vector<unsigned> FwdRefAttrGrps;
3771 Type *RetType = nullptr;
3774 SmallVector<ParamInfo, 16> ArgList;
3776 BasicBlock *NormalBB, *UnwindBB;
3777 if (ParseOptionalCallingConv(CC) ||
3778 ParseOptionalReturnAttrs(RetAttrs) ||
3779 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3780 ParseValID(CalleeID) ||
3781 ParseParameterList(ArgList, PFS) ||
3782 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3784 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3785 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3786 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3787 ParseTypeAndBasicBlock(UnwindBB, PFS))
3790 // If RetType is a non-function pointer type, then this is the short syntax
3791 // for the call, which means that RetType is just the return type. Infer the
3792 // rest of the function argument types from the arguments that are present.
3793 PointerType *PFTy = nullptr;
3794 FunctionType *Ty = nullptr;
3795 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3796 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3797 // Pull out the types of all of the arguments...
3798 std::vector<Type*> ParamTypes;
3799 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3800 ParamTypes.push_back(ArgList[i].V->getType());
3802 if (!FunctionType::isValidReturnType(RetType))
3803 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3805 Ty = FunctionType::get(RetType, ParamTypes, false);
3806 PFTy = PointerType::getUnqual(Ty);
3809 // Look up the callee.
3811 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3813 // Set up the Attribute for the function.
3814 SmallVector<AttributeSet, 8> Attrs;
3815 if (RetAttrs.hasAttributes())
3816 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3817 AttributeSet::ReturnIndex,
3820 SmallVector<Value*, 8> Args;
3822 // Loop through FunctionType's arguments and ensure they are specified
3823 // correctly. Also, gather any parameter attributes.
3824 FunctionType::param_iterator I = Ty->param_begin();
3825 FunctionType::param_iterator E = Ty->param_end();
3826 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3827 Type *ExpectedTy = nullptr;
3830 } else if (!Ty->isVarArg()) {
3831 return Error(ArgList[i].Loc, "too many arguments specified");
3834 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3835 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3836 getTypeString(ExpectedTy) + "'");
3837 Args.push_back(ArgList[i].V);
3838 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3839 AttrBuilder B(ArgList[i].Attrs, i + 1);
3840 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3845 return Error(CallLoc, "not enough parameters specified for call");
3847 if (FnAttrs.hasAttributes())
3848 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3849 AttributeSet::FunctionIndex,
3852 // Finish off the Attribute and check them
3853 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3855 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3856 II->setCallingConv(CC);
3857 II->setAttributes(PAL);
3858 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3864 /// ::= 'resume' TypeAndValue
3865 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3866 Value *Exn; LocTy ExnLoc;
3867 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3870 ResumeInst *RI = ResumeInst::Create(Exn);
3875 //===----------------------------------------------------------------------===//
3876 // Binary Operators.
3877 //===----------------------------------------------------------------------===//
3880 /// ::= ArithmeticOps TypeAndValue ',' Value
3882 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3883 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3884 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3885 unsigned Opc, unsigned OperandType) {
3886 LocTy Loc; Value *LHS, *RHS;
3887 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3888 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3889 ParseValue(LHS->getType(), RHS, PFS))
3893 switch (OperandType) {
3894 default: llvm_unreachable("Unknown operand type!");
3895 case 0: // int or FP.
3896 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3897 LHS->getType()->isFPOrFPVectorTy();
3899 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3900 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3904 return Error(Loc, "invalid operand type for instruction");
3906 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3911 /// ::= ArithmeticOps TypeAndValue ',' Value {
3912 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3914 LocTy Loc; Value *LHS, *RHS;
3915 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3916 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3917 ParseValue(LHS->getType(), RHS, PFS))
3920 if (!LHS->getType()->isIntOrIntVectorTy())
3921 return Error(Loc,"instruction requires integer or integer vector operands");
3923 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3929 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3930 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3931 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3933 // Parse the integer/fp comparison predicate.
3937 if (ParseCmpPredicate(Pred, Opc) ||
3938 ParseTypeAndValue(LHS, Loc, PFS) ||
3939 ParseToken(lltok::comma, "expected ',' after compare value") ||
3940 ParseValue(LHS->getType(), RHS, PFS))
3943 if (Opc == Instruction::FCmp) {
3944 if (!LHS->getType()->isFPOrFPVectorTy())
3945 return Error(Loc, "fcmp requires floating point operands");
3946 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3948 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3949 if (!LHS->getType()->isIntOrIntVectorTy() &&
3950 !LHS->getType()->getScalarType()->isPointerTy())
3951 return Error(Loc, "icmp requires integer operands");
3952 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3957 //===----------------------------------------------------------------------===//
3958 // Other Instructions.
3959 //===----------------------------------------------------------------------===//
3963 /// ::= CastOpc TypeAndValue 'to' Type
3964 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3968 Type *DestTy = nullptr;
3969 if (ParseTypeAndValue(Op, Loc, PFS) ||
3970 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3974 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3975 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3976 return Error(Loc, "invalid cast opcode for cast from '" +
3977 getTypeString(Op->getType()) + "' to '" +
3978 getTypeString(DestTy) + "'");
3980 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3985 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3986 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3988 Value *Op0, *Op1, *Op2;
3989 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3990 ParseToken(lltok::comma, "expected ',' after select condition") ||
3991 ParseTypeAndValue(Op1, PFS) ||
3992 ParseToken(lltok::comma, "expected ',' after select value") ||
3993 ParseTypeAndValue(Op2, PFS))
3996 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3997 return Error(Loc, Reason);
3999 Inst = SelectInst::Create(Op0, Op1, Op2);
4004 /// ::= 'va_arg' TypeAndValue ',' Type
4005 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4007 Type *EltTy = nullptr;
4009 if (ParseTypeAndValue(Op, PFS) ||
4010 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4011 ParseType(EltTy, TypeLoc))
4014 if (!EltTy->isFirstClassType())
4015 return Error(TypeLoc, "va_arg requires operand with first class type");
4017 Inst = new VAArgInst(Op, EltTy);
4021 /// ParseExtractElement
4022 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4023 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4026 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4027 ParseToken(lltok::comma, "expected ',' after extract value") ||
4028 ParseTypeAndValue(Op1, PFS))
4031 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4032 return Error(Loc, "invalid extractelement operands");
4034 Inst = ExtractElementInst::Create(Op0, Op1);
4038 /// ParseInsertElement
4039 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4040 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4042 Value *Op0, *Op1, *Op2;
4043 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4044 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4045 ParseTypeAndValue(Op1, PFS) ||
4046 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4047 ParseTypeAndValue(Op2, PFS))
4050 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4051 return Error(Loc, "invalid insertelement operands");
4053 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4057 /// ParseShuffleVector
4058 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4059 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4061 Value *Op0, *Op1, *Op2;
4062 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4063 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4064 ParseTypeAndValue(Op1, PFS) ||
4065 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4066 ParseTypeAndValue(Op2, PFS))
4069 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4070 return Error(Loc, "invalid shufflevector operands");
4072 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4077 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4078 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4079 Type *Ty = nullptr; LocTy TypeLoc;
4082 if (ParseType(Ty, TypeLoc) ||
4083 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4084 ParseValue(Ty, Op0, PFS) ||
4085 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4086 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4087 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4090 bool AteExtraComma = false;
4091 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4093 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4095 if (!EatIfPresent(lltok::comma))
4098 if (Lex.getKind() == lltok::MetadataVar) {
4099 AteExtraComma = true;
4103 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4104 ParseValue(Ty, Op0, PFS) ||
4105 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4106 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4107 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4111 if (!Ty->isFirstClassType())
4112 return Error(TypeLoc, "phi node must have first class type");
4114 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4115 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4116 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4118 return AteExtraComma ? InstExtraComma : InstNormal;
4122 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4124 /// ::= 'catch' TypeAndValue
4126 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4127 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4128 Type *Ty = nullptr; LocTy TyLoc;
4129 Value *PersFn; LocTy PersFnLoc;
4131 if (ParseType(Ty, TyLoc) ||
4132 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4133 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4136 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4137 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4139 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4140 LandingPadInst::ClauseType CT;
4141 if (EatIfPresent(lltok::kw_catch))
4142 CT = LandingPadInst::Catch;
4143 else if (EatIfPresent(lltok::kw_filter))
4144 CT = LandingPadInst::Filter;
4146 return TokError("expected 'catch' or 'filter' clause type");
4150 if (ParseTypeAndValue(V, VLoc, PFS)) {
4155 // A 'catch' type expects a non-array constant. A filter clause expects an
4157 if (CT == LandingPadInst::Catch) {
4158 if (isa<ArrayType>(V->getType()))
4159 Error(VLoc, "'catch' clause has an invalid type");
4161 if (!isa<ArrayType>(V->getType()))
4162 Error(VLoc, "'filter' clause has an invalid type");
4165 LP->addClause(cast<Constant>(V));
4173 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4174 /// ParameterList OptionalAttrs
4175 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4176 /// ParameterList OptionalAttrs
4177 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4178 /// ParameterList OptionalAttrs
4179 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4180 CallInst::TailCallKind TCK) {
4181 AttrBuilder RetAttrs, FnAttrs;
4182 std::vector<unsigned> FwdRefAttrGrps;
4185 Type *RetType = nullptr;
4188 SmallVector<ParamInfo, 16> ArgList;
4189 LocTy CallLoc = Lex.getLoc();
4191 if ((TCK != CallInst::TCK_None &&
4192 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4193 ParseOptionalCallingConv(CC) ||
4194 ParseOptionalReturnAttrs(RetAttrs) ||
4195 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4196 ParseValID(CalleeID) ||
4197 ParseParameterList(ArgList, PFS) ||
4198 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4202 // If RetType is a non-function pointer type, then this is the short syntax
4203 // for the call, which means that RetType is just the return type. Infer the
4204 // rest of the function argument types from the arguments that are present.
4205 PointerType *PFTy = nullptr;
4206 FunctionType *Ty = nullptr;
4207 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4208 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4209 // Pull out the types of all of the arguments...
4210 std::vector<Type*> ParamTypes;
4211 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4212 ParamTypes.push_back(ArgList[i].V->getType());
4214 if (!FunctionType::isValidReturnType(RetType))
4215 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4217 Ty = FunctionType::get(RetType, ParamTypes, false);
4218 PFTy = PointerType::getUnqual(Ty);
4221 // Look up the callee.
4223 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4225 // Set up the Attribute for the function.
4226 SmallVector<AttributeSet, 8> Attrs;
4227 if (RetAttrs.hasAttributes())
4228 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4229 AttributeSet::ReturnIndex,
4232 SmallVector<Value*, 8> Args;
4234 // Loop through FunctionType's arguments and ensure they are specified
4235 // correctly. Also, gather any parameter attributes.
4236 FunctionType::param_iterator I = Ty->param_begin();
4237 FunctionType::param_iterator E = Ty->param_end();
4238 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4239 Type *ExpectedTy = nullptr;
4242 } else if (!Ty->isVarArg()) {
4243 return Error(ArgList[i].Loc, "too many arguments specified");
4246 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4247 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4248 getTypeString(ExpectedTy) + "'");
4249 Args.push_back(ArgList[i].V);
4250 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4251 AttrBuilder B(ArgList[i].Attrs, i + 1);
4252 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4257 return Error(CallLoc, "not enough parameters specified for call");
4259 if (FnAttrs.hasAttributes())
4260 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4261 AttributeSet::FunctionIndex,
4264 // Finish off the Attribute and check them
4265 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4267 CallInst *CI = CallInst::Create(Callee, Args);
4268 CI->setTailCallKind(TCK);
4269 CI->setCallingConv(CC);
4270 CI->setAttributes(PAL);
4271 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4276 //===----------------------------------------------------------------------===//
4277 // Memory Instructions.
4278 //===----------------------------------------------------------------------===//
4281 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4282 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4283 Value *Size = nullptr;
4285 unsigned Alignment = 0;
4288 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4290 if (ParseType(Ty)) return true;
4292 bool AteExtraComma = false;
4293 if (EatIfPresent(lltok::comma)) {
4294 if (Lex.getKind() == lltok::kw_align) {
4295 if (ParseOptionalAlignment(Alignment)) return true;
4296 } else if (Lex.getKind() == lltok::MetadataVar) {
4297 AteExtraComma = true;
4299 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4300 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4305 if (Size && !Size->getType()->isIntegerTy())
4306 return Error(SizeLoc, "element count must have integer type");
4308 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4309 AI->setUsedWithInAlloca(IsInAlloca);
4311 return AteExtraComma ? InstExtraComma : InstNormal;
4315 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4316 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4317 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4318 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4319 Value *Val; LocTy Loc;
4320 unsigned Alignment = 0;
4321 bool AteExtraComma = false;
4322 bool isAtomic = false;
4323 AtomicOrdering Ordering = NotAtomic;
4324 SynchronizationScope Scope = CrossThread;
4326 if (Lex.getKind() == lltok::kw_atomic) {
4331 bool isVolatile = false;
4332 if (Lex.getKind() == lltok::kw_volatile) {
4337 if (ParseTypeAndValue(Val, Loc, PFS) ||
4338 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4339 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4342 if (!Val->getType()->isPointerTy() ||
4343 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4344 return Error(Loc, "load operand must be a pointer to a first class type");
4345 if (isAtomic && !Alignment)
4346 return Error(Loc, "atomic load must have explicit non-zero alignment");
4347 if (Ordering == Release || Ordering == AcquireRelease)
4348 return Error(Loc, "atomic load cannot use Release ordering");
4350 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4351 return AteExtraComma ? InstExtraComma : InstNormal;
4356 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4357 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4358 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4359 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4360 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4361 unsigned Alignment = 0;
4362 bool AteExtraComma = false;
4363 bool isAtomic = false;
4364 AtomicOrdering Ordering = NotAtomic;
4365 SynchronizationScope Scope = CrossThread;
4367 if (Lex.getKind() == lltok::kw_atomic) {
4372 bool isVolatile = false;
4373 if (Lex.getKind() == lltok::kw_volatile) {
4378 if (ParseTypeAndValue(Val, Loc, PFS) ||
4379 ParseToken(lltok::comma, "expected ',' after store operand") ||
4380 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4381 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4382 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4385 if (!Ptr->getType()->isPointerTy())
4386 return Error(PtrLoc, "store operand must be a pointer");
4387 if (!Val->getType()->isFirstClassType())
4388 return Error(Loc, "store operand must be a first class value");
4389 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4390 return Error(Loc, "stored value and pointer type do not match");
4391 if (isAtomic && !Alignment)
4392 return Error(Loc, "atomic store must have explicit non-zero alignment");
4393 if (Ordering == Acquire || Ordering == AcquireRelease)
4394 return Error(Loc, "atomic store cannot use Acquire ordering");
4396 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4397 return AteExtraComma ? InstExtraComma : InstNormal;
4401 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4402 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4403 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4404 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4405 bool AteExtraComma = false;
4406 AtomicOrdering SuccessOrdering = NotAtomic;
4407 AtomicOrdering FailureOrdering = NotAtomic;
4408 SynchronizationScope Scope = CrossThread;
4409 bool isVolatile = false;
4410 bool isWeak = false;
4412 if (EatIfPresent(lltok::kw_weak))
4415 if (EatIfPresent(lltok::kw_volatile))
4418 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4419 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4420 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4421 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4422 ParseTypeAndValue(New, NewLoc, PFS) ||
4423 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4424 ParseOrdering(FailureOrdering))
4427 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4428 return TokError("cmpxchg cannot be unordered");
4429 if (SuccessOrdering < FailureOrdering)
4430 return TokError("cmpxchg must be at least as ordered on success as failure");
4431 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4432 return TokError("cmpxchg failure ordering cannot include release semantics");
4433 if (!Ptr->getType()->isPointerTy())
4434 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4435 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4436 return Error(CmpLoc, "compare value and pointer type do not match");
4437 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4438 return Error(NewLoc, "new value and pointer type do not match");
4439 if (!New->getType()->isIntegerTy())
4440 return Error(NewLoc, "cmpxchg operand must be an integer");
4441 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4442 if (Size < 8 || (Size & (Size - 1)))
4443 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4446 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4447 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4448 CXI->setVolatile(isVolatile);
4449 CXI->setWeak(isWeak);
4451 return AteExtraComma ? InstExtraComma : InstNormal;
4455 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4456 /// 'singlethread'? AtomicOrdering
4457 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4458 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4459 bool AteExtraComma = false;
4460 AtomicOrdering Ordering = NotAtomic;
4461 SynchronizationScope Scope = CrossThread;
4462 bool isVolatile = false;
4463 AtomicRMWInst::BinOp Operation;
4465 if (EatIfPresent(lltok::kw_volatile))
4468 switch (Lex.getKind()) {
4469 default: return TokError("expected binary operation in atomicrmw");
4470 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4471 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4472 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4473 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4474 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4475 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4476 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4477 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4478 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4479 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4480 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4482 Lex.Lex(); // Eat the operation.
4484 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4485 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4486 ParseTypeAndValue(Val, ValLoc, PFS) ||
4487 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4490 if (Ordering == Unordered)
4491 return TokError("atomicrmw cannot be unordered");
4492 if (!Ptr->getType()->isPointerTy())
4493 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4494 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4495 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4496 if (!Val->getType()->isIntegerTy())
4497 return Error(ValLoc, "atomicrmw operand must be an integer");
4498 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4499 if (Size < 8 || (Size & (Size - 1)))
4500 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4503 AtomicRMWInst *RMWI =
4504 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4505 RMWI->setVolatile(isVolatile);
4507 return AteExtraComma ? InstExtraComma : InstNormal;
4511 /// ::= 'fence' 'singlethread'? AtomicOrdering
4512 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4513 AtomicOrdering Ordering = NotAtomic;
4514 SynchronizationScope Scope = CrossThread;
4515 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4518 if (Ordering == Unordered)
4519 return TokError("fence cannot be unordered");
4520 if (Ordering == Monotonic)
4521 return TokError("fence cannot be monotonic");
4523 Inst = new FenceInst(Context, Ordering, Scope);
4527 /// ParseGetElementPtr
4528 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4529 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4530 Value *Ptr = nullptr;
4531 Value *Val = nullptr;
4534 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4536 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4538 Type *BaseType = Ptr->getType();
4539 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4540 if (!BasePointerType)
4541 return Error(Loc, "base of getelementptr must be a pointer");
4543 SmallVector<Value*, 16> Indices;
4544 bool AteExtraComma = false;
4545 while (EatIfPresent(lltok::comma)) {
4546 if (Lex.getKind() == lltok::MetadataVar) {
4547 AteExtraComma = true;
4550 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4551 if (!Val->getType()->getScalarType()->isIntegerTy())
4552 return Error(EltLoc, "getelementptr index must be an integer");
4553 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4554 return Error(EltLoc, "getelementptr index type missmatch");
4555 if (Val->getType()->isVectorTy()) {
4556 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4557 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4558 if (ValNumEl != PtrNumEl)
4559 return Error(EltLoc,
4560 "getelementptr vector index has a wrong number of elements");
4562 Indices.push_back(Val);
4565 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4566 return Error(Loc, "base element of getelementptr must be sized");
4568 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4569 return Error(Loc, "invalid getelementptr indices");
4570 Inst = GetElementPtrInst::Create(Ptr, Indices);
4572 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4573 return AteExtraComma ? InstExtraComma : InstNormal;
4576 /// ParseExtractValue
4577 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4578 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4579 Value *Val; LocTy Loc;
4580 SmallVector<unsigned, 4> Indices;
4582 if (ParseTypeAndValue(Val, Loc, PFS) ||
4583 ParseIndexList(Indices, AteExtraComma))
4586 if (!Val->getType()->isAggregateType())
4587 return Error(Loc, "extractvalue operand must be aggregate type");
4589 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4590 return Error(Loc, "invalid indices for extractvalue");
4591 Inst = ExtractValueInst::Create(Val, Indices);
4592 return AteExtraComma ? InstExtraComma : InstNormal;
4595 /// ParseInsertValue
4596 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4597 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4598 Value *Val0, *Val1; LocTy Loc0, Loc1;
4599 SmallVector<unsigned, 4> Indices;
4601 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4602 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4603 ParseTypeAndValue(Val1, Loc1, PFS) ||
4604 ParseIndexList(Indices, AteExtraComma))
4607 if (!Val0->getType()->isAggregateType())
4608 return Error(Loc0, "insertvalue operand must be aggregate type");
4610 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4611 return Error(Loc0, "invalid indices for insertvalue");
4612 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4613 return AteExtraComma ? InstExtraComma : InstNormal;
4616 //===----------------------------------------------------------------------===//
4617 // Embedded metadata.
4618 //===----------------------------------------------------------------------===//
4620 /// ParseMDNodeVector
4621 /// ::= Element (',' Element)*
4623 /// ::= 'null' | TypeAndValue
4624 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4625 PerFunctionState *PFS) {
4626 // Check for an empty list.
4627 if (Lex.getKind() == lltok::rbrace)
4631 // Null is a special case since it is typeless.
4632 if (EatIfPresent(lltok::kw_null)) {
4633 Elts.push_back(nullptr);
4638 if (ParseTypeAndValue(V, PFS)) return true;
4640 } while (EatIfPresent(lltok::comma));