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 (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
174 Twine(ForwardRefValIDs.begin()->first) + "'");
176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
179 Twine(ForwardRefMDNodes.begin()->first) + "'");
182 // Look for intrinsic functions and CallInst that need to be upgraded
183 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
186 UpgradeDebugInfo(*M);
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193 PerFunctionState *PFS) {
194 // Loop over all the references, resolving them.
195 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
198 if (Refs[i].first.Kind == ValID::t_LocalName)
199 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
201 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203 return Error(Refs[i].first.Loc,
204 "cannot take address of numeric label after the function is defined");
206 Res = dyn_cast_or_null<BasicBlock>(
207 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
211 return Error(Refs[i].first.Loc,
212 "referenced value is not a basic block");
214 // Get the BlockAddress for this and update references to use it.
215 BlockAddress *BA = BlockAddress::get(TheFn, Res);
216 Refs[i].second->replaceAllUsesWith(BA);
217 Refs[i].second->eraseFromParent();
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
227 bool LLParser::ParseTopLevelEntities() {
229 switch (Lex.getKind()) {
230 default: return TokError("expected top-level entity");
231 case lltok::Eof: return false;
232 case lltok::kw_declare: if (ParseDeclare()) return true; break;
233 case lltok::kw_define: if (ParseDefine()) return true; break;
234 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
235 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
236 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238 case lltok::LocalVar: if (ParseNamedType()) return true; break;
239 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
240 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
241 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
242 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
244 // The Global variable production with no name can have many different
245 // optional leading prefixes, the production is:
246 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248 // ('constant'|'global') ...
249 case lltok::kw_private: // OptionalLinkage
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_linker_private: // Obsolete OptionalLinkage
252 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_extern_weak: // OptionalLinkage
260 case lltok::kw_external: { // OptionalLinkage
261 unsigned Linkage, Visibility, DLLStorageClass;
262 if (ParseOptionalLinkage(Linkage) ||
263 ParseOptionalVisibility(Visibility) ||
264 ParseOptionalDLLStorageClass(DLLStorageClass) ||
265 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
269 case lltok::kw_default: // OptionalVisibility
270 case lltok::kw_hidden: // OptionalVisibility
271 case lltok::kw_protected: { // OptionalVisibility
272 unsigned Visibility, DLLStorageClass;
273 if (ParseOptionalVisibility(Visibility) ||
274 ParseOptionalDLLStorageClass(DLLStorageClass) ||
275 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
280 case lltok::kw_thread_local: // OptionalThreadLocal
281 case lltok::kw_addrspace: // OptionalAddrSpace
282 case lltok::kw_constant: // GlobalType
283 case lltok::kw_global: // GlobalType
284 if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
287 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
294 /// ::= 'module' 'asm' STRINGCONSTANT
295 bool LLParser::ParseModuleAsm() {
296 assert(Lex.getKind() == lltok::kw_module);
300 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
301 ParseStringConstant(AsmStr)) return true;
303 M->appendModuleInlineAsm(AsmStr);
308 /// ::= 'target' 'triple' '=' STRINGCONSTANT
309 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
310 bool LLParser::ParseTargetDefinition() {
311 assert(Lex.getKind() == lltok::kw_target);
314 default: return TokError("unknown target property");
315 case lltok::kw_triple:
317 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
318 ParseStringConstant(Str))
320 M->setTargetTriple(Str);
322 case lltok::kw_datalayout:
324 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
325 ParseStringConstant(Str))
327 M->setDataLayout(Str);
333 /// ::= 'deplibs' '=' '[' ']'
334 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
335 /// FIXME: Remove in 4.0. Currently parse, but ignore.
336 bool LLParser::ParseDepLibs() {
337 assert(Lex.getKind() == lltok::kw_deplibs);
339 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
340 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
343 if (EatIfPresent(lltok::rsquare))
348 if (ParseStringConstant(Str)) return true;
349 } while (EatIfPresent(lltok::comma));
351 return ParseToken(lltok::rsquare, "expected ']' at end of list");
354 /// ParseUnnamedType:
355 /// ::= LocalVarID '=' 'type' type
356 bool LLParser::ParseUnnamedType() {
357 LocTy TypeLoc = Lex.getLoc();
358 unsigned TypeID = Lex.getUIntVal();
359 Lex.Lex(); // eat LocalVarID;
361 if (ParseToken(lltok::equal, "expected '=' after name") ||
362 ParseToken(lltok::kw_type, "expected 'type' after '='"))
365 if (TypeID >= NumberedTypes.size())
366 NumberedTypes.resize(TypeID+1);
368 Type *Result = nullptr;
369 if (ParseStructDefinition(TypeLoc, "",
370 NumberedTypes[TypeID], Result)) return true;
372 if (!isa<StructType>(Result)) {
373 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
375 return Error(TypeLoc, "non-struct types may not be recursive");
376 Entry.first = Result;
377 Entry.second = SMLoc();
385 /// ::= LocalVar '=' 'type' type
386 bool LLParser::ParseNamedType() {
387 std::string Name = Lex.getStrVal();
388 LocTy NameLoc = Lex.getLoc();
389 Lex.Lex(); // eat LocalVar.
391 if (ParseToken(lltok::equal, "expected '=' after name") ||
392 ParseToken(lltok::kw_type, "expected 'type' after name"))
395 Type *Result = nullptr;
396 if (ParseStructDefinition(NameLoc, Name,
397 NamedTypes[Name], Result)) return true;
399 if (!isa<StructType>(Result)) {
400 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
402 return Error(NameLoc, "non-struct types may not be recursive");
403 Entry.first = Result;
404 Entry.second = SMLoc();
412 /// ::= 'declare' FunctionHeader
413 bool LLParser::ParseDeclare() {
414 assert(Lex.getKind() == lltok::kw_declare);
418 return ParseFunctionHeader(F, false);
422 /// ::= 'define' FunctionHeader '{' ...
423 bool LLParser::ParseDefine() {
424 assert(Lex.getKind() == lltok::kw_define);
428 return ParseFunctionHeader(F, true) ||
429 ParseFunctionBody(*F);
435 bool LLParser::ParseGlobalType(bool &IsConstant) {
436 if (Lex.getKind() == lltok::kw_constant)
438 else if (Lex.getKind() == lltok::kw_global)
442 return TokError("expected 'global' or 'constant'");
448 /// ParseUnnamedGlobal:
449 /// OptionalVisibility ALIAS ...
450 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
451 /// ... -> global variable
452 /// GlobalID '=' OptionalVisibility ALIAS ...
453 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454 /// ... -> global variable
455 bool LLParser::ParseUnnamedGlobal() {
456 unsigned VarID = NumberedVals.size();
458 LocTy NameLoc = Lex.getLoc();
460 // Handle the GlobalID form.
461 if (Lex.getKind() == lltok::GlobalID) {
462 if (Lex.getUIntVal() != VarID)
463 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
465 Lex.Lex(); // eat GlobalID;
467 if (ParseToken(lltok::equal, "expected '=' after name"))
472 unsigned Linkage, Visibility, DLLStorageClass;
473 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
474 ParseOptionalVisibility(Visibility) ||
475 ParseOptionalDLLStorageClass(DLLStorageClass))
478 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
479 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
481 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
484 /// ParseNamedGlobal:
485 /// GlobalVar '=' OptionalVisibility ALIAS ...
486 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487 /// ... -> global variable
488 bool LLParser::ParseNamedGlobal() {
489 assert(Lex.getKind() == lltok::GlobalVar);
490 LocTy NameLoc = Lex.getLoc();
491 std::string Name = Lex.getStrVal();
495 unsigned Linkage, Visibility, DLLStorageClass;
496 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
497 ParseOptionalLinkage(Linkage, HasLinkage) ||
498 ParseOptionalVisibility(Visibility) ||
499 ParseOptionalDLLStorageClass(DLLStorageClass))
502 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
503 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
505 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
509 // ::= '!' STRINGCONSTANT
510 bool LLParser::ParseMDString(MDString *&Result) {
512 if (ParseStringConstant(Str)) return true;
513 Result = MDString::get(Context, Str);
518 // ::= '!' MDNodeNumber
520 /// This version of ParseMDNodeID returns the slot number and null in the case
521 /// of a forward reference.
522 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
523 // !{ ..., !42, ... }
524 if (ParseUInt32(SlotNo)) return true;
526 // Check existing MDNode.
527 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
528 Result = NumberedMetadata[SlotNo];
534 bool LLParser::ParseMDNodeID(MDNode *&Result) {
535 // !{ ..., !42, ... }
537 if (ParseMDNodeID(Result, MID)) return true;
539 // If not a forward reference, just return it now.
540 if (Result) return false;
542 // Otherwise, create MDNode forward reference.
543 MDNode *FwdNode = MDNode::getTemporary(Context, None);
544 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
546 if (NumberedMetadata.size() <= MID)
547 NumberedMetadata.resize(MID+1);
548 NumberedMetadata[MID] = FwdNode;
553 /// ParseNamedMetadata:
554 /// !foo = !{ !1, !2 }
555 bool LLParser::ParseNamedMetadata() {
556 assert(Lex.getKind() == lltok::MetadataVar);
557 std::string Name = Lex.getStrVal();
560 if (ParseToken(lltok::equal, "expected '=' here") ||
561 ParseToken(lltok::exclaim, "Expected '!' here") ||
562 ParseToken(lltok::lbrace, "Expected '{' here"))
565 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
566 if (Lex.getKind() != lltok::rbrace)
568 if (ParseToken(lltok::exclaim, "Expected '!' here"))
572 if (ParseMDNodeID(N)) return true;
574 } while (EatIfPresent(lltok::comma));
576 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
582 /// ParseStandaloneMetadata:
584 bool LLParser::ParseStandaloneMetadata() {
585 assert(Lex.getKind() == lltok::exclaim);
587 unsigned MetadataID = 0;
591 SmallVector<Value *, 16> Elts;
592 if (ParseUInt32(MetadataID) ||
593 ParseToken(lltok::equal, "expected '=' here") ||
594 ParseType(Ty, TyLoc) ||
595 ParseToken(lltok::exclaim, "Expected '!' here") ||
596 ParseToken(lltok::lbrace, "Expected '{' here") ||
597 ParseMDNodeVector(Elts, nullptr) ||
598 ParseToken(lltok::rbrace, "expected end of metadata node"))
601 MDNode *Init = MDNode::get(Context, Elts);
603 // See if this was forward referenced, if so, handle it.
604 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
605 FI = ForwardRefMDNodes.find(MetadataID);
606 if (FI != ForwardRefMDNodes.end()) {
607 MDNode *Temp = FI->second.first;
608 Temp->replaceAllUsesWith(Init);
609 MDNode::deleteTemporary(Temp);
610 ForwardRefMDNodes.erase(FI);
612 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
614 if (MetadataID >= NumberedMetadata.size())
615 NumberedMetadata.resize(MetadataID+1);
617 if (NumberedMetadata[MetadataID] != nullptr)
618 return TokError("Metadata id is already used");
619 NumberedMetadata[MetadataID] = Init;
625 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
626 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
627 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
631 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
632 /// OptionalLinkage Aliasee
633 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
634 /// OptionalLinkage OptionalAddrSpace Type, Aliasee
639 /// Everything through DLL storage class has already been parsed.
641 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
642 unsigned Visibility, unsigned DLLStorageClass) {
643 assert(Lex.getKind() == lltok::kw_alias);
645 LocTy LinkageLoc = Lex.getLoc();
647 if (ParseOptionalLinkage(L))
650 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
652 if(!GlobalAlias::isValidLinkage(Linkage))
653 return Error(LinkageLoc, "invalid linkage type for alias");
655 if (!isValidVisibilityForLinkage(Visibility, L))
656 return Error(LinkageLoc,
657 "symbol with local linkage must have default visibility");
659 bool HasAddrSpace = Lex.getKind() == lltok::kw_addrspace;
661 LocTy AddrSpaceLoc = Lex.getLoc();
662 if (ParseOptionalAddrSpace(AddrSpace))
665 LocTy TyLoc = Lex.getLoc();
670 bool DifferentType = EatIfPresent(lltok::comma);
671 if (HasAddrSpace && !DifferentType)
672 return Error(AddrSpaceLoc, "A type is required if addrspace is given");
674 Type *AliaseeType = nullptr;
676 if (ParseType(AliaseeType))
680 auto *PTy = dyn_cast<PointerType>(Ty);
682 return Error(TyLoc, "An alias must have pointer type");
683 Ty = PTy->getElementType();
684 AddrSpace = PTy->getAddressSpace();
687 LocTy AliaseeLoc = Lex.getLoc();
689 if (ParseGlobalValue(AliaseeType, C))
692 auto *Aliasee = dyn_cast<GlobalObject>(C);
694 return Error(AliaseeLoc, "Alias must point to function or variable");
696 assert(Aliasee->getType()->isPointerTy());
698 // Okay, create the alias but do not insert it into the module yet.
699 std::unique_ptr<GlobalAlias> GA(
700 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
701 Name, Aliasee, /*Parent*/ nullptr));
702 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
703 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
705 // See if this value already exists in the symbol table. If so, it is either
706 // a redefinition or a definition of a forward reference.
707 if (GlobalValue *Val = M->getNamedValue(Name)) {
708 // See if this was a redefinition. If so, there is no entry in
710 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
711 I = ForwardRefVals.find(Name);
712 if (I == ForwardRefVals.end())
713 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
715 // Otherwise, this was a definition of forward ref. Verify that types
717 if (Val->getType() != GA->getType())
718 return Error(NameLoc,
719 "forward reference and definition of alias have different types");
721 // If they agree, just RAUW the old value with the alias and remove the
723 for (auto *User : Val->users()) {
724 if (auto *GA = dyn_cast<GlobalAlias>(User))
725 return Error(NameLoc, "Alias is pointed by alias " + GA->getName());
728 Val->replaceAllUsesWith(GA.get());
729 Val->eraseFromParent();
730 ForwardRefVals.erase(I);
733 // Insert into the module, we know its name won't collide now.
734 M->getAliasList().push_back(GA.get());
735 assert(GA->getName() == Name && "Should not be a name conflict!");
737 // The module owns this now
744 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
745 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
746 /// OptionalExternallyInitialized GlobalType Type Const
747 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
748 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
749 /// OptionalExternallyInitialized GlobalType Type Const
751 /// Everything up to and including OptionalDLLStorageClass has been parsed
754 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
755 unsigned Linkage, bool HasLinkage,
756 unsigned Visibility, unsigned DLLStorageClass) {
757 if (!isValidVisibilityForLinkage(Visibility, Linkage))
758 return Error(NameLoc,
759 "symbol with local linkage must have default visibility");
762 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
763 GlobalVariable::ThreadLocalMode TLM;
764 LocTy UnnamedAddrLoc;
765 LocTy IsExternallyInitializedLoc;
769 if (ParseOptionalThreadLocal(TLM) ||
770 ParseOptionalAddrSpace(AddrSpace) ||
771 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
773 ParseOptionalToken(lltok::kw_externally_initialized,
774 IsExternallyInitialized,
775 &IsExternallyInitializedLoc) ||
776 ParseGlobalType(IsConstant) ||
777 ParseType(Ty, TyLoc))
780 // If the linkage is specified and is external, then no initializer is
782 Constant *Init = nullptr;
783 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
784 Linkage != GlobalValue::ExternalLinkage)) {
785 if (ParseGlobalValue(Ty, Init))
789 if (Ty->isFunctionTy() || Ty->isLabelTy())
790 return Error(TyLoc, "invalid type for global variable");
792 GlobalVariable *GV = nullptr;
794 // See if the global was forward referenced, if so, use the global.
796 if (GlobalValue *GVal = M->getNamedValue(Name)) {
797 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
798 return Error(NameLoc, "redefinition of global '@" + Name + "'");
799 GV = cast<GlobalVariable>(GVal);
802 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
803 I = ForwardRefValIDs.find(NumberedVals.size());
804 if (I != ForwardRefValIDs.end()) {
805 GV = cast<GlobalVariable>(I->second.first);
806 ForwardRefValIDs.erase(I);
811 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
812 Name, nullptr, GlobalVariable::NotThreadLocal,
815 if (GV->getType()->getElementType() != Ty)
817 "forward reference and definition of global have different types");
819 // Move the forward-reference to the correct spot in the module.
820 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
824 NumberedVals.push_back(GV);
826 // Set the parsed properties on the global.
828 GV->setInitializer(Init);
829 GV->setConstant(IsConstant);
830 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
831 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
832 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
833 GV->setExternallyInitialized(IsExternallyInitialized);
834 GV->setThreadLocalMode(TLM);
835 GV->setUnnamedAddr(UnnamedAddr);
837 // Parse attributes on the global.
838 while (Lex.getKind() == lltok::comma) {
841 if (Lex.getKind() == lltok::kw_section) {
843 GV->setSection(Lex.getStrVal());
844 if (ParseToken(lltok::StringConstant, "expected global section string"))
846 } else if (Lex.getKind() == lltok::kw_align) {
848 if (ParseOptionalAlignment(Alignment)) return true;
849 GV->setAlignment(Alignment);
851 TokError("unknown global variable property!");
858 /// ParseUnnamedAttrGrp
859 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
860 bool LLParser::ParseUnnamedAttrGrp() {
861 assert(Lex.getKind() == lltok::kw_attributes);
862 LocTy AttrGrpLoc = Lex.getLoc();
865 assert(Lex.getKind() == lltok::AttrGrpID);
866 unsigned VarID = Lex.getUIntVal();
867 std::vector<unsigned> unused;
871 if (ParseToken(lltok::equal, "expected '=' here") ||
872 ParseToken(lltok::lbrace, "expected '{' here") ||
873 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
875 ParseToken(lltok::rbrace, "expected end of attribute group"))
878 if (!NumberedAttrBuilders[VarID].hasAttributes())
879 return Error(AttrGrpLoc, "attribute group has no attributes");
884 /// ParseFnAttributeValuePairs
885 /// ::= <attr> | <attr> '=' <value>
886 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
887 std::vector<unsigned> &FwdRefAttrGrps,
888 bool inAttrGrp, LocTy &BuiltinLoc) {
889 bool HaveError = false;
894 lltok::Kind Token = Lex.getKind();
895 if (Token == lltok::kw_builtin)
896 BuiltinLoc = Lex.getLoc();
899 if (!inAttrGrp) return HaveError;
900 return Error(Lex.getLoc(), "unterminated attribute group");
905 case lltok::AttrGrpID: {
906 // Allow a function to reference an attribute group:
908 // define void @foo() #1 { ... }
912 "cannot have an attribute group reference in an attribute group");
914 unsigned AttrGrpNum = Lex.getUIntVal();
915 if (inAttrGrp) break;
917 // Save the reference to the attribute group. We'll fill it in later.
918 FwdRefAttrGrps.push_back(AttrGrpNum);
921 // Target-dependent attributes:
922 case lltok::StringConstant: {
923 std::string Attr = Lex.getStrVal();
926 if (EatIfPresent(lltok::equal) &&
927 ParseStringConstant(Val))
930 B.addAttribute(Attr, Val);
934 // Target-independent attributes:
935 case lltok::kw_align: {
936 // As a hack, we allow function alignment to be initially parsed as an
937 // attribute on a function declaration/definition or added to an attribute
938 // group and later moved to the alignment field.
942 if (ParseToken(lltok::equal, "expected '=' here") ||
943 ParseUInt32(Alignment))
946 if (ParseOptionalAlignment(Alignment))
949 B.addAlignmentAttr(Alignment);
952 case lltok::kw_alignstack: {
956 if (ParseToken(lltok::equal, "expected '=' here") ||
957 ParseUInt32(Alignment))
960 if (ParseOptionalStackAlignment(Alignment))
963 B.addStackAlignmentAttr(Alignment);
966 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
967 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
968 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
969 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
970 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
971 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
972 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
973 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
974 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
975 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
976 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
977 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
978 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
979 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
980 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
981 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
982 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
983 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
984 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
985 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
986 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
987 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
988 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
989 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
990 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
991 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
994 case lltok::kw_inreg:
995 case lltok::kw_signext:
996 case lltok::kw_zeroext:
999 "invalid use of attribute on a function");
1001 case lltok::kw_byval:
1002 case lltok::kw_inalloca:
1003 case lltok::kw_nest:
1004 case lltok::kw_noalias:
1005 case lltok::kw_nocapture:
1006 case lltok::kw_nonnull:
1007 case lltok::kw_returned:
1008 case lltok::kw_sret:
1011 "invalid use of parameter-only attribute on a function");
1019 //===----------------------------------------------------------------------===//
1020 // GlobalValue Reference/Resolution Routines.
1021 //===----------------------------------------------------------------------===//
1023 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1024 /// forward reference record if needed. This can return null if the value
1025 /// exists but does not have the right type.
1026 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1028 PointerType *PTy = dyn_cast<PointerType>(Ty);
1030 Error(Loc, "global variable reference must have pointer type");
1034 // Look this name up in the normal function symbol table.
1036 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1038 // If this is a forward reference for the value, see if we already created a
1039 // forward ref record.
1041 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1042 I = ForwardRefVals.find(Name);
1043 if (I != ForwardRefVals.end())
1044 Val = I->second.first;
1047 // If we have the value in the symbol table or fwd-ref table, return it.
1049 if (Val->getType() == Ty) return Val;
1050 Error(Loc, "'@" + Name + "' defined with type '" +
1051 getTypeString(Val->getType()) + "'");
1055 // Otherwise, create a new forward reference for this value and remember it.
1056 GlobalValue *FwdVal;
1057 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1058 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1060 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1061 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1062 nullptr, GlobalVariable::NotThreadLocal,
1063 PTy->getAddressSpace());
1065 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1069 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1070 PointerType *PTy = dyn_cast<PointerType>(Ty);
1072 Error(Loc, "global variable reference must have pointer type");
1076 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1078 // If this is a forward reference for the value, see if we already created a
1079 // forward ref record.
1081 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1082 I = ForwardRefValIDs.find(ID);
1083 if (I != ForwardRefValIDs.end())
1084 Val = I->second.first;
1087 // If we have the value in the symbol table or fwd-ref table, return it.
1089 if (Val->getType() == Ty) return Val;
1090 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1091 getTypeString(Val->getType()) + "'");
1095 // Otherwise, create a new forward reference for this value and remember it.
1096 GlobalValue *FwdVal;
1097 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1098 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1100 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1101 GlobalValue::ExternalWeakLinkage, nullptr, "");
1103 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1108 //===----------------------------------------------------------------------===//
1110 //===----------------------------------------------------------------------===//
1112 /// ParseToken - If the current token has the specified kind, eat it and return
1113 /// success. Otherwise, emit the specified error and return failure.
1114 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1115 if (Lex.getKind() != T)
1116 return TokError(ErrMsg);
1121 /// ParseStringConstant
1122 /// ::= StringConstant
1123 bool LLParser::ParseStringConstant(std::string &Result) {
1124 if (Lex.getKind() != lltok::StringConstant)
1125 return TokError("expected string constant");
1126 Result = Lex.getStrVal();
1133 bool LLParser::ParseUInt32(unsigned &Val) {
1134 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1135 return TokError("expected integer");
1136 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1137 if (Val64 != unsigned(Val64))
1138 return TokError("expected 32-bit integer (too large)");
1145 /// := 'localdynamic'
1146 /// := 'initialexec'
1148 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1149 switch (Lex.getKind()) {
1151 return TokError("expected localdynamic, initialexec or localexec");
1152 case lltok::kw_localdynamic:
1153 TLM = GlobalVariable::LocalDynamicTLSModel;
1155 case lltok::kw_initialexec:
1156 TLM = GlobalVariable::InitialExecTLSModel;
1158 case lltok::kw_localexec:
1159 TLM = GlobalVariable::LocalExecTLSModel;
1167 /// ParseOptionalThreadLocal
1169 /// := 'thread_local'
1170 /// := 'thread_local' '(' tlsmodel ')'
1171 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1172 TLM = GlobalVariable::NotThreadLocal;
1173 if (!EatIfPresent(lltok::kw_thread_local))
1176 TLM = GlobalVariable::GeneralDynamicTLSModel;
1177 if (Lex.getKind() == lltok::lparen) {
1179 return ParseTLSModel(TLM) ||
1180 ParseToken(lltok::rparen, "expected ')' after thread local model");
1185 /// ParseOptionalAddrSpace
1187 /// := 'addrspace' '(' uint32 ')'
1188 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1190 if (!EatIfPresent(lltok::kw_addrspace))
1192 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1193 ParseUInt32(AddrSpace) ||
1194 ParseToken(lltok::rparen, "expected ')' in address space");
1197 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1198 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1199 bool HaveError = false;
1204 lltok::Kind Token = Lex.getKind();
1206 default: // End of attributes.
1208 case lltok::kw_align: {
1210 if (ParseOptionalAlignment(Alignment))
1212 B.addAlignmentAttr(Alignment);
1215 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1216 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1217 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1218 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1219 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1220 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1221 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1222 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1223 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1224 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1225 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1226 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1227 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1229 case lltok::kw_alignstack:
1230 case lltok::kw_alwaysinline:
1231 case lltok::kw_builtin:
1232 case lltok::kw_inlinehint:
1233 case lltok::kw_minsize:
1234 case lltok::kw_naked:
1235 case lltok::kw_nobuiltin:
1236 case lltok::kw_noduplicate:
1237 case lltok::kw_noimplicitfloat:
1238 case lltok::kw_noinline:
1239 case lltok::kw_nonlazybind:
1240 case lltok::kw_noredzone:
1241 case lltok::kw_noreturn:
1242 case lltok::kw_nounwind:
1243 case lltok::kw_optnone:
1244 case lltok::kw_optsize:
1245 case lltok::kw_returns_twice:
1246 case lltok::kw_sanitize_address:
1247 case lltok::kw_sanitize_memory:
1248 case lltok::kw_sanitize_thread:
1250 case lltok::kw_sspreq:
1251 case lltok::kw_sspstrong:
1252 case lltok::kw_uwtable:
1253 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1261 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1262 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1263 bool HaveError = false;
1268 lltok::Kind Token = Lex.getKind();
1270 default: // End of attributes.
1272 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1273 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1274 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1275 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1276 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1279 case lltok::kw_align:
1280 case lltok::kw_byval:
1281 case lltok::kw_inalloca:
1282 case lltok::kw_nest:
1283 case lltok::kw_nocapture:
1284 case lltok::kw_returned:
1285 case lltok::kw_sret:
1286 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1289 case lltok::kw_alignstack:
1290 case lltok::kw_alwaysinline:
1291 case lltok::kw_builtin:
1292 case lltok::kw_cold:
1293 case lltok::kw_inlinehint:
1294 case lltok::kw_minsize:
1295 case lltok::kw_naked:
1296 case lltok::kw_nobuiltin:
1297 case lltok::kw_noduplicate:
1298 case lltok::kw_noimplicitfloat:
1299 case lltok::kw_noinline:
1300 case lltok::kw_nonlazybind:
1301 case lltok::kw_noredzone:
1302 case lltok::kw_noreturn:
1303 case lltok::kw_nounwind:
1304 case lltok::kw_optnone:
1305 case lltok::kw_optsize:
1306 case lltok::kw_returns_twice:
1307 case lltok::kw_sanitize_address:
1308 case lltok::kw_sanitize_memory:
1309 case lltok::kw_sanitize_thread:
1311 case lltok::kw_sspreq:
1312 case lltok::kw_sspstrong:
1313 case lltok::kw_uwtable:
1314 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1317 case lltok::kw_readnone:
1318 case lltok::kw_readonly:
1319 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1326 /// ParseOptionalLinkage
1333 /// ::= 'linkonce_odr'
1334 /// ::= 'available_externally'
1337 /// ::= 'extern_weak'
1340 /// Deprecated Values:
1341 /// ::= 'linker_private'
1342 /// ::= 'linker_private_weak'
1343 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1345 switch (Lex.getKind()) {
1346 default: Res=GlobalValue::ExternalLinkage; return false;
1347 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1348 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1349 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1350 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1351 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1352 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1353 case lltok::kw_available_externally:
1354 Res = GlobalValue::AvailableExternallyLinkage;
1356 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1357 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1358 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1359 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1361 case lltok::kw_linker_private:
1362 case lltok::kw_linker_private_weak:
1363 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1366 // treat linker_private and linker_private_weak as PrivateLinkage
1367 Res = GlobalValue::PrivateLinkage;
1375 /// ParseOptionalVisibility
1381 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1382 switch (Lex.getKind()) {
1383 default: Res = GlobalValue::DefaultVisibility; return false;
1384 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1385 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1386 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1392 /// ParseOptionalDLLStorageClass
1397 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1398 switch (Lex.getKind()) {
1399 default: Res = GlobalValue::DefaultStorageClass; return false;
1400 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1401 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1407 /// ParseOptionalCallingConv
1411 /// ::= 'kw_intel_ocl_bicc'
1413 /// ::= 'x86_stdcallcc'
1414 /// ::= 'x86_fastcallcc'
1415 /// ::= 'x86_thiscallcc'
1416 /// ::= 'arm_apcscc'
1417 /// ::= 'arm_aapcscc'
1418 /// ::= 'arm_aapcs_vfpcc'
1419 /// ::= 'msp430_intrcc'
1420 /// ::= 'ptx_kernel'
1421 /// ::= 'ptx_device'
1423 /// ::= 'spir_kernel'
1424 /// ::= 'x86_64_sysvcc'
1425 /// ::= 'x86_64_win64cc'
1426 /// ::= 'webkit_jscc'
1428 /// ::= 'preserve_mostcc'
1429 /// ::= 'preserve_allcc'
1432 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1433 switch (Lex.getKind()) {
1434 default: CC = CallingConv::C; return false;
1435 case lltok::kw_ccc: CC = CallingConv::C; break;
1436 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1437 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1438 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1439 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1440 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1441 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1442 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1443 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1444 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1445 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1446 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1447 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1448 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1449 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1450 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1451 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1452 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1453 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1454 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1455 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1456 case lltok::kw_cc: {
1457 unsigned ArbitraryCC;
1459 if (ParseUInt32(ArbitraryCC))
1461 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1470 /// ParseInstructionMetadata
1471 /// ::= !dbg !42 (',' !dbg !57)*
1472 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1473 PerFunctionState *PFS) {
1475 if (Lex.getKind() != lltok::MetadataVar)
1476 return TokError("expected metadata after comma");
1478 std::string Name = Lex.getStrVal();
1479 unsigned MDK = M->getMDKindID(Name);
1483 SMLoc Loc = Lex.getLoc();
1485 if (ParseToken(lltok::exclaim, "expected '!' here"))
1488 // This code is similar to that of ParseMetadataValue, however it needs to
1489 // have special-case code for a forward reference; see the comments on
1490 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1491 // at the top level here.
1492 if (Lex.getKind() == lltok::lbrace) {
1494 if (ParseMetadataListValue(ID, PFS))
1496 assert(ID.Kind == ValID::t_MDNode);
1497 Inst->setMetadata(MDK, ID.MDNodeVal);
1499 unsigned NodeID = 0;
1500 if (ParseMDNodeID(Node, NodeID))
1503 // If we got the node, add it to the instruction.
1504 Inst->setMetadata(MDK, Node);
1506 MDRef R = { Loc, MDK, NodeID };
1507 // Otherwise, remember that this should be resolved later.
1508 ForwardRefInstMetadata[Inst].push_back(R);
1512 if (MDK == LLVMContext::MD_tbaa)
1513 InstsWithTBAATag.push_back(Inst);
1515 // If this is the end of the list, we're done.
1516 } while (EatIfPresent(lltok::comma));
1520 /// ParseOptionalAlignment
1523 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1525 if (!EatIfPresent(lltok::kw_align))
1527 LocTy AlignLoc = Lex.getLoc();
1528 if (ParseUInt32(Alignment)) return true;
1529 if (!isPowerOf2_32(Alignment))
1530 return Error(AlignLoc, "alignment is not a power of two");
1531 if (Alignment > Value::MaximumAlignment)
1532 return Error(AlignLoc, "huge alignments are not supported yet");
1536 /// ParseOptionalCommaAlign
1540 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1542 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1543 bool &AteExtraComma) {
1544 AteExtraComma = false;
1545 while (EatIfPresent(lltok::comma)) {
1546 // Metadata at the end is an early exit.
1547 if (Lex.getKind() == lltok::MetadataVar) {
1548 AteExtraComma = true;
1552 if (Lex.getKind() != lltok::kw_align)
1553 return Error(Lex.getLoc(), "expected metadata or 'align'");
1555 if (ParseOptionalAlignment(Alignment)) return true;
1561 /// ParseScopeAndOrdering
1562 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1565 /// This sets Scope and Ordering to the parsed values.
1566 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1567 AtomicOrdering &Ordering) {
1571 Scope = CrossThread;
1572 if (EatIfPresent(lltok::kw_singlethread))
1573 Scope = SingleThread;
1575 return ParseOrdering(Ordering);
1579 /// ::= AtomicOrdering
1581 /// This sets Ordering to the parsed value.
1582 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1583 switch (Lex.getKind()) {
1584 default: return TokError("Expected ordering on atomic instruction");
1585 case lltok::kw_unordered: Ordering = Unordered; break;
1586 case lltok::kw_monotonic: Ordering = Monotonic; break;
1587 case lltok::kw_acquire: Ordering = Acquire; break;
1588 case lltok::kw_release: Ordering = Release; break;
1589 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1590 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1596 /// ParseOptionalStackAlignment
1598 /// ::= 'alignstack' '(' 4 ')'
1599 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1601 if (!EatIfPresent(lltok::kw_alignstack))
1603 LocTy ParenLoc = Lex.getLoc();
1604 if (!EatIfPresent(lltok::lparen))
1605 return Error(ParenLoc, "expected '('");
1606 LocTy AlignLoc = Lex.getLoc();
1607 if (ParseUInt32(Alignment)) return true;
1608 ParenLoc = Lex.getLoc();
1609 if (!EatIfPresent(lltok::rparen))
1610 return Error(ParenLoc, "expected ')'");
1611 if (!isPowerOf2_32(Alignment))
1612 return Error(AlignLoc, "stack alignment is not a power of two");
1616 /// ParseIndexList - This parses the index list for an insert/extractvalue
1617 /// instruction. This sets AteExtraComma in the case where we eat an extra
1618 /// comma at the end of the line and find that it is followed by metadata.
1619 /// Clients that don't allow metadata can call the version of this function that
1620 /// only takes one argument.
1623 /// ::= (',' uint32)+
1625 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1626 bool &AteExtraComma) {
1627 AteExtraComma = false;
1629 if (Lex.getKind() != lltok::comma)
1630 return TokError("expected ',' as start of index list");
1632 while (EatIfPresent(lltok::comma)) {
1633 if (Lex.getKind() == lltok::MetadataVar) {
1634 AteExtraComma = true;
1638 if (ParseUInt32(Idx)) return true;
1639 Indices.push_back(Idx);
1645 //===----------------------------------------------------------------------===//
1647 //===----------------------------------------------------------------------===//
1649 /// ParseType - Parse a type.
1650 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1651 SMLoc TypeLoc = Lex.getLoc();
1652 switch (Lex.getKind()) {
1654 return TokError("expected type");
1656 // Type ::= 'float' | 'void' (etc)
1657 Result = Lex.getTyVal();
1661 // Type ::= StructType
1662 if (ParseAnonStructType(Result, false))
1665 case lltok::lsquare:
1666 // Type ::= '[' ... ']'
1667 Lex.Lex(); // eat the lsquare.
1668 if (ParseArrayVectorType(Result, false))
1671 case lltok::less: // Either vector or packed struct.
1672 // Type ::= '<' ... '>'
1674 if (Lex.getKind() == lltok::lbrace) {
1675 if (ParseAnonStructType(Result, true) ||
1676 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1678 } else if (ParseArrayVectorType(Result, true))
1681 case lltok::LocalVar: {
1683 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1685 // If the type hasn't been defined yet, create a forward definition and
1686 // remember where that forward def'n was seen (in case it never is defined).
1688 Entry.first = StructType::create(Context, Lex.getStrVal());
1689 Entry.second = Lex.getLoc();
1691 Result = Entry.first;
1696 case lltok::LocalVarID: {
1698 if (Lex.getUIntVal() >= NumberedTypes.size())
1699 NumberedTypes.resize(Lex.getUIntVal()+1);
1700 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1702 // If the type hasn't been defined yet, create a forward definition and
1703 // remember where that forward def'n was seen (in case it never is defined).
1705 Entry.first = StructType::create(Context);
1706 Entry.second = Lex.getLoc();
1708 Result = Entry.first;
1714 // Parse the type suffixes.
1716 switch (Lex.getKind()) {
1719 if (!AllowVoid && Result->isVoidTy())
1720 return Error(TypeLoc, "void type only allowed for function results");
1723 // Type ::= Type '*'
1725 if (Result->isLabelTy())
1726 return TokError("basic block pointers are invalid");
1727 if (Result->isVoidTy())
1728 return TokError("pointers to void are invalid - use i8* instead");
1729 if (!PointerType::isValidElementType(Result))
1730 return TokError("pointer to this type is invalid");
1731 Result = PointerType::getUnqual(Result);
1735 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1736 case lltok::kw_addrspace: {
1737 if (Result->isLabelTy())
1738 return TokError("basic block pointers are invalid");
1739 if (Result->isVoidTy())
1740 return TokError("pointers to void are invalid; use i8* instead");
1741 if (!PointerType::isValidElementType(Result))
1742 return TokError("pointer to this type is invalid");
1744 if (ParseOptionalAddrSpace(AddrSpace) ||
1745 ParseToken(lltok::star, "expected '*' in address space"))
1748 Result = PointerType::get(Result, AddrSpace);
1752 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1754 if (ParseFunctionType(Result))
1761 /// ParseParameterList
1763 /// ::= '(' Arg (',' Arg)* ')'
1765 /// ::= Type OptionalAttributes Value OptionalAttributes
1766 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1767 PerFunctionState &PFS) {
1768 if (ParseToken(lltok::lparen, "expected '(' in call"))
1771 unsigned AttrIndex = 1;
1772 while (Lex.getKind() != lltok::rparen) {
1773 // If this isn't the first argument, we need a comma.
1774 if (!ArgList.empty() &&
1775 ParseToken(lltok::comma, "expected ',' in argument list"))
1778 // Parse the argument.
1780 Type *ArgTy = nullptr;
1781 AttrBuilder ArgAttrs;
1783 if (ParseType(ArgTy, ArgLoc))
1786 // Otherwise, handle normal operands.
1787 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1789 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1794 Lex.Lex(); // Lex the ')'.
1800 /// ParseArgumentList - Parse the argument list for a function type or function
1802 /// ::= '(' ArgTypeListI ')'
1806 /// ::= ArgTypeList ',' '...'
1807 /// ::= ArgType (',' ArgType)*
1809 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1812 assert(Lex.getKind() == lltok::lparen);
1813 Lex.Lex(); // eat the (.
1815 if (Lex.getKind() == lltok::rparen) {
1817 } else if (Lex.getKind() == lltok::dotdotdot) {
1821 LocTy TypeLoc = Lex.getLoc();
1822 Type *ArgTy = nullptr;
1826 if (ParseType(ArgTy) ||
1827 ParseOptionalParamAttrs(Attrs)) return true;
1829 if (ArgTy->isVoidTy())
1830 return Error(TypeLoc, "argument can not have void type");
1832 if (Lex.getKind() == lltok::LocalVar) {
1833 Name = Lex.getStrVal();
1837 if (!FunctionType::isValidArgumentType(ArgTy))
1838 return Error(TypeLoc, "invalid type for function argument");
1840 unsigned AttrIndex = 1;
1841 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1842 AttributeSet::get(ArgTy->getContext(),
1843 AttrIndex++, Attrs), Name));
1845 while (EatIfPresent(lltok::comma)) {
1846 // Handle ... at end of arg list.
1847 if (EatIfPresent(lltok::dotdotdot)) {
1852 // Otherwise must be an argument type.
1853 TypeLoc = Lex.getLoc();
1854 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1856 if (ArgTy->isVoidTy())
1857 return Error(TypeLoc, "argument can not have void type");
1859 if (Lex.getKind() == lltok::LocalVar) {
1860 Name = Lex.getStrVal();
1866 if (!ArgTy->isFirstClassType())
1867 return Error(TypeLoc, "invalid type for function argument");
1869 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1870 AttributeSet::get(ArgTy->getContext(),
1871 AttrIndex++, Attrs),
1876 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1879 /// ParseFunctionType
1880 /// ::= Type ArgumentList OptionalAttrs
1881 bool LLParser::ParseFunctionType(Type *&Result) {
1882 assert(Lex.getKind() == lltok::lparen);
1884 if (!FunctionType::isValidReturnType(Result))
1885 return TokError("invalid function return type");
1887 SmallVector<ArgInfo, 8> ArgList;
1889 if (ParseArgumentList(ArgList, isVarArg))
1892 // Reject names on the arguments lists.
1893 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1894 if (!ArgList[i].Name.empty())
1895 return Error(ArgList[i].Loc, "argument name invalid in function type");
1896 if (ArgList[i].Attrs.hasAttributes(i + 1))
1897 return Error(ArgList[i].Loc,
1898 "argument attributes invalid in function type");
1901 SmallVector<Type*, 16> ArgListTy;
1902 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1903 ArgListTy.push_back(ArgList[i].Ty);
1905 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1909 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1911 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1912 SmallVector<Type*, 8> Elts;
1913 if (ParseStructBody(Elts)) return true;
1915 Result = StructType::get(Context, Elts, Packed);
1919 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1920 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1921 std::pair<Type*, LocTy> &Entry,
1923 // If the type was already defined, diagnose the redefinition.
1924 if (Entry.first && !Entry.second.isValid())
1925 return Error(TypeLoc, "redefinition of type");
1927 // If we have opaque, just return without filling in the definition for the
1928 // struct. This counts as a definition as far as the .ll file goes.
1929 if (EatIfPresent(lltok::kw_opaque)) {
1930 // This type is being defined, so clear the location to indicate this.
1931 Entry.second = SMLoc();
1933 // If this type number has never been uttered, create it.
1935 Entry.first = StructType::create(Context, Name);
1936 ResultTy = Entry.first;
1940 // If the type starts with '<', then it is either a packed struct or a vector.
1941 bool isPacked = EatIfPresent(lltok::less);
1943 // If we don't have a struct, then we have a random type alias, which we
1944 // accept for compatibility with old files. These types are not allowed to be
1945 // forward referenced and not allowed to be recursive.
1946 if (Lex.getKind() != lltok::lbrace) {
1948 return Error(TypeLoc, "forward references to non-struct type");
1952 return ParseArrayVectorType(ResultTy, true);
1953 return ParseType(ResultTy);
1956 // This type is being defined, so clear the location to indicate this.
1957 Entry.second = SMLoc();
1959 // If this type number has never been uttered, create it.
1961 Entry.first = StructType::create(Context, Name);
1963 StructType *STy = cast<StructType>(Entry.first);
1965 SmallVector<Type*, 8> Body;
1966 if (ParseStructBody(Body) ||
1967 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1970 STy->setBody(Body, isPacked);
1976 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1979 /// ::= '{' Type (',' Type)* '}'
1980 /// ::= '<' '{' '}' '>'
1981 /// ::= '<' '{' Type (',' Type)* '}' '>'
1982 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1983 assert(Lex.getKind() == lltok::lbrace);
1984 Lex.Lex(); // Consume the '{'
1986 // Handle the empty struct.
1987 if (EatIfPresent(lltok::rbrace))
1990 LocTy EltTyLoc = Lex.getLoc();
1992 if (ParseType(Ty)) return true;
1995 if (!StructType::isValidElementType(Ty))
1996 return Error(EltTyLoc, "invalid element type for struct");
1998 while (EatIfPresent(lltok::comma)) {
1999 EltTyLoc = Lex.getLoc();
2000 if (ParseType(Ty)) return true;
2002 if (!StructType::isValidElementType(Ty))
2003 return Error(EltTyLoc, "invalid element type for struct");
2008 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2011 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2012 /// token has already been consumed.
2014 /// ::= '[' APSINTVAL 'x' Types ']'
2015 /// ::= '<' APSINTVAL 'x' Types '>'
2016 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2017 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2018 Lex.getAPSIntVal().getBitWidth() > 64)
2019 return TokError("expected number in address space");
2021 LocTy SizeLoc = Lex.getLoc();
2022 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2025 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2028 LocTy TypeLoc = Lex.getLoc();
2029 Type *EltTy = nullptr;
2030 if (ParseType(EltTy)) return true;
2032 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2033 "expected end of sequential type"))
2038 return Error(SizeLoc, "zero element vector is illegal");
2039 if ((unsigned)Size != Size)
2040 return Error(SizeLoc, "size too large for vector");
2041 if (!VectorType::isValidElementType(EltTy))
2042 return Error(TypeLoc, "invalid vector element type");
2043 Result = VectorType::get(EltTy, unsigned(Size));
2045 if (!ArrayType::isValidElementType(EltTy))
2046 return Error(TypeLoc, "invalid array element type");
2047 Result = ArrayType::get(EltTy, Size);
2052 //===----------------------------------------------------------------------===//
2053 // Function Semantic Analysis.
2054 //===----------------------------------------------------------------------===//
2056 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2058 : P(p), F(f), FunctionNumber(functionNumber) {
2060 // Insert unnamed arguments into the NumberedVals list.
2061 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2064 NumberedVals.push_back(AI);
2067 LLParser::PerFunctionState::~PerFunctionState() {
2068 // If there were any forward referenced non-basicblock values, delete them.
2069 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2070 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2071 if (!isa<BasicBlock>(I->second.first)) {
2072 I->second.first->replaceAllUsesWith(
2073 UndefValue::get(I->second.first->getType()));
2074 delete I->second.first;
2075 I->second.first = nullptr;
2078 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2079 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2080 if (!isa<BasicBlock>(I->second.first)) {
2081 I->second.first->replaceAllUsesWith(
2082 UndefValue::get(I->second.first->getType()));
2083 delete I->second.first;
2084 I->second.first = nullptr;
2088 bool LLParser::PerFunctionState::FinishFunction() {
2089 // Check to see if someone took the address of labels in this block.
2090 if (!P.ForwardRefBlockAddresses.empty()) {
2092 if (!F.getName().empty()) {
2093 FunctionID.Kind = ValID::t_GlobalName;
2094 FunctionID.StrVal = F.getName();
2096 FunctionID.Kind = ValID::t_GlobalID;
2097 FunctionID.UIntVal = FunctionNumber;
2100 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2101 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2102 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2103 // Resolve all these references.
2104 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2107 P.ForwardRefBlockAddresses.erase(FRBAI);
2111 if (!ForwardRefVals.empty())
2112 return P.Error(ForwardRefVals.begin()->second.second,
2113 "use of undefined value '%" + ForwardRefVals.begin()->first +
2115 if (!ForwardRefValIDs.empty())
2116 return P.Error(ForwardRefValIDs.begin()->second.second,
2117 "use of undefined value '%" +
2118 Twine(ForwardRefValIDs.begin()->first) + "'");
2123 /// GetVal - Get a value with the specified name or ID, creating a
2124 /// forward reference record if needed. This can return null if the value
2125 /// exists but does not have the right type.
2126 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2127 Type *Ty, LocTy Loc) {
2128 // Look this name up in the normal function symbol table.
2129 Value *Val = F.getValueSymbolTable().lookup(Name);
2131 // If this is a forward reference for the value, see if we already created a
2132 // forward ref record.
2134 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2135 I = ForwardRefVals.find(Name);
2136 if (I != ForwardRefVals.end())
2137 Val = I->second.first;
2140 // If we have the value in the symbol table or fwd-ref table, return it.
2142 if (Val->getType() == Ty) return Val;
2143 if (Ty->isLabelTy())
2144 P.Error(Loc, "'%" + Name + "' is not a basic block");
2146 P.Error(Loc, "'%" + Name + "' defined with type '" +
2147 getTypeString(Val->getType()) + "'");
2151 // Don't make placeholders with invalid type.
2152 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2153 P.Error(Loc, "invalid use of a non-first-class type");
2157 // Otherwise, create a new forward reference for this value and remember it.
2159 if (Ty->isLabelTy())
2160 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2162 FwdVal = new Argument(Ty, Name);
2164 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2168 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2170 // Look this name up in the normal function symbol table.
2171 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2173 // If this is a forward reference for the value, see if we already created a
2174 // forward ref record.
2176 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2177 I = ForwardRefValIDs.find(ID);
2178 if (I != ForwardRefValIDs.end())
2179 Val = I->second.first;
2182 // If we have the value in the symbol table or fwd-ref table, return it.
2184 if (Val->getType() == Ty) return Val;
2185 if (Ty->isLabelTy())
2186 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2188 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2189 getTypeString(Val->getType()) + "'");
2193 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2194 P.Error(Loc, "invalid use of a non-first-class type");
2198 // Otherwise, create a new forward reference for this value and remember it.
2200 if (Ty->isLabelTy())
2201 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2203 FwdVal = new Argument(Ty);
2205 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2209 /// SetInstName - After an instruction is parsed and inserted into its
2210 /// basic block, this installs its name.
2211 bool LLParser::PerFunctionState::SetInstName(int NameID,
2212 const std::string &NameStr,
2213 LocTy NameLoc, Instruction *Inst) {
2214 // If this instruction has void type, it cannot have a name or ID specified.
2215 if (Inst->getType()->isVoidTy()) {
2216 if (NameID != -1 || !NameStr.empty())
2217 return P.Error(NameLoc, "instructions returning void cannot have a name");
2221 // If this was a numbered instruction, verify that the instruction is the
2222 // expected value and resolve any forward references.
2223 if (NameStr.empty()) {
2224 // If neither a name nor an ID was specified, just use the next ID.
2226 NameID = NumberedVals.size();
2228 if (unsigned(NameID) != NumberedVals.size())
2229 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2230 Twine(NumberedVals.size()) + "'");
2232 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2233 ForwardRefValIDs.find(NameID);
2234 if (FI != ForwardRefValIDs.end()) {
2235 if (FI->second.first->getType() != Inst->getType())
2236 return P.Error(NameLoc, "instruction forward referenced with type '" +
2237 getTypeString(FI->second.first->getType()) + "'");
2238 FI->second.first->replaceAllUsesWith(Inst);
2239 delete FI->second.first;
2240 ForwardRefValIDs.erase(FI);
2243 NumberedVals.push_back(Inst);
2247 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2248 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2249 FI = ForwardRefVals.find(NameStr);
2250 if (FI != ForwardRefVals.end()) {
2251 if (FI->second.first->getType() != Inst->getType())
2252 return P.Error(NameLoc, "instruction forward referenced with type '" +
2253 getTypeString(FI->second.first->getType()) + "'");
2254 FI->second.first->replaceAllUsesWith(Inst);
2255 delete FI->second.first;
2256 ForwardRefVals.erase(FI);
2259 // Set the name on the instruction.
2260 Inst->setName(NameStr);
2262 if (Inst->getName() != NameStr)
2263 return P.Error(NameLoc, "multiple definition of local value named '" +
2268 /// GetBB - Get a basic block with the specified name or ID, creating a
2269 /// forward reference record if needed.
2270 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2272 return cast_or_null<BasicBlock>(GetVal(Name,
2273 Type::getLabelTy(F.getContext()), Loc));
2276 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2277 return cast_or_null<BasicBlock>(GetVal(ID,
2278 Type::getLabelTy(F.getContext()), Loc));
2281 /// DefineBB - Define the specified basic block, which is either named or
2282 /// unnamed. If there is an error, this returns null otherwise it returns
2283 /// the block being defined.
2284 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2288 BB = GetBB(NumberedVals.size(), Loc);
2290 BB = GetBB(Name, Loc);
2291 if (!BB) return nullptr; // Already diagnosed error.
2293 // Move the block to the end of the function. Forward ref'd blocks are
2294 // inserted wherever they happen to be referenced.
2295 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2297 // Remove the block from forward ref sets.
2299 ForwardRefValIDs.erase(NumberedVals.size());
2300 NumberedVals.push_back(BB);
2302 // BB forward references are already in the function symbol table.
2303 ForwardRefVals.erase(Name);
2309 //===----------------------------------------------------------------------===//
2311 //===----------------------------------------------------------------------===//
2313 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2314 /// type implied. For example, if we parse "4" we don't know what integer type
2315 /// it has. The value will later be combined with its type and checked for
2316 /// sanity. PFS is used to convert function-local operands of metadata (since
2317 /// metadata operands are not just parsed here but also converted to values).
2318 /// PFS can be null when we are not parsing metadata values inside a function.
2319 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2320 ID.Loc = Lex.getLoc();
2321 switch (Lex.getKind()) {
2322 default: return TokError("expected value token");
2323 case lltok::GlobalID: // @42
2324 ID.UIntVal = Lex.getUIntVal();
2325 ID.Kind = ValID::t_GlobalID;
2327 case lltok::GlobalVar: // @foo
2328 ID.StrVal = Lex.getStrVal();
2329 ID.Kind = ValID::t_GlobalName;
2331 case lltok::LocalVarID: // %42
2332 ID.UIntVal = Lex.getUIntVal();
2333 ID.Kind = ValID::t_LocalID;
2335 case lltok::LocalVar: // %foo
2336 ID.StrVal = Lex.getStrVal();
2337 ID.Kind = ValID::t_LocalName;
2339 case lltok::exclaim: // !42, !{...}, or !"foo"
2340 return ParseMetadataValue(ID, PFS);
2342 ID.APSIntVal = Lex.getAPSIntVal();
2343 ID.Kind = ValID::t_APSInt;
2345 case lltok::APFloat:
2346 ID.APFloatVal = Lex.getAPFloatVal();
2347 ID.Kind = ValID::t_APFloat;
2349 case lltok::kw_true:
2350 ID.ConstantVal = ConstantInt::getTrue(Context);
2351 ID.Kind = ValID::t_Constant;
2353 case lltok::kw_false:
2354 ID.ConstantVal = ConstantInt::getFalse(Context);
2355 ID.Kind = ValID::t_Constant;
2357 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2358 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2359 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2361 case lltok::lbrace: {
2362 // ValID ::= '{' ConstVector '}'
2364 SmallVector<Constant*, 16> Elts;
2365 if (ParseGlobalValueVector(Elts) ||
2366 ParseToken(lltok::rbrace, "expected end of struct constant"))
2369 ID.ConstantStructElts = new Constant*[Elts.size()];
2370 ID.UIntVal = Elts.size();
2371 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2372 ID.Kind = ValID::t_ConstantStruct;
2376 // ValID ::= '<' ConstVector '>' --> Vector.
2377 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2379 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2381 SmallVector<Constant*, 16> Elts;
2382 LocTy FirstEltLoc = Lex.getLoc();
2383 if (ParseGlobalValueVector(Elts) ||
2385 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2386 ParseToken(lltok::greater, "expected end of constant"))
2389 if (isPackedStruct) {
2390 ID.ConstantStructElts = new Constant*[Elts.size()];
2391 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2392 ID.UIntVal = Elts.size();
2393 ID.Kind = ValID::t_PackedConstantStruct;
2398 return Error(ID.Loc, "constant vector must not be empty");
2400 if (!Elts[0]->getType()->isIntegerTy() &&
2401 !Elts[0]->getType()->isFloatingPointTy() &&
2402 !Elts[0]->getType()->isPointerTy())
2403 return Error(FirstEltLoc,
2404 "vector elements must have integer, pointer or floating point type");
2406 // Verify that all the vector elements have the same type.
2407 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2408 if (Elts[i]->getType() != Elts[0]->getType())
2409 return Error(FirstEltLoc,
2410 "vector element #" + Twine(i) +
2411 " is not of type '" + getTypeString(Elts[0]->getType()));
2413 ID.ConstantVal = ConstantVector::get(Elts);
2414 ID.Kind = ValID::t_Constant;
2417 case lltok::lsquare: { // Array Constant
2419 SmallVector<Constant*, 16> Elts;
2420 LocTy FirstEltLoc = Lex.getLoc();
2421 if (ParseGlobalValueVector(Elts) ||
2422 ParseToken(lltok::rsquare, "expected end of array constant"))
2425 // Handle empty element.
2427 // Use undef instead of an array because it's inconvenient to determine
2428 // the element type at this point, there being no elements to examine.
2429 ID.Kind = ValID::t_EmptyArray;
2433 if (!Elts[0]->getType()->isFirstClassType())
2434 return Error(FirstEltLoc, "invalid array element type: " +
2435 getTypeString(Elts[0]->getType()));
2437 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2439 // Verify all elements are correct type!
2440 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2441 if (Elts[i]->getType() != Elts[0]->getType())
2442 return Error(FirstEltLoc,
2443 "array element #" + Twine(i) +
2444 " is not of type '" + getTypeString(Elts[0]->getType()));
2447 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2448 ID.Kind = ValID::t_Constant;
2451 case lltok::kw_c: // c "foo"
2453 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2455 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2456 ID.Kind = ValID::t_Constant;
2459 case lltok::kw_asm: {
2460 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2462 bool HasSideEffect, AlignStack, AsmDialect;
2464 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2465 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2466 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2467 ParseStringConstant(ID.StrVal) ||
2468 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2469 ParseToken(lltok::StringConstant, "expected constraint string"))
2471 ID.StrVal2 = Lex.getStrVal();
2472 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2473 (unsigned(AsmDialect)<<2);
2474 ID.Kind = ValID::t_InlineAsm;
2478 case lltok::kw_blockaddress: {
2479 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2484 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2486 ParseToken(lltok::comma, "expected comma in block address expression")||
2487 ParseValID(Label) ||
2488 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2491 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2492 return Error(Fn.Loc, "expected function name in blockaddress");
2493 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2494 return Error(Label.Loc, "expected basic block name in blockaddress");
2496 // Make a global variable as a placeholder for this reference.
2497 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2498 false, GlobalValue::InternalLinkage,
2500 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2501 ID.ConstantVal = FwdRef;
2502 ID.Kind = ValID::t_Constant;
2506 case lltok::kw_trunc:
2507 case lltok::kw_zext:
2508 case lltok::kw_sext:
2509 case lltok::kw_fptrunc:
2510 case lltok::kw_fpext:
2511 case lltok::kw_bitcast:
2512 case lltok::kw_addrspacecast:
2513 case lltok::kw_uitofp:
2514 case lltok::kw_sitofp:
2515 case lltok::kw_fptoui:
2516 case lltok::kw_fptosi:
2517 case lltok::kw_inttoptr:
2518 case lltok::kw_ptrtoint: {
2519 unsigned Opc = Lex.getUIntVal();
2520 Type *DestTy = nullptr;
2523 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2524 ParseGlobalTypeAndValue(SrcVal) ||
2525 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2526 ParseType(DestTy) ||
2527 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2529 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2530 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2531 getTypeString(SrcVal->getType()) + "' to '" +
2532 getTypeString(DestTy) + "'");
2533 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2535 ID.Kind = ValID::t_Constant;
2538 case lltok::kw_extractvalue: {
2541 SmallVector<unsigned, 4> Indices;
2542 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2543 ParseGlobalTypeAndValue(Val) ||
2544 ParseIndexList(Indices) ||
2545 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2548 if (!Val->getType()->isAggregateType())
2549 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2550 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2551 return Error(ID.Loc, "invalid indices for extractvalue");
2552 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2553 ID.Kind = ValID::t_Constant;
2556 case lltok::kw_insertvalue: {
2558 Constant *Val0, *Val1;
2559 SmallVector<unsigned, 4> Indices;
2560 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2561 ParseGlobalTypeAndValue(Val0) ||
2562 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2563 ParseGlobalTypeAndValue(Val1) ||
2564 ParseIndexList(Indices) ||
2565 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2567 if (!Val0->getType()->isAggregateType())
2568 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2569 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2570 return Error(ID.Loc, "invalid indices for insertvalue");
2571 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2572 ID.Kind = ValID::t_Constant;
2575 case lltok::kw_icmp:
2576 case lltok::kw_fcmp: {
2577 unsigned PredVal, Opc = Lex.getUIntVal();
2578 Constant *Val0, *Val1;
2580 if (ParseCmpPredicate(PredVal, Opc) ||
2581 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2582 ParseGlobalTypeAndValue(Val0) ||
2583 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2584 ParseGlobalTypeAndValue(Val1) ||
2585 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2588 if (Val0->getType() != Val1->getType())
2589 return Error(ID.Loc, "compare operands must have the same type");
2591 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2593 if (Opc == Instruction::FCmp) {
2594 if (!Val0->getType()->isFPOrFPVectorTy())
2595 return Error(ID.Loc, "fcmp requires floating point operands");
2596 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2598 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2599 if (!Val0->getType()->isIntOrIntVectorTy() &&
2600 !Val0->getType()->getScalarType()->isPointerTy())
2601 return Error(ID.Loc, "icmp requires pointer or integer operands");
2602 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2604 ID.Kind = ValID::t_Constant;
2608 // Binary Operators.
2610 case lltok::kw_fadd:
2612 case lltok::kw_fsub:
2614 case lltok::kw_fmul:
2615 case lltok::kw_udiv:
2616 case lltok::kw_sdiv:
2617 case lltok::kw_fdiv:
2618 case lltok::kw_urem:
2619 case lltok::kw_srem:
2620 case lltok::kw_frem:
2622 case lltok::kw_lshr:
2623 case lltok::kw_ashr: {
2627 unsigned Opc = Lex.getUIntVal();
2628 Constant *Val0, *Val1;
2630 LocTy ModifierLoc = Lex.getLoc();
2631 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2632 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2633 if (EatIfPresent(lltok::kw_nuw))
2635 if (EatIfPresent(lltok::kw_nsw)) {
2637 if (EatIfPresent(lltok::kw_nuw))
2640 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2641 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2642 if (EatIfPresent(lltok::kw_exact))
2645 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2646 ParseGlobalTypeAndValue(Val0) ||
2647 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2648 ParseGlobalTypeAndValue(Val1) ||
2649 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2651 if (Val0->getType() != Val1->getType())
2652 return Error(ID.Loc, "operands of constexpr must have same type");
2653 if (!Val0->getType()->isIntOrIntVectorTy()) {
2655 return Error(ModifierLoc, "nuw only applies to integer operations");
2657 return Error(ModifierLoc, "nsw only applies to integer operations");
2659 // Check that the type is valid for the operator.
2661 case Instruction::Add:
2662 case Instruction::Sub:
2663 case Instruction::Mul:
2664 case Instruction::UDiv:
2665 case Instruction::SDiv:
2666 case Instruction::URem:
2667 case Instruction::SRem:
2668 case Instruction::Shl:
2669 case Instruction::AShr:
2670 case Instruction::LShr:
2671 if (!Val0->getType()->isIntOrIntVectorTy())
2672 return Error(ID.Loc, "constexpr requires integer operands");
2674 case Instruction::FAdd:
2675 case Instruction::FSub:
2676 case Instruction::FMul:
2677 case Instruction::FDiv:
2678 case Instruction::FRem:
2679 if (!Val0->getType()->isFPOrFPVectorTy())
2680 return Error(ID.Loc, "constexpr requires fp operands");
2682 default: llvm_unreachable("Unknown binary operator!");
2685 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2686 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2687 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2688 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2690 ID.Kind = ValID::t_Constant;
2694 // Logical Operations
2697 case lltok::kw_xor: {
2698 unsigned Opc = Lex.getUIntVal();
2699 Constant *Val0, *Val1;
2701 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2702 ParseGlobalTypeAndValue(Val0) ||
2703 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2704 ParseGlobalTypeAndValue(Val1) ||
2705 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2707 if (Val0->getType() != Val1->getType())
2708 return Error(ID.Loc, "operands of constexpr must have same type");
2709 if (!Val0->getType()->isIntOrIntVectorTy())
2710 return Error(ID.Loc,
2711 "constexpr requires integer or integer vector operands");
2712 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2713 ID.Kind = ValID::t_Constant;
2717 case lltok::kw_getelementptr:
2718 case lltok::kw_shufflevector:
2719 case lltok::kw_insertelement:
2720 case lltok::kw_extractelement:
2721 case lltok::kw_select: {
2722 unsigned Opc = Lex.getUIntVal();
2723 SmallVector<Constant*, 16> Elts;
2724 bool InBounds = false;
2726 if (Opc == Instruction::GetElementPtr)
2727 InBounds = EatIfPresent(lltok::kw_inbounds);
2728 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2729 ParseGlobalValueVector(Elts) ||
2730 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2733 if (Opc == Instruction::GetElementPtr) {
2734 if (Elts.size() == 0 ||
2735 !Elts[0]->getType()->getScalarType()->isPointerTy())
2736 return Error(ID.Loc, "getelementptr requires pointer operand");
2738 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2739 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2740 return Error(ID.Loc, "invalid indices for getelementptr");
2741 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2743 } else if (Opc == Instruction::Select) {
2744 if (Elts.size() != 3)
2745 return Error(ID.Loc, "expected three operands to select");
2746 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2748 return Error(ID.Loc, Reason);
2749 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2750 } else if (Opc == Instruction::ShuffleVector) {
2751 if (Elts.size() != 3)
2752 return Error(ID.Loc, "expected three operands to shufflevector");
2753 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2754 return Error(ID.Loc, "invalid operands to shufflevector");
2756 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2757 } else if (Opc == Instruction::ExtractElement) {
2758 if (Elts.size() != 2)
2759 return Error(ID.Loc, "expected two operands to extractelement");
2760 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2761 return Error(ID.Loc, "invalid extractelement operands");
2762 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2764 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2765 if (Elts.size() != 3)
2766 return Error(ID.Loc, "expected three operands to insertelement");
2767 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2768 return Error(ID.Loc, "invalid insertelement operands");
2770 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2773 ID.Kind = ValID::t_Constant;
2782 /// ParseGlobalValue - Parse a global value with the specified type.
2783 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2787 bool Parsed = ParseValID(ID) ||
2788 ConvertValIDToValue(Ty, ID, V, nullptr);
2789 if (V && !(C = dyn_cast<Constant>(V)))
2790 return Error(ID.Loc, "global values must be constants");
2794 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2796 return ParseType(Ty) ||
2797 ParseGlobalValue(Ty, V);
2800 /// ParseGlobalValueVector
2802 /// ::= TypeAndValue (',' TypeAndValue)*
2803 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2805 if (Lex.getKind() == lltok::rbrace ||
2806 Lex.getKind() == lltok::rsquare ||
2807 Lex.getKind() == lltok::greater ||
2808 Lex.getKind() == lltok::rparen)
2812 if (ParseGlobalTypeAndValue(C)) return true;
2815 while (EatIfPresent(lltok::comma)) {
2816 if (ParseGlobalTypeAndValue(C)) return true;
2823 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2824 assert(Lex.getKind() == lltok::lbrace);
2827 SmallVector<Value*, 16> Elts;
2828 if (ParseMDNodeVector(Elts, PFS) ||
2829 ParseToken(lltok::rbrace, "expected end of metadata node"))
2832 ID.MDNodeVal = MDNode::get(Context, Elts);
2833 ID.Kind = ValID::t_MDNode;
2837 /// ParseMetadataValue
2841 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2842 assert(Lex.getKind() == lltok::exclaim);
2847 if (Lex.getKind() == lltok::lbrace)
2848 return ParseMetadataListValue(ID, PFS);
2850 // Standalone metadata reference
2852 if (Lex.getKind() == lltok::APSInt) {
2853 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2854 ID.Kind = ValID::t_MDNode;
2859 // ::= '!' STRINGCONSTANT
2860 if (ParseMDString(ID.MDStringVal)) return true;
2861 ID.Kind = ValID::t_MDString;
2866 //===----------------------------------------------------------------------===//
2867 // Function Parsing.
2868 //===----------------------------------------------------------------------===//
2870 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2871 PerFunctionState *PFS) {
2872 if (Ty->isFunctionTy())
2873 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2876 case ValID::t_LocalID:
2877 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2878 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2879 return V == nullptr;
2880 case ValID::t_LocalName:
2881 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2882 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2883 return V == nullptr;
2884 case ValID::t_InlineAsm: {
2885 PointerType *PTy = dyn_cast<PointerType>(Ty);
2887 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2888 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2889 return Error(ID.Loc, "invalid type for inline asm constraint string");
2890 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2891 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2894 case ValID::t_MDNode:
2895 if (!Ty->isMetadataTy())
2896 return Error(ID.Loc, "metadata value must have metadata type");
2899 case ValID::t_MDString:
2900 if (!Ty->isMetadataTy())
2901 return Error(ID.Loc, "metadata value must have metadata type");
2904 case ValID::t_GlobalName:
2905 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2906 return V == nullptr;
2907 case ValID::t_GlobalID:
2908 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2909 return V == nullptr;
2910 case ValID::t_APSInt:
2911 if (!Ty->isIntegerTy())
2912 return Error(ID.Loc, "integer constant must have integer type");
2913 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2914 V = ConstantInt::get(Context, ID.APSIntVal);
2916 case ValID::t_APFloat:
2917 if (!Ty->isFloatingPointTy() ||
2918 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2919 return Error(ID.Loc, "floating point constant invalid for type");
2921 // The lexer has no type info, so builds all half, float, and double FP
2922 // constants as double. Fix this here. Long double does not need this.
2923 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2926 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2928 else if (Ty->isFloatTy())
2929 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2932 V = ConstantFP::get(Context, ID.APFloatVal);
2934 if (V->getType() != Ty)
2935 return Error(ID.Loc, "floating point constant does not have type '" +
2936 getTypeString(Ty) + "'");
2940 if (!Ty->isPointerTy())
2941 return Error(ID.Loc, "null must be a pointer type");
2942 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2944 case ValID::t_Undef:
2945 // FIXME: LabelTy should not be a first-class type.
2946 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2947 return Error(ID.Loc, "invalid type for undef constant");
2948 V = UndefValue::get(Ty);
2950 case ValID::t_EmptyArray:
2951 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2952 return Error(ID.Loc, "invalid empty array initializer");
2953 V = UndefValue::get(Ty);
2956 // FIXME: LabelTy should not be a first-class type.
2957 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2958 return Error(ID.Loc, "invalid type for null constant");
2959 V = Constant::getNullValue(Ty);
2961 case ValID::t_Constant:
2962 if (ID.ConstantVal->getType() != Ty)
2963 return Error(ID.Loc, "constant expression type mismatch");
2967 case ValID::t_ConstantStruct:
2968 case ValID::t_PackedConstantStruct:
2969 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2970 if (ST->getNumElements() != ID.UIntVal)
2971 return Error(ID.Loc,
2972 "initializer with struct type has wrong # elements");
2973 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2974 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2976 // Verify that the elements are compatible with the structtype.
2977 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2978 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2979 return Error(ID.Loc, "element " + Twine(i) +
2980 " of struct initializer doesn't match struct element type");
2982 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2985 return Error(ID.Loc, "constant expression type mismatch");
2988 llvm_unreachable("Invalid ValID");
2991 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2994 return ParseValID(ID, PFS) ||
2995 ConvertValIDToValue(Ty, ID, V, PFS);
2998 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3000 return ParseType(Ty) ||
3001 ParseValue(Ty, V, PFS);
3004 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3005 PerFunctionState &PFS) {
3008 if (ParseTypeAndValue(V, PFS)) return true;
3009 if (!isa<BasicBlock>(V))
3010 return Error(Loc, "expected a basic block");
3011 BB = cast<BasicBlock>(V);
3017 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3018 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3019 /// OptionalAlign OptGC OptionalPrefix
3020 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3021 // Parse the linkage.
3022 LocTy LinkageLoc = Lex.getLoc();
3025 unsigned Visibility;
3026 unsigned DLLStorageClass;
3027 AttrBuilder RetAttrs;
3029 Type *RetType = nullptr;
3030 LocTy RetTypeLoc = Lex.getLoc();
3031 if (ParseOptionalLinkage(Linkage) ||
3032 ParseOptionalVisibility(Visibility) ||
3033 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3034 ParseOptionalCallingConv(CC) ||
3035 ParseOptionalReturnAttrs(RetAttrs) ||
3036 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3039 // Verify that the linkage is ok.
3040 switch ((GlobalValue::LinkageTypes)Linkage) {
3041 case GlobalValue::ExternalLinkage:
3042 break; // always ok.
3043 case GlobalValue::ExternalWeakLinkage:
3045 return Error(LinkageLoc, "invalid linkage for function definition");
3047 case GlobalValue::PrivateLinkage:
3048 case GlobalValue::InternalLinkage:
3049 case GlobalValue::AvailableExternallyLinkage:
3050 case GlobalValue::LinkOnceAnyLinkage:
3051 case GlobalValue::LinkOnceODRLinkage:
3052 case GlobalValue::WeakAnyLinkage:
3053 case GlobalValue::WeakODRLinkage:
3055 return Error(LinkageLoc, "invalid linkage for function declaration");
3057 case GlobalValue::AppendingLinkage:
3058 case GlobalValue::CommonLinkage:
3059 return Error(LinkageLoc, "invalid function linkage type");
3062 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3063 return Error(LinkageLoc,
3064 "symbol with local linkage must have default visibility");
3066 if (!FunctionType::isValidReturnType(RetType))
3067 return Error(RetTypeLoc, "invalid function return type");
3069 LocTy NameLoc = Lex.getLoc();
3071 std::string FunctionName;
3072 if (Lex.getKind() == lltok::GlobalVar) {
3073 FunctionName = Lex.getStrVal();
3074 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3075 unsigned NameID = Lex.getUIntVal();
3077 if (NameID != NumberedVals.size())
3078 return TokError("function expected to be numbered '%" +
3079 Twine(NumberedVals.size()) + "'");
3081 return TokError("expected function name");
3086 if (Lex.getKind() != lltok::lparen)
3087 return TokError("expected '(' in function argument list");
3089 SmallVector<ArgInfo, 8> ArgList;
3091 AttrBuilder FuncAttrs;
3092 std::vector<unsigned> FwdRefAttrGrps;
3094 std::string Section;
3098 LocTy UnnamedAddrLoc;
3099 Constant *Prefix = nullptr;
3101 if (ParseArgumentList(ArgList, isVarArg) ||
3102 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3104 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3106 (EatIfPresent(lltok::kw_section) &&
3107 ParseStringConstant(Section)) ||
3108 ParseOptionalAlignment(Alignment) ||
3109 (EatIfPresent(lltok::kw_gc) &&
3110 ParseStringConstant(GC)) ||
3111 (EatIfPresent(lltok::kw_prefix) &&
3112 ParseGlobalTypeAndValue(Prefix)))
3115 if (FuncAttrs.contains(Attribute::Builtin))
3116 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3118 // If the alignment was parsed as an attribute, move to the alignment field.
3119 if (FuncAttrs.hasAlignmentAttr()) {
3120 Alignment = FuncAttrs.getAlignment();
3121 FuncAttrs.removeAttribute(Attribute::Alignment);
3124 // Okay, if we got here, the function is syntactically valid. Convert types
3125 // and do semantic checks.
3126 std::vector<Type*> ParamTypeList;
3127 SmallVector<AttributeSet, 8> Attrs;
3129 if (RetAttrs.hasAttributes())
3130 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3131 AttributeSet::ReturnIndex,
3134 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3135 ParamTypeList.push_back(ArgList[i].Ty);
3136 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3137 AttrBuilder B(ArgList[i].Attrs, i + 1);
3138 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3142 if (FuncAttrs.hasAttributes())
3143 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3144 AttributeSet::FunctionIndex,
3147 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3149 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3150 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3153 FunctionType::get(RetType, ParamTypeList, isVarArg);
3154 PointerType *PFT = PointerType::getUnqual(FT);
3157 if (!FunctionName.empty()) {
3158 // If this was a definition of a forward reference, remove the definition
3159 // from the forward reference table and fill in the forward ref.
3160 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3161 ForwardRefVals.find(FunctionName);
3162 if (FRVI != ForwardRefVals.end()) {
3163 Fn = M->getFunction(FunctionName);
3165 return Error(FRVI->second.second, "invalid forward reference to "
3166 "function as global value!");
3167 if (Fn->getType() != PFT)
3168 return Error(FRVI->second.second, "invalid forward reference to "
3169 "function '" + FunctionName + "' with wrong type!");
3171 ForwardRefVals.erase(FRVI);
3172 } else if ((Fn = M->getFunction(FunctionName))) {
3173 // Reject redefinitions.
3174 return Error(NameLoc, "invalid redefinition of function '" +
3175 FunctionName + "'");
3176 } else if (M->getNamedValue(FunctionName)) {
3177 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3181 // If this is a definition of a forward referenced function, make sure the
3183 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3184 = ForwardRefValIDs.find(NumberedVals.size());
3185 if (I != ForwardRefValIDs.end()) {
3186 Fn = cast<Function>(I->second.first);
3187 if (Fn->getType() != PFT)
3188 return Error(NameLoc, "type of definition and forward reference of '@" +
3189 Twine(NumberedVals.size()) + "' disagree");
3190 ForwardRefValIDs.erase(I);
3195 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3196 else // Move the forward-reference to the correct spot in the module.
3197 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3199 if (FunctionName.empty())
3200 NumberedVals.push_back(Fn);
3202 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3203 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3204 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3205 Fn->setCallingConv(CC);
3206 Fn->setAttributes(PAL);
3207 Fn->setUnnamedAddr(UnnamedAddr);
3208 Fn->setAlignment(Alignment);
3209 Fn->setSection(Section);
3210 if (!GC.empty()) Fn->setGC(GC.c_str());
3211 Fn->setPrefixData(Prefix);
3212 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3214 // Add all of the arguments we parsed to the function.
3215 Function::arg_iterator ArgIt = Fn->arg_begin();
3216 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3217 // If the argument has a name, insert it into the argument symbol table.
3218 if (ArgList[i].Name.empty()) continue;
3220 // Set the name, if it conflicted, it will be auto-renamed.
3221 ArgIt->setName(ArgList[i].Name);
3223 if (ArgIt->getName() != ArgList[i].Name)
3224 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3225 ArgList[i].Name + "'");
3232 /// ParseFunctionBody
3233 /// ::= '{' BasicBlock+ '}'
3235 bool LLParser::ParseFunctionBody(Function &Fn) {
3236 if (Lex.getKind() != lltok::lbrace)
3237 return TokError("expected '{' in function body");
3238 Lex.Lex(); // eat the {.
3240 int FunctionNumber = -1;
3241 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3243 PerFunctionState PFS(*this, Fn, FunctionNumber);
3245 // We need at least one basic block.
3246 if (Lex.getKind() == lltok::rbrace)
3247 return TokError("function body requires at least one basic block");
3249 while (Lex.getKind() != lltok::rbrace)
3250 if (ParseBasicBlock(PFS)) return true;
3255 // Verify function is ok.
3256 return PFS.FinishFunction();
3260 /// ::= LabelStr? Instruction*
3261 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3262 // If this basic block starts out with a name, remember it.
3264 LocTy NameLoc = Lex.getLoc();
3265 if (Lex.getKind() == lltok::LabelStr) {
3266 Name = Lex.getStrVal();
3270 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3271 if (!BB) return true;
3273 std::string NameStr;
3275 // Parse the instructions in this block until we get a terminator.
3278 // This instruction may have three possibilities for a name: a) none
3279 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3280 LocTy NameLoc = Lex.getLoc();
3284 if (Lex.getKind() == lltok::LocalVarID) {
3285 NameID = Lex.getUIntVal();
3287 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3289 } else if (Lex.getKind() == lltok::LocalVar) {
3290 NameStr = Lex.getStrVal();
3292 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3296 switch (ParseInstruction(Inst, BB, PFS)) {
3297 default: llvm_unreachable("Unknown ParseInstruction result!");
3298 case InstError: return true;
3300 BB->getInstList().push_back(Inst);
3302 // With a normal result, we check to see if the instruction is followed by
3303 // a comma and metadata.
3304 if (EatIfPresent(lltok::comma))
3305 if (ParseInstructionMetadata(Inst, &PFS))
3308 case InstExtraComma:
3309 BB->getInstList().push_back(Inst);
3311 // If the instruction parser ate an extra comma at the end of it, it
3312 // *must* be followed by metadata.
3313 if (ParseInstructionMetadata(Inst, &PFS))
3318 // Set the name on the instruction.
3319 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3320 } while (!isa<TerminatorInst>(Inst));
3325 //===----------------------------------------------------------------------===//
3326 // Instruction Parsing.
3327 //===----------------------------------------------------------------------===//
3329 /// ParseInstruction - Parse one of the many different instructions.
3331 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3332 PerFunctionState &PFS) {
3333 lltok::Kind Token = Lex.getKind();
3334 if (Token == lltok::Eof)
3335 return TokError("found end of file when expecting more instructions");
3336 LocTy Loc = Lex.getLoc();
3337 unsigned KeywordVal = Lex.getUIntVal();
3338 Lex.Lex(); // Eat the keyword.
3341 default: return Error(Loc, "expected instruction opcode");
3342 // Terminator Instructions.
3343 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3344 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3345 case lltok::kw_br: return ParseBr(Inst, PFS);
3346 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3347 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3348 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3349 case lltok::kw_resume: return ParseResume(Inst, PFS);
3350 // Binary Operators.
3354 case lltok::kw_shl: {
3355 bool NUW = EatIfPresent(lltok::kw_nuw);
3356 bool NSW = EatIfPresent(lltok::kw_nsw);
3357 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3359 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3361 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3362 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3365 case lltok::kw_fadd:
3366 case lltok::kw_fsub:
3367 case lltok::kw_fmul:
3368 case lltok::kw_fdiv:
3369 case lltok::kw_frem: {
3370 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3371 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3375 Inst->setFastMathFlags(FMF);
3379 case lltok::kw_sdiv:
3380 case lltok::kw_udiv:
3381 case lltok::kw_lshr:
3382 case lltok::kw_ashr: {
3383 bool Exact = EatIfPresent(lltok::kw_exact);
3385 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3386 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3390 case lltok::kw_urem:
3391 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3394 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3395 case lltok::kw_icmp:
3396 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3398 case lltok::kw_trunc:
3399 case lltok::kw_zext:
3400 case lltok::kw_sext:
3401 case lltok::kw_fptrunc:
3402 case lltok::kw_fpext:
3403 case lltok::kw_bitcast:
3404 case lltok::kw_addrspacecast:
3405 case lltok::kw_uitofp:
3406 case lltok::kw_sitofp:
3407 case lltok::kw_fptoui:
3408 case lltok::kw_fptosi:
3409 case lltok::kw_inttoptr:
3410 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3412 case lltok::kw_select: return ParseSelect(Inst, PFS);
3413 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3414 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3415 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3416 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3417 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3418 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3420 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3421 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3422 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3424 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3425 case lltok::kw_load: return ParseLoad(Inst, PFS);
3426 case lltok::kw_store: return ParseStore(Inst, PFS);
3427 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3428 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3429 case lltok::kw_fence: return ParseFence(Inst, PFS);
3430 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3431 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3432 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3436 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3437 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3438 if (Opc == Instruction::FCmp) {
3439 switch (Lex.getKind()) {
3440 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3441 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3442 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3443 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3444 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3445 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3446 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3447 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3448 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3449 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3450 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3451 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3452 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3453 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3454 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3455 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3456 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3459 switch (Lex.getKind()) {
3460 default: return TokError("expected icmp predicate (e.g. 'eq')");
3461 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3462 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3463 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3464 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3465 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3466 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3467 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3468 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3469 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3470 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3477 //===----------------------------------------------------------------------===//
3478 // Terminator Instructions.
3479 //===----------------------------------------------------------------------===//
3481 /// ParseRet - Parse a return instruction.
3482 /// ::= 'ret' void (',' !dbg, !1)*
3483 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3484 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3485 PerFunctionState &PFS) {
3486 SMLoc TypeLoc = Lex.getLoc();
3488 if (ParseType(Ty, true /*void allowed*/)) return true;
3490 Type *ResType = PFS.getFunction().getReturnType();
3492 if (Ty->isVoidTy()) {
3493 if (!ResType->isVoidTy())
3494 return Error(TypeLoc, "value doesn't match function result type '" +
3495 getTypeString(ResType) + "'");
3497 Inst = ReturnInst::Create(Context);
3502 if (ParseValue(Ty, RV, PFS)) return true;
3504 if (ResType != RV->getType())
3505 return Error(TypeLoc, "value doesn't match function result type '" +
3506 getTypeString(ResType) + "'");
3508 Inst = ReturnInst::Create(Context, RV);
3514 /// ::= 'br' TypeAndValue
3515 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3516 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3519 BasicBlock *Op1, *Op2;
3520 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3522 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3523 Inst = BranchInst::Create(BB);
3527 if (Op0->getType() != Type::getInt1Ty(Context))
3528 return Error(Loc, "branch condition must have 'i1' type");
3530 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3531 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3532 ParseToken(lltok::comma, "expected ',' after true destination") ||
3533 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3536 Inst = BranchInst::Create(Op1, Op2, Op0);
3542 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3544 /// ::= (TypeAndValue ',' TypeAndValue)*
3545 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3546 LocTy CondLoc, BBLoc;
3548 BasicBlock *DefaultBB;
3549 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3550 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3551 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3552 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3555 if (!Cond->getType()->isIntegerTy())
3556 return Error(CondLoc, "switch condition must have integer type");
3558 // Parse the jump table pairs.
3559 SmallPtrSet<Value*, 32> SeenCases;
3560 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3561 while (Lex.getKind() != lltok::rsquare) {
3565 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3566 ParseToken(lltok::comma, "expected ',' after case value") ||
3567 ParseTypeAndBasicBlock(DestBB, PFS))
3570 if (!SeenCases.insert(Constant))
3571 return Error(CondLoc, "duplicate case value in switch");
3572 if (!isa<ConstantInt>(Constant))
3573 return Error(CondLoc, "case value is not a constant integer");
3575 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3578 Lex.Lex(); // Eat the ']'.
3580 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3581 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3582 SI->addCase(Table[i].first, Table[i].second);
3589 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3590 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3593 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3594 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3595 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3598 if (!Address->getType()->isPointerTy())
3599 return Error(AddrLoc, "indirectbr address must have pointer type");
3601 // Parse the destination list.
3602 SmallVector<BasicBlock*, 16> DestList;
3604 if (Lex.getKind() != lltok::rsquare) {
3606 if (ParseTypeAndBasicBlock(DestBB, PFS))
3608 DestList.push_back(DestBB);
3610 while (EatIfPresent(lltok::comma)) {
3611 if (ParseTypeAndBasicBlock(DestBB, PFS))
3613 DestList.push_back(DestBB);
3617 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3620 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3621 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3622 IBI->addDestination(DestList[i]);
3629 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3630 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3631 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3632 LocTy CallLoc = Lex.getLoc();
3633 AttrBuilder RetAttrs, FnAttrs;
3634 std::vector<unsigned> FwdRefAttrGrps;
3637 Type *RetType = nullptr;
3640 SmallVector<ParamInfo, 16> ArgList;
3642 BasicBlock *NormalBB, *UnwindBB;
3643 if (ParseOptionalCallingConv(CC) ||
3644 ParseOptionalReturnAttrs(RetAttrs) ||
3645 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3646 ParseValID(CalleeID) ||
3647 ParseParameterList(ArgList, PFS) ||
3648 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3650 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3651 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3652 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3653 ParseTypeAndBasicBlock(UnwindBB, PFS))
3656 // If RetType is a non-function pointer type, then this is the short syntax
3657 // for the call, which means that RetType is just the return type. Infer the
3658 // rest of the function argument types from the arguments that are present.
3659 PointerType *PFTy = nullptr;
3660 FunctionType *Ty = nullptr;
3661 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3662 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3663 // Pull out the types of all of the arguments...
3664 std::vector<Type*> ParamTypes;
3665 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3666 ParamTypes.push_back(ArgList[i].V->getType());
3668 if (!FunctionType::isValidReturnType(RetType))
3669 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3671 Ty = FunctionType::get(RetType, ParamTypes, false);
3672 PFTy = PointerType::getUnqual(Ty);
3675 // Look up the callee.
3677 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3679 // Set up the Attribute for the function.
3680 SmallVector<AttributeSet, 8> Attrs;
3681 if (RetAttrs.hasAttributes())
3682 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3683 AttributeSet::ReturnIndex,
3686 SmallVector<Value*, 8> Args;
3688 // Loop through FunctionType's arguments and ensure they are specified
3689 // correctly. Also, gather any parameter attributes.
3690 FunctionType::param_iterator I = Ty->param_begin();
3691 FunctionType::param_iterator E = Ty->param_end();
3692 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3693 Type *ExpectedTy = nullptr;
3696 } else if (!Ty->isVarArg()) {
3697 return Error(ArgList[i].Loc, "too many arguments specified");
3700 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3701 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3702 getTypeString(ExpectedTy) + "'");
3703 Args.push_back(ArgList[i].V);
3704 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3705 AttrBuilder B(ArgList[i].Attrs, i + 1);
3706 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3711 return Error(CallLoc, "not enough parameters specified for call");
3713 if (FnAttrs.hasAttributes())
3714 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3715 AttributeSet::FunctionIndex,
3718 // Finish off the Attribute and check them
3719 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3721 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3722 II->setCallingConv(CC);
3723 II->setAttributes(PAL);
3724 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3730 /// ::= 'resume' TypeAndValue
3731 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3732 Value *Exn; LocTy ExnLoc;
3733 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3736 ResumeInst *RI = ResumeInst::Create(Exn);
3741 //===----------------------------------------------------------------------===//
3742 // Binary Operators.
3743 //===----------------------------------------------------------------------===//
3746 /// ::= ArithmeticOps TypeAndValue ',' Value
3748 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3749 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3750 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3751 unsigned Opc, unsigned OperandType) {
3752 LocTy Loc; Value *LHS, *RHS;
3753 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3754 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3755 ParseValue(LHS->getType(), RHS, PFS))
3759 switch (OperandType) {
3760 default: llvm_unreachable("Unknown operand type!");
3761 case 0: // int or FP.
3762 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3763 LHS->getType()->isFPOrFPVectorTy();
3765 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3766 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3770 return Error(Loc, "invalid operand type for instruction");
3772 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3777 /// ::= ArithmeticOps TypeAndValue ',' Value {
3778 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3780 LocTy Loc; Value *LHS, *RHS;
3781 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3782 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3783 ParseValue(LHS->getType(), RHS, PFS))
3786 if (!LHS->getType()->isIntOrIntVectorTy())
3787 return Error(Loc,"instruction requires integer or integer vector operands");
3789 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3795 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3796 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3797 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3799 // Parse the integer/fp comparison predicate.
3803 if (ParseCmpPredicate(Pred, Opc) ||
3804 ParseTypeAndValue(LHS, Loc, PFS) ||
3805 ParseToken(lltok::comma, "expected ',' after compare value") ||
3806 ParseValue(LHS->getType(), RHS, PFS))
3809 if (Opc == Instruction::FCmp) {
3810 if (!LHS->getType()->isFPOrFPVectorTy())
3811 return Error(Loc, "fcmp requires floating point operands");
3812 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3814 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3815 if (!LHS->getType()->isIntOrIntVectorTy() &&
3816 !LHS->getType()->getScalarType()->isPointerTy())
3817 return Error(Loc, "icmp requires integer operands");
3818 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3823 //===----------------------------------------------------------------------===//
3824 // Other Instructions.
3825 //===----------------------------------------------------------------------===//
3829 /// ::= CastOpc TypeAndValue 'to' Type
3830 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3834 Type *DestTy = nullptr;
3835 if (ParseTypeAndValue(Op, Loc, PFS) ||
3836 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3840 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3841 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3842 return Error(Loc, "invalid cast opcode for cast from '" +
3843 getTypeString(Op->getType()) + "' to '" +
3844 getTypeString(DestTy) + "'");
3846 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3851 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3852 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3854 Value *Op0, *Op1, *Op2;
3855 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3856 ParseToken(lltok::comma, "expected ',' after select condition") ||
3857 ParseTypeAndValue(Op1, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after select value") ||
3859 ParseTypeAndValue(Op2, PFS))
3862 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3863 return Error(Loc, Reason);
3865 Inst = SelectInst::Create(Op0, Op1, Op2);
3870 /// ::= 'va_arg' TypeAndValue ',' Type
3871 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3873 Type *EltTy = nullptr;
3875 if (ParseTypeAndValue(Op, PFS) ||
3876 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3877 ParseType(EltTy, TypeLoc))
3880 if (!EltTy->isFirstClassType())
3881 return Error(TypeLoc, "va_arg requires operand with first class type");
3883 Inst = new VAArgInst(Op, EltTy);
3887 /// ParseExtractElement
3888 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3889 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3892 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3893 ParseToken(lltok::comma, "expected ',' after extract value") ||
3894 ParseTypeAndValue(Op1, PFS))
3897 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3898 return Error(Loc, "invalid extractelement operands");
3900 Inst = ExtractElementInst::Create(Op0, Op1);
3904 /// ParseInsertElement
3905 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3906 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3908 Value *Op0, *Op1, *Op2;
3909 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3910 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3911 ParseTypeAndValue(Op1, PFS) ||
3912 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3913 ParseTypeAndValue(Op2, PFS))
3916 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3917 return Error(Loc, "invalid insertelement operands");
3919 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3923 /// ParseShuffleVector
3924 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3925 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3927 Value *Op0, *Op1, *Op2;
3928 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3929 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3930 ParseTypeAndValue(Op1, PFS) ||
3931 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3932 ParseTypeAndValue(Op2, PFS))
3935 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3936 return Error(Loc, "invalid shufflevector operands");
3938 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3943 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3944 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3945 Type *Ty = nullptr; LocTy TypeLoc;
3948 if (ParseType(Ty, TypeLoc) ||
3949 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3950 ParseValue(Ty, Op0, PFS) ||
3951 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3952 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3953 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3956 bool AteExtraComma = false;
3957 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3959 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3961 if (!EatIfPresent(lltok::comma))
3964 if (Lex.getKind() == lltok::MetadataVar) {
3965 AteExtraComma = true;
3969 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3970 ParseValue(Ty, Op0, PFS) ||
3971 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3972 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3973 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3977 if (!Ty->isFirstClassType())
3978 return Error(TypeLoc, "phi node must have first class type");
3980 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3981 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3982 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3984 return AteExtraComma ? InstExtraComma : InstNormal;
3988 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3990 /// ::= 'catch' TypeAndValue
3992 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3993 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3994 Type *Ty = nullptr; LocTy TyLoc;
3995 Value *PersFn; LocTy PersFnLoc;
3997 if (ParseType(Ty, TyLoc) ||
3998 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3999 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4002 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4003 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4005 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4006 LandingPadInst::ClauseType CT;
4007 if (EatIfPresent(lltok::kw_catch))
4008 CT = LandingPadInst::Catch;
4009 else if (EatIfPresent(lltok::kw_filter))
4010 CT = LandingPadInst::Filter;
4012 return TokError("expected 'catch' or 'filter' clause type");
4014 Value *V; LocTy VLoc;
4015 if (ParseTypeAndValue(V, VLoc, PFS)) {
4020 // A 'catch' type expects a non-array constant. A filter clause expects an
4022 if (CT == LandingPadInst::Catch) {
4023 if (isa<ArrayType>(V->getType()))
4024 Error(VLoc, "'catch' clause has an invalid type");
4026 if (!isa<ArrayType>(V->getType()))
4027 Error(VLoc, "'filter' clause has an invalid type");
4038 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4039 /// ParameterList OptionalAttrs
4040 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4041 /// ParameterList OptionalAttrs
4042 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4043 /// ParameterList OptionalAttrs
4044 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4045 CallInst::TailCallKind TCK) {
4046 AttrBuilder RetAttrs, FnAttrs;
4047 std::vector<unsigned> FwdRefAttrGrps;
4050 Type *RetType = nullptr;
4053 SmallVector<ParamInfo, 16> ArgList;
4054 LocTy CallLoc = Lex.getLoc();
4056 if ((TCK != CallInst::TCK_None &&
4057 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4058 ParseOptionalCallingConv(CC) ||
4059 ParseOptionalReturnAttrs(RetAttrs) ||
4060 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4061 ParseValID(CalleeID) ||
4062 ParseParameterList(ArgList, PFS) ||
4063 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4067 // If RetType is a non-function pointer type, then this is the short syntax
4068 // for the call, which means that RetType is just the return type. Infer the
4069 // rest of the function argument types from the arguments that are present.
4070 PointerType *PFTy = nullptr;
4071 FunctionType *Ty = nullptr;
4072 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4073 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4074 // Pull out the types of all of the arguments...
4075 std::vector<Type*> ParamTypes;
4076 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4077 ParamTypes.push_back(ArgList[i].V->getType());
4079 if (!FunctionType::isValidReturnType(RetType))
4080 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4082 Ty = FunctionType::get(RetType, ParamTypes, false);
4083 PFTy = PointerType::getUnqual(Ty);
4086 // Look up the callee.
4088 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4090 // Set up the Attribute for the function.
4091 SmallVector<AttributeSet, 8> Attrs;
4092 if (RetAttrs.hasAttributes())
4093 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4094 AttributeSet::ReturnIndex,
4097 SmallVector<Value*, 8> Args;
4099 // Loop through FunctionType's arguments and ensure they are specified
4100 // correctly. Also, gather any parameter attributes.
4101 FunctionType::param_iterator I = Ty->param_begin();
4102 FunctionType::param_iterator E = Ty->param_end();
4103 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4104 Type *ExpectedTy = nullptr;
4107 } else if (!Ty->isVarArg()) {
4108 return Error(ArgList[i].Loc, "too many arguments specified");
4111 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4112 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4113 getTypeString(ExpectedTy) + "'");
4114 Args.push_back(ArgList[i].V);
4115 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4116 AttrBuilder B(ArgList[i].Attrs, i + 1);
4117 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4122 return Error(CallLoc, "not enough parameters specified for call");
4124 if (FnAttrs.hasAttributes())
4125 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4126 AttributeSet::FunctionIndex,
4129 // Finish off the Attribute and check them
4130 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4132 CallInst *CI = CallInst::Create(Callee, Args);
4133 CI->setTailCallKind(TCK);
4134 CI->setCallingConv(CC);
4135 CI->setAttributes(PAL);
4136 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4141 //===----------------------------------------------------------------------===//
4142 // Memory Instructions.
4143 //===----------------------------------------------------------------------===//
4146 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4147 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4148 Value *Size = nullptr;
4150 unsigned Alignment = 0;
4153 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4155 if (ParseType(Ty)) return true;
4157 bool AteExtraComma = false;
4158 if (EatIfPresent(lltok::comma)) {
4159 if (Lex.getKind() == lltok::kw_align) {
4160 if (ParseOptionalAlignment(Alignment)) return true;
4161 } else if (Lex.getKind() == lltok::MetadataVar) {
4162 AteExtraComma = true;
4164 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4165 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4170 if (Size && !Size->getType()->isIntegerTy())
4171 return Error(SizeLoc, "element count must have integer type");
4173 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4174 AI->setUsedWithInAlloca(IsInAlloca);
4176 return AteExtraComma ? InstExtraComma : InstNormal;
4180 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4181 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4182 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4183 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4184 Value *Val; LocTy Loc;
4185 unsigned Alignment = 0;
4186 bool AteExtraComma = false;
4187 bool isAtomic = false;
4188 AtomicOrdering Ordering = NotAtomic;
4189 SynchronizationScope Scope = CrossThread;
4191 if (Lex.getKind() == lltok::kw_atomic) {
4196 bool isVolatile = false;
4197 if (Lex.getKind() == lltok::kw_volatile) {
4202 if (ParseTypeAndValue(Val, Loc, PFS) ||
4203 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4204 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4207 if (!Val->getType()->isPointerTy() ||
4208 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4209 return Error(Loc, "load operand must be a pointer to a first class type");
4210 if (isAtomic && !Alignment)
4211 return Error(Loc, "atomic load must have explicit non-zero alignment");
4212 if (Ordering == Release || Ordering == AcquireRelease)
4213 return Error(Loc, "atomic load cannot use Release ordering");
4215 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4216 return AteExtraComma ? InstExtraComma : InstNormal;
4221 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4222 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4223 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4224 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4225 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4226 unsigned Alignment = 0;
4227 bool AteExtraComma = false;
4228 bool isAtomic = false;
4229 AtomicOrdering Ordering = NotAtomic;
4230 SynchronizationScope Scope = CrossThread;
4232 if (Lex.getKind() == lltok::kw_atomic) {
4237 bool isVolatile = false;
4238 if (Lex.getKind() == lltok::kw_volatile) {
4243 if (ParseTypeAndValue(Val, Loc, PFS) ||
4244 ParseToken(lltok::comma, "expected ',' after store operand") ||
4245 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4246 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4247 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4250 if (!Ptr->getType()->isPointerTy())
4251 return Error(PtrLoc, "store operand must be a pointer");
4252 if (!Val->getType()->isFirstClassType())
4253 return Error(Loc, "store operand must be a first class value");
4254 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4255 return Error(Loc, "stored value and pointer type do not match");
4256 if (isAtomic && !Alignment)
4257 return Error(Loc, "atomic store must have explicit non-zero alignment");
4258 if (Ordering == Acquire || Ordering == AcquireRelease)
4259 return Error(Loc, "atomic store cannot use Acquire ordering");
4261 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4262 return AteExtraComma ? InstExtraComma : InstNormal;
4266 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4267 /// 'singlethread'? AtomicOrdering AtomicOrdering
4268 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4269 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4270 bool AteExtraComma = false;
4271 AtomicOrdering SuccessOrdering = NotAtomic;
4272 AtomicOrdering FailureOrdering = NotAtomic;
4273 SynchronizationScope Scope = CrossThread;
4274 bool isVolatile = false;
4276 if (EatIfPresent(lltok::kw_volatile))
4279 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4280 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4281 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4282 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4283 ParseTypeAndValue(New, NewLoc, PFS) ||
4284 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4285 ParseOrdering(FailureOrdering))
4288 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4289 return TokError("cmpxchg cannot be unordered");
4290 if (SuccessOrdering < FailureOrdering)
4291 return TokError("cmpxchg must be at least as ordered on success as failure");
4292 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4293 return TokError("cmpxchg failure ordering cannot include release semantics");
4294 if (!Ptr->getType()->isPointerTy())
4295 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4296 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4297 return Error(CmpLoc, "compare value and pointer type do not match");
4298 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4299 return Error(NewLoc, "new value and pointer type do not match");
4300 if (!New->getType()->isIntegerTy())
4301 return Error(NewLoc, "cmpxchg operand must be an integer");
4302 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4303 if (Size < 8 || (Size & (Size - 1)))
4304 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4307 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4308 FailureOrdering, Scope);
4309 CXI->setVolatile(isVolatile);
4311 return AteExtraComma ? InstExtraComma : InstNormal;
4315 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4316 /// 'singlethread'? AtomicOrdering
4317 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4318 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4319 bool AteExtraComma = false;
4320 AtomicOrdering Ordering = NotAtomic;
4321 SynchronizationScope Scope = CrossThread;
4322 bool isVolatile = false;
4323 AtomicRMWInst::BinOp Operation;
4325 if (EatIfPresent(lltok::kw_volatile))
4328 switch (Lex.getKind()) {
4329 default: return TokError("expected binary operation in atomicrmw");
4330 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4331 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4332 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4333 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4334 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4335 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4336 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4337 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4338 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4339 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4340 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4342 Lex.Lex(); // Eat the operation.
4344 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4345 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4346 ParseTypeAndValue(Val, ValLoc, PFS) ||
4347 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4350 if (Ordering == Unordered)
4351 return TokError("atomicrmw cannot be unordered");
4352 if (!Ptr->getType()->isPointerTy())
4353 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4354 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4355 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4356 if (!Val->getType()->isIntegerTy())
4357 return Error(ValLoc, "atomicrmw operand must be an integer");
4358 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4359 if (Size < 8 || (Size & (Size - 1)))
4360 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4363 AtomicRMWInst *RMWI =
4364 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4365 RMWI->setVolatile(isVolatile);
4367 return AteExtraComma ? InstExtraComma : InstNormal;
4371 /// ::= 'fence' 'singlethread'? AtomicOrdering
4372 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4373 AtomicOrdering Ordering = NotAtomic;
4374 SynchronizationScope Scope = CrossThread;
4375 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4378 if (Ordering == Unordered)
4379 return TokError("fence cannot be unordered");
4380 if (Ordering == Monotonic)
4381 return TokError("fence cannot be monotonic");
4383 Inst = new FenceInst(Context, Ordering, Scope);
4387 /// ParseGetElementPtr
4388 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4389 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4390 Value *Ptr = nullptr;
4391 Value *Val = nullptr;
4394 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4396 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4398 Type *BaseType = Ptr->getType();
4399 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4400 if (!BasePointerType)
4401 return Error(Loc, "base of getelementptr must be a pointer");
4403 SmallVector<Value*, 16> Indices;
4404 bool AteExtraComma = false;
4405 while (EatIfPresent(lltok::comma)) {
4406 if (Lex.getKind() == lltok::MetadataVar) {
4407 AteExtraComma = true;
4410 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4411 if (!Val->getType()->getScalarType()->isIntegerTy())
4412 return Error(EltLoc, "getelementptr index must be an integer");
4413 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4414 return Error(EltLoc, "getelementptr index type missmatch");
4415 if (Val->getType()->isVectorTy()) {
4416 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4417 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4418 if (ValNumEl != PtrNumEl)
4419 return Error(EltLoc,
4420 "getelementptr vector index has a wrong number of elements");
4422 Indices.push_back(Val);
4425 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4426 return Error(Loc, "base element of getelementptr must be sized");
4428 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4429 return Error(Loc, "invalid getelementptr indices");
4430 Inst = GetElementPtrInst::Create(Ptr, Indices);
4432 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4433 return AteExtraComma ? InstExtraComma : InstNormal;
4436 /// ParseExtractValue
4437 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4438 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4439 Value *Val; LocTy Loc;
4440 SmallVector<unsigned, 4> Indices;
4442 if (ParseTypeAndValue(Val, Loc, PFS) ||
4443 ParseIndexList(Indices, AteExtraComma))
4446 if (!Val->getType()->isAggregateType())
4447 return Error(Loc, "extractvalue operand must be aggregate type");
4449 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4450 return Error(Loc, "invalid indices for extractvalue");
4451 Inst = ExtractValueInst::Create(Val, Indices);
4452 return AteExtraComma ? InstExtraComma : InstNormal;
4455 /// ParseInsertValue
4456 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4457 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4458 Value *Val0, *Val1; LocTy Loc0, Loc1;
4459 SmallVector<unsigned, 4> Indices;
4461 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4462 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4463 ParseTypeAndValue(Val1, Loc1, PFS) ||
4464 ParseIndexList(Indices, AteExtraComma))
4467 if (!Val0->getType()->isAggregateType())
4468 return Error(Loc0, "insertvalue operand must be aggregate type");
4470 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4471 return Error(Loc0, "invalid indices for insertvalue");
4472 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4473 return AteExtraComma ? InstExtraComma : InstNormal;
4476 //===----------------------------------------------------------------------===//
4477 // Embedded metadata.
4478 //===----------------------------------------------------------------------===//
4480 /// ParseMDNodeVector
4481 /// ::= Element (',' Element)*
4483 /// ::= 'null' | TypeAndValue
4484 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4485 PerFunctionState *PFS) {
4486 // Check for an empty list.
4487 if (Lex.getKind() == lltok::rbrace)
4491 // Null is a special case since it is typeless.
4492 if (EatIfPresent(lltok::kw_null)) {
4493 Elts.push_back(nullptr);
4498 if (ParseTypeAndValue(V, PFS)) return true;
4500 } while (EatIfPresent(lltok::comma));